示例#1
0
 def test_newpub(self):
     old = RSA.load_pub_key(self.pubkey)
     new = RSA.new_pub_key(old.pub())
     self.assertTrue(new.check_key())
     self.assertEqual(len(new), 1024)
     # aka 65537 aka 0xf4
     self.assertEqual(new.e, b'\000\000\000\003\001\000\001')
示例#2
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())
示例#3
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
示例#4
0
    def test_sign_and_verify(self):
        """
        Testing signing and verifying digests
        """
        algos = {'sha1': '',
                 'ripemd160': '',
                 'md5': ''}

        if m2.OPENSSL_VERSION_NUMBER >= 0x90800F:
            algos['sha224'] = ''
            algos['sha256'] = ''
            algos['sha384'] = ''
            algos['sha512'] = ''

        message = b"This is the message string"
        digest = hashlib.sha1(message).digest()
        rsa = RSA.load_key(self.privkey)
        rsa2 = RSA.load_pub_key(self.pubkey)
        for algo in algos.keys():
            signature = rsa.sign(digest, algo)
            # assert signature == algos[algo],
            #     'mismatched signature with algorithm %s:
            #     signature=%s' % (algo, signature)
            verify = rsa2.verify(digest, signature, algo)
            self.assertEqual(verify, 1,
                             'verification failed with algorithm %s' % algo)
示例#5
0
def m2c_key(arg1, arg2):
    try:
        rsa = RSA.gen_key(1024, 3, lambda *agr:None)
        pub_bio = BIO.MemoryBuffer()
        priv_bio = BIO.MemoryBuffer()

        rsa.save_pub_key_bio(pub_bio)
        rsa.save_key_bio(priv_bio, None)
        
        pub_file = arg1 
       # pub_file = arg1 + 'pub.pem'
        private_file = arg2 
       # private_file = arg2 + 'private.pem'
        open(pub_file,'w').write(pub_bio.read_all())
        open(private_file,'w').write(priv_bio.read_all())

        pub_key = RSA.load_pub_key(pub_file)
        priv_key = RSA.load_key(private_file)

        message = 'opzoon'
  
        encrypted = pub_key.public_encrypt(message, RSA.pkcs1_padding)
        decrypted = priv_key.private_decrypt(encrypted, RSA.pkcs1_padding)

        if decrypted==message:
            #os.popen("rm -rf m2crypto_gen_key.py")
            pass
        else:
            os.popen("rm -rf *.pem")
            print "Key generation failed,please try again!"
            raise Exception("Key generation failed,please try again!")
    except Exception,e:
        os.popen("rm -rf *.pem")
        raise Exception("Key generation failed,please try again!")
示例#6
0
  def _LoadOurCertificate(self):
    """Loads an RSA key from the certificate.

    If no certificate is found, or it is invalid, we make a new random RSA key,
    and store it as our certificate.

    Returns:
      An RSA key - either from the certificate or a new random key.
    """
    try:
      # This is our private key - make sure it has no password set.
      rsa = RSA.load_key_string(str(self.private_key), callback=lambda x: "")
      self._ParseRSAKey(rsa)

      logging.info("Starting client %s", self.common_name)
    except (X509.X509Error, RSA.RSAError):
      # 65537 is the standard value for e
      rsa = RSA.gen_key(self.BITS, 65537, lambda: None)

      self._ParseRSAKey(rsa)
      logging.info("Client pending enrolment %s", self.common_name)

      # Make new keys
      pk = EVP.PKey()
      pk.assign_rsa(rsa)

      # Save the keys
      self.SavePrivateKey(pk)

    return rsa
示例#7
0
def read_keys():
    global P_K_enc, P_K_shop, P_ca, K_K_enc
    try:
        """key = open('./keys/P_enc--loyaltyEncryptionPublic.key').read()
        P_K_enc = PublicKey.RSA.importKey(key)    
        key = open('./keys/K_enc--loyaltyEncryptionPrivate.key').read()
        P_K_enc = PublicKey.RSA.importKey(key)  """

        pub = RSA2.load_pub_key("./keys/P_enc--loyaltyEncryptionPublic.key")
        priv = RSA2.load_key("./keys/K_enc--loyaltyEncryptionPrivate.key")
        P_K_enc = (pub, priv)

        key = open('./keys/P_CA--CAPublicKey.key').read()
        P_ca = PublicKey.RSA.importKey(key)
        #key = open('./keys/Attrapez-les-tous_RSAprivate.key').read()
        #P_K_shop = PublicKey.RSA.importKey(key)
        P_K_shop = RSA2.load_key("./keys/Attrapez-les-tous_RSAprivate.key")
    except IOError:
        print """
    Need the files:
    ./keys/P_enc--loyaltyEncryptionPublic.key
    ./keys/K_enc--loyaltyEncryptionPrivate.key
    ./keys/P_CA--CAPublicKey.key  
    ./keys/Attrapez-les-tous_RSAprivate.key  
    """
        exit(-1)
示例#8
0
def main(keylen, hashalg):
    global rsa, dgst     # this exists ONLY for speed testing
    
    Rand.load_file('randpool.dat', -1) 
        
    pvtkeyfilename = 'rsa%dpvtkey.pem' % (keylen)
    pubkeyfilename = 'rsa%dpubkey.pem' % (keylen)  
    
    if makenewkey:
        print '  making and saving a new key'
        rsa = RSA.gen_key(keylen, exponent)
        rsa.save_key(pvtkeyfilename, None )  # no pswd callback
        rsa.save_pub_key(pubkeyfilename)
    else:
        print '  loading an existing key'
        rsa = RSA.load_key(pvtkeyfilename)
    print '  rsa key length:', len(rsa)
    
    if not rsa.check_key():
        raise 'key is not initialised'

    # since we are testing signing and verification, let's not 
    # be fussy about the digest.  Just make one.
    md = EVP.MessageDigest(hashalg)
    md.update('can you spell subliminal channel?')
    dgst = md.digest()
    print '  hash algorithm: %s' % hashalg
    if showdigest:
        print '  %s digest: \n%s' % (hashalg, base64.encodestring(dgst))
    
    test(rsa, dgst)
#    test_asn1(rsa, dgst)
    test_speed(rsa, dgst)
    Rand.save_file('randpool.dat')
示例#9
0
    def __saveResponse(self, recv):
        # decode from application/x-www-form-urlencoded
        self.__response = {}
        
        for pair in urlparse.parse_qsl(recv):
            if pair[0] in self.__response:
                raise TestFailed("Received several fields with key %s"%(pair[0]))

            self.__response[pair[0]] = pair[1]

        print ""
        print "Response from server:"
        for k, v in self.__response.iteritems():
            print "%s=%s"%(k, v)

        # check signature of response

        # "openssl dgst -sha1 -verify ../resources/server_publickey.pem 
        #    -signature signature.txt message.txt"

        sortedKeys = sorted(self.__response.keys())
        sortedTuples = [(key, self.__response[key]) for key in sortedKeys]

        msg = ""
        for key in sortedKeys:
            # ; in value must be replaced with ;;
            if not 'signature' in key:
                msg += "%s=%s;"%(key, self.__response[key].replace(';',';;'))
        
        if 's-t-256-256_signature-one' in self.__response:
            signatureBytes = binascii.a2b_hex(self.__response['s-t-256-256_signature-one'])
            
            keyPath = os.path.join(os.path.dirname(__file__), 'server_publickey.pem')
            pkey = RSA.load_pub_key(keyPath)
            
            result = None
            try:
                result = pkey.verify(hashlib.sha1(msg.encode('utf-8')).digest(), 
                                            signatureBytes, algo='sha1')
            except Exception as e:
                raise TestFailed("Response sha1 validation failed: " + str(e))

            if not result:
                raise TestFailed("Response sha1 validation failed.")

        if 's-t-256-256_signature-two' in self.__response:
            signatureBytes = binascii.a2b_hex(self.__response['s-t-256-256_signature-two'])
            
            keyPath = os.path.join(os.path.dirname(__file__), 'server_publickey.pem')
            pkey = RSA.load_pub_key(keyPath)

            result = None
            try:
                result = pkey.verify(hashlib.sha512(msg.encode('utf-8')).digest(), 
                                            signatureBytes, algo='sha512')
            except Exception as e:
                raise TestFailed("Response sha512 validation failed: " + str(e))

            if not result:
                raise TestFailed("Response sha512 validation failed.")
    def __init__(self, pub_key, priv_key, ca_cert, passphrase):
        """ Create a Certification Subject Object.

        Arguments:
            pub_key: file system path of the Subject's Public Key.
            priv_key: file system path of the Subject's Private Key (encrypted).
            ca_cert: file system path of the Certification Authority's Certificate.
            passphrase: Symmetric key for priv_key decryption.
        """
        def getPassphrase(*args):
            """ Callback for private key decrypting.
            """
            return str(passphrase.encode('utf-8'))

        self.pub_key = RSA.load_pub_key(pub_key.encode('utf-8'))
        self.priv_key = RSA.load_key(priv_key.encode('utf-8'), getPassphrase)
        self.ca_cert = X509.load_cert(ca_cert.decode('utf-8'))

        # Private key for signing
        self.signEVP = EVP.PKey()
        self.signEVP.assign_rsa(self.priv_key)

        # CA Key for validations
        self.verifyEVP = EVP.PKey()
        self.verifyEVP.assign_rsa(self.ca_cert.get_pubkey().get_rsa())
示例#11
0
 def action_validate(self, cr, uid, ids, context=None):
     if context is None:
         context = {}
     pairkeys = self.read(cr, uid, ids, ["key", "pub"], context=context)
     confirm_ids = []
     for pk in pairkeys:
         # Check public key
         try:
             PUB = BIO.MemoryBuffer(pk["pub"].encode("ascii"))
             RSA.load_pub_key_bio(PUB)
             pub = True
         except:
             pub = False
         # Check private key
         try:
             RSA.load_key_string(pk["key"].encode("ascii"))
             key = True
         except:
             key = False
         if key or pub:
             confirm_ids.append(pk["id"])
         else:
             raise osv.except_osv(
                 _("Invalid action !"),
                 _("Cannot confirm invalid pairkeys. You need provide private and public keys in PEM format."),
             )
     self.write(cr, uid, confirm_ids, {"state": "confirmed"}, context=context)
     return True
示例#12
0
 def action_validate(self, cr, uid, ids, context=None):
     if context is None:
         context = {}
     pairkeys = self.read(cr, uid, ids, ['key', 'pub'], context=context)
     confirm_ids = []
     for pk in pairkeys:
         # Check public key
         try:
             PUB = BIO.MemoryBuffer(pk['pub'].encode('ascii'))
             RSA.load_pub_key_bio(PUB)
             pub = True
         except:
             pub = False
         # Check private key
         try:
             RSA.load_key_string(pk['key'].encode('ascii'))
             key = True
         except:
             key = False
         if key or pub:
             confirm_ids.append(pk['id'])
         else:
             raise osv.except_osv(_('Invalid action !'),
                                  _('Cannot confirm invalid pairkeys. You need provide private and public keys in PEM format.'))
     return True
示例#13
0
文件: key.py 项目: 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
示例#14
0
    def test_get_rsa(self):
        """
        Testing retrieving the RSA key from the PKey instance.
        """
        rsa = RSA.gen_key(1024, 3, callback=self._gen_callback)
        self.assertIsInstance(rsa, RSA.RSA)
        pkey = EVP.PKey()
        pkey.assign_rsa(rsa)
        rsa2 = pkey.get_rsa()
        self.assertIsInstance(rsa2, RSA.RSA_pub)
        self.assertEqual(rsa.e, rsa2.e)
        self.assertEqual(rsa.n, rsa2.n)
        # FIXME
        # hanging call is
        #     m2.rsa_write_key(self.rsa, bio._ptr(), ciph, callback)s
        # from RSA.py/save_key_bio

        pem = rsa.as_pem(callback=self._pass_callback)
        pem2 = rsa2.as_pem()
        assert pem
        assert pem2
        self.assertNotEqual(pem, pem2)

        message = b'This is the message string'
        digest = hashlib.sha1(message).digest()
        self.assertEqual(rsa.sign(digest), rsa2.sign(digest))

        rsa3 = RSA.gen_key(1024, 3, callback=self._gen_callback)
        self.assertNotEqual(rsa.sign(digest), rsa3.sign(digest))
示例#15
0
def create_rsa_keyring(passphrase_callback, key_size=2048, exponent=65537):
    """ Return a new RSA keyring as tuple (<public key>, <private key>)
    @param passphrase_callback: A Python callable object that is invoked
    during key generation; its usual purpose is to provide visual
    feedback.
    You must load a randpool file before calling this method with
    Rand.load_file('randpool', -1).
    After calling the method, you must save the randpool file with
    Rand.save_file('randpool')
    @type passphrase_callback: Callback

    @param key_size: Key length, in bits
    @type key_size: Integer

    @param exponent: The RSA public exponent
    @type exponent: Integer
    """
    keyring = RSA.gen_key(key_size, exponent)

    privkey_filename = get_secure_filename()
    pubkey_filename = get_secure_filename()

    keyring.save_key(privkey_filename, callback=passphrase_callback)
    keyring.save_pub_key(pubkey_filename)

    privkey = RSA.load_key(privkey_filename, callback=passphrase_callback)
    pubkey = RSA.load_pub_key(pubkey_filename)

    os.unlink(privkey_filename)
    os.unlink(pubkey_filename)

    return (pubkey, privkey)
示例#16
0
 def load_key(self, key):
     # Key can be a file, an string or an RSA object
     if not isinstance(key, RSA.RSA):
         try:
             key = RSA.load_key(key)
         except:
             key = RSA.load_key_string(key)
     self.key = key
     self.pkey = EVP.PKey()
     self.pkey.assign_rsa(key)
示例#17
0
 def test_newpub(self):
     old = RSA.load_pub_key(self.pubkey)
     log.debug('old = %s', old)
     log.debug('old.pub = %s', old.pub())
     new = RSA.new_pub_key(old.pub())
     log.debug('new = %s', new)
     self.assertTrue(new.check_key())
     self.assertEqual(len(new), 1024)
     # aka 65537 aka 0xf4
     self.assertEqual(new.e, '\000\000\000\003\001\000\001')
示例#18
0
文件: rsa.py 项目: SushiTee/teerace
	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)
示例#19
0
    def bogus(self):
        bogus = []
        if self.content:
            try:
                RSA.load_key_string(self.content)
            except Exception:
                bogus.append("Invalid key data")
        else:
            bogus.append("No key data provided")

        return bogus
示例#20
0
    def CreatePKey(self, filename):
        """This function accepts the filename of the key file to write to.
........It write the private key to the specified file name without ciphering it."""

        self.keypair = RSA.gen_key(self.rsakey['KeyLength'],
                                   self.rsakey['PubExponent'],
                                   self.rsakey['keygen_callback'])
        RSA.new_pub_key(self.keypair.pub())
        self.keypair.save_key(filename, cipher=None)
        self.pkey = EVP.PKey(md='sha1')
        self.pkey.assign_rsa(self.keypair)
示例#21
0
文件: crypto.py 项目: 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)
示例#22
0
 def __get_keys(self):
     '''
     Returns a key objects for the master
     '''
     if os.path.exists(self.rsa_path):
         key = RSA.load_key(self.rsa_path)
         log.debug('Loaded master key: {0}'.format(self.rsa_path))
     else:
         log.info('Generating keys: {0}'.format(self.opts['pki_dir']))
         gen_keys(self.opts['pki_dir'], 'master', 4096)
         key = RSA.load_key(self.rsa_path)
     return key
 def _restore_level1(self, newpassword, adminpassword):
     '''
     Restores a lost passwort of an user with security level 1
     The Rescue password is symmetrical encrypted
     '''
     x = self._sym_decrypt(self._private_key_rescue, adminpassword)
     try:
         RSA.load_key_string(x)
     except:
         raise WrongPasswordError("Could not restore Private Key with Admin Password")
     self._private_key = self._sym_encrypt(x, newpassword)
     return True
示例#24
0
 def test_verify_mismatched_algo(self):
     """
     Testing verify to make sure it fails when we use a different
     message digest algorithm
     """
     rsa = RSA.load_key(self.privkey)
     message = "This is the message string"
     digest = sha.sha(message).digest() 
     signature = rsa.sign(digest, 'sha1')
     rsa2 = RSA.load_pub_key(self.pubkey)
     self.assertRaises(RSA.RSAError, rsa.verify, 
                       digest, signature, 'md5')
示例#25
0
 def __get_keys(self):
     """
     Returns a key objects for the master
     """
     if os.path.exists(self.rsa_path):
         key = RSA.load_key(self.rsa_path)
         log.debug("Loaded master key: {0}".format(self.rsa_path))
     else:
         log.info("Generating keys: {0}".format(self.opts["pki_dir"]))
         gen_keys(self.opts["pki_dir"], "master", self.opts["keysize"], self.opts.get("user"))
         key = RSA.load_key(self.rsa_path)
     return key
示例#26
0
文件: test_auth.py 项目: ipanova/pulp
    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)
示例#27
0
文件: crypt.py 项目: atoponce/salt
def gen_keys(keydir, keyname, keysize):
    '''
    Generate a keypair for use with salt
    '''
    base = os.path.join(keydir, keyname)
    priv = '{0}.pem'.format(base)
    pub = '{0}.pub'.format(base)
    gen = RSA.gen_key(keysize, 1)
    gen.save_key(priv, callback=foo_pass)
    gen.save_pub_key(pub)
    key = RSA.load_key(priv, callback=foo_pass)
    os.chmod(priv, 256)
    return key
示例#28
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]
示例#29
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
示例#30
0
文件: crypt.py 项目: jhutchins/salt
def gen_keys(keydir, keyname, keysize):
    """
    Generate a keypair for use with salt
    """
    base = os.path.join(keydir, keyname)
    priv = "{0}.pem".format(base)
    pub = "{0}.pub".format(base)
    gen = RSA.gen_key(keysize, 1)
    cumask = os.umask(191)
    gen.save_key(priv, callback=foo_pass)
    os.umask(cumask)
    gen.save_pub_key(pub)
    key = RSA.load_key(priv, callback=foo_pass)
    os.chmod(priv, 256)
    return key
示例#31
0
    def test_load_key_string_pubkey(self):
        """
        Testing creating a PKey instance from PEM string.
        """
        rsa = RSA.gen_key(1024, 3, callback=self._gen_callback)
        self.assertIsInstance(rsa, RSA.RSA)

        rsa_pem = BIO.MemoryBuffer()
        rsa.save_pub_key_bio(rsa_pem)
        pkey = EVP.load_key_string_pubkey(rsa_pem.read())
        rsa2 = pkey.get_rsa()
        self.assertIsInstance(rsa2, RSA.RSA_pub)
        self.assertEqual(rsa.e, rsa2.e)
        self.assertEqual(rsa.n, rsa2.n)
        pem = rsa.as_pem(callback=self._pass_callback)
        pem2 = rsa2.as_pem()
        assert pem
        assert pem2
        self.assertNotEqual(pem, pem2)
示例#32
0
def createKey():
    """
    Creates a private and public key
    
    @rtype: dict
    @returns: pair of keys
    """
    # try to create key
    try:
        keys = RSA.gen_key(1024, 65537, lambda x: None)
    
    # issue to save keys: report
    except Exception:
        print "Cannot create key. Aborting."
    
    return { 
            "private": keys,
            "public": keys.pub()
    }
示例#33
0
 def _getRSA():
     rc, stdout, stderr = self.execute(
         args=(
             self.command.get('openssl'),
             'pkcs12',
             '-in', (
                 FileLocations.OVIRT_ENGINE_PKI_ENGINE_STORE
             ),
             '-passin', 'pass:%s' % self.environment[
                 oenginecons.PKIEnv.STORE_PASS
             ],
             '-nocerts',
             '-nodes',
         ),
         logStreams=False,
     )
     return RSA.load_key_string(
         str('\n'.join(stdout))
     )
示例#34
0
文件: master.py 项目: fatbox/salt
    def __verify_minion(self, id_, token):
        '''
        Take a minion id and a string signed with the minion private key
        The string needs to verify as 'salt' with the minion public key
        '''
        pub_path = os.path.join(self.opts['pki_dir'], 'minions', id_)
        with open(pub_path, 'r') as fp_:
            minion_pub = fp_.read()
        fd_, tmp_pub = tempfile.mkstemp()
        os.close(fd_)
        with open(tmp_pub, 'w+') as fp_:
            fp_.write(minion_pub)

        pub = None
        try:
            pub = RSA.load_pub_key(tmp_pub)
        except RSA.RSAError, e:
            log.error('Unable to load temporary public key "{0}": {1}'.format(
                tmp_pub, e))
示例#35
0
    def make_proxycert(self, eecert):
        proxycert = X509.X509()
        pk2 = EVP.PKey()
        proxykey = RSA.gen_key(1024, 65537, self.callback)
        pk2.assign_rsa(proxykey)
        proxycert.set_pubkey(pk2)
        proxycert.set_version(2)
        not_before = ASN1.ASN1_UTCTIME()
        not_after = ASN1.ASN1_UTCTIME()
        not_before.set_time(int(time.time()))
        offset = 12 * 3600
        not_after.set_time(int(time.time()) + offset)
        proxycert.set_not_before(not_before)
        proxycert.set_not_after(not_after)
        proxycert.set_issuer_name(eecert.get_subject())
        proxycert.set_serial_number(12345678)
        proxy_subject_name = X509.X509_Name()
        issuer_name_string = eecert.get_subject().as_text()
        seq = issuer_name_string.split(",")

        subject_name = X509.X509_Name()
        for entry in seq:
            l = entry.split("=")
            subject_name.add_entry_by_txt(field=l[0].strip(),
                                          type=ASN1.MBSTRING_ASC,
                                          entry=l[1],
                                          len=-1,
                                          loc=-1,
                                          set=0)

        subject_name.add_entry_by_txt(field="CN",
                                      type=ASN1.MBSTRING_ASC,
                                      entry="Proxy",
                                      len=-1,
                                      loc=-1,
                                      set=0)

        proxycert.set_subject_name(subject_name)
        pci_ext = X509.new_extension("proxyCertInfo",
                                     "critical,language:Inherit all",
                                     1)  # XXX leaks 8 bytes
        proxycert.add_ext(pci_ext)
        return proxycert
示例#36
0
 def CrearClavePrivada(self, filename="privada.key", key_length=4096, 
                             pub_exponent=0x10001, passphrase=""):
     "Crea una clave privada (private key)"
     from M2Crypto import RSA, EVP
     
     # only protect if passphrase was given (it will fail otherwise)
     callback = lambda *args, **kwarg: passphrase
     chiper = None if not passphrase else "aes_128_cbc"
     # create the RSA key pair (and save the result to a file):
     rsa_key_pair = RSA.gen_key(key_length, pub_exponent, callback)
     bio = BIO.MemoryBuffer()
     rsa_key_pair.save_key_bio(bio, chiper, callback)
     f = open(filename, "w")
     f.write(bio.read())
     f.close()
     # create a public key to sign the certificate request:
     self.pkey = EVP.PKey(md='sha256')
     self.pkey.assign_rsa(rsa_key_pair)
     return True
示例#37
0
    def verify_merchant_sign_parse_response(self):

        if self.response_dict['resultCode'] == 0:
            res_dict = self.response_dict['resultData']
            # 1.解密签名内容
            # 此处签名为网银+返回的签名
            b64d_sign = base64.b64decode(res_dict['sign'])
            # 对返回的签名用公钥解密得到decrypt_sign_string
            pub_key = RSA.load_pub_key(
                self.pay_account.merchant_wy_rsa_pub_key)
            decrypt_sign_string = pub_key.public_decrypt(
                b64d_sign, RSA.pkcs1_padding)

            # 2.对data进行sha256摘要加密,从而得到一个string来验证签名。
            # data 为网银+返回的data域(尚未解密)
            data = res_dict['data']
            # print data
            sha256_source_sign_string = sha256(data)
            # 3.对比1和2的结果
            if (decrypt_sign_string == sha256_source_sign_string):
                # 验证签名通过
                hex_to_byte = binascii.unhexlify(data)

                # 3DES解密
                plain_trade_data = decrypt_trade_data(
                    hex_to_byte, self.pay_account.merchant_deskey)

                pattern = re.compile(r'{"(.+)"}')
                match = pattern.search(plain_trade_data)
                if match:
                    self.res_json = match.group()

                else:
                    raise ValueError(u'Failed to macth the final trade data.')
            else:
                # 验签失败  不受信任的响应数据
                raise ValueError('Sign test failure, untrusted response data.')

        self.res['resultCode'] = self.response_dict['resultCode']
        self.res['resultMsg'] = self.response_dict[
            'resultMsg'] if self.response_dict['resultMsg'] else ''
        self.res['data'] = self.res_json if self.res_json else ''
示例#38
0
    def __init__(self, config):
        self.name = "SQlAudit"
        self.config = config
        connect_string = config.get("linotpAudit.sql.url")
        pool_recycle = config.get("linotpAudit.sql.pool_recyle", 3600)
        implicit_returning = config.get("linotpSQL.implicit_returning", True)

        self.engine = None
        ########################## SESSION ##################################

        # Create an engine and create all the tables we need
        if implicit_returning:
            # If implicit_returning is explicitly set to True, we
            # get lots of mysql errors
            # AttributeError: 'MySQLCompiler_mysqldb' object has no
            # attribute 'returning_clause'
            # So we do not mention explicit_returning at all
            self.engine = create_engine(connect_string,
                                        pool_recycle=pool_recycle)
        else:
            self.engine = create_engine(connect_string,
                                        pool_recycle=pool_recycle,
                                        implicit_returning=False)

        metadata.bind = self.engine
        metadata.create_all()

        # Set up the session
        self.sm = orm.sessionmaker(bind=self.engine, autoflush=True,
                                   autocommit=True, expire_on_commit=True)
        self.session = orm.scoped_session(self.sm)

        # initialize signing keys
        self.readKeys()

        self.PublicKey = RSA.load_pub_key(
                                          self.config.get("linotpAudit.key.public"))
        self.VerifyEVP = EVP.PKey()
        self.VerifyEVP.reset_context(md='sha256')
        self.VerifyEVP.assign_rsa(self.PublicKey)

        return
示例#39
0
def generate_self_signed_cert_m2(cert_dir):
    if not os.path.exists(cert_dir):
        os.makedirs(cert_dir)
    cert_path = os.path.join(cert_dir, 'cert-rsa.pem')
    key_path = os.path.join(cert_dir, 'key-rsa.pem')

    if os.path.exists(cert_path):
        os.remove(cert_path)
    if os.path.exists(key_path):
        os.remove(key_path)

    # create a key pair
    key = RSA.gen_key(2048, 65537)
    key.save_key(key_path, None)
    pkey = EVP.PKey(
    )  # Converting the RSA key into a PKey() which is stored in a certificate
    pkey.assign_rsa(key)

    # create a self-signed cert, the config is copied from src/lib/opensslVerify/openssl.cnf. not sure whether making it random is good or not.
    # time for certificate to stay valid
    cur_time = M2Crypto.ASN1.ASN1_UTCTIME()
    cur_time.set_time(int(time.time()) - 60 * 60 * 24)
    expire_time = M2Crypto.ASN1.ASN1_UTCTIME()
    expire_time.set_time(int(time.time()) + 60 * 60 * 24 * 365)
    # creating a certificate
    cert = M2Crypto.X509.X509()
    cert.set_pubkey(pkey)
    cs_name = M2Crypto.X509.X509_Name()
    cs_name.C = "US"
    cs_name.ST = 'NY'
    cs_name.L = 'New York'
    cs_name.O = 'Example, LLC'
    cs_name.CN = 'Example Company'
    #    cs_name.Email = "*****@*****.**"
    cert.set_subject(cs_name)
    cert.set_issuer_name(cs_name)
    cert.set_not_before(cur_time)
    cert.set_not_after(expire_time)
    # self signing a certificate
    cert.sign(pkey, md="sha256")
    cert.save_pem(cert_path)
    return cert_path, key_path
 def verify_attachment(self):
     if not crypto_install:
         raise MissingError("ERROR IMPORTING M2Crypto, if not installed, "
                            "please install it.\nGet it here:\n"
                            "https://pypi.python.org/pypi/M2Crypto")
     signature = self.signature_tested
     if self.force_signature:
         if not self.signature_tested:
             raise MissingError("Please set a key to test")
     else:
         signature = self.attachment_tested_id.signed_content
         if not signature:
             raise MissingError("This document have't been signed.")
     params = self.env['ir.config_parameter']
     def _get_key():
         signature_key = params.sudo().\
             get_param('attachment_signature_key',
                       default='')
         return signature_key
     def gimmepw(*args):
         signature_passphrase = params.sudo().\
             get_param('attachment_signature_passphrase',
                       default='')
         return str(signature_passphrase)
     key = _get_key()
     pkey = RSA.load_key(key, gimmepw)
     att = self.env['ir.attachment'].create({
                                             'name': 'File tested',
                                             'datas': self.datas,
                                             'datas_fname': 'File tested',
                                             'res_model': self._name,
                                             'res_id': self.id,
                                             })
     value = att.datas
     signature = base64.decodestring(signature)
     sha256_val = hashlib.sha256(value).digest()
     try:
         pkey.verify(sha256_val, signature)
         raise Warning(_("The signature is OK !\n"
                         "This document hasn't been changed."))
     except RSAError:
         raise Warning(_("Wrong signature !\nThe document has changed."))
示例#41
0
def decodeClientKey(encodedKey):
    try:
        qKeys = MpSiteKeys.query.filter(MpSiteKeys.active == '1').first()
        priKeyFile = "/tmp/." + str(uuid.uuid4())
        f = open(priKeyFile, "w")
        f.write(qKeys.priKey)
        f.close()

        priv = RSA.load_key(priKeyFile)
        decrypted = priv.private_decrypt(base64.b64decode(encodedKey),
                                         RSA.pkcs1_padding)
        os.remove(priKeyFile)
        return decrypted

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        log_Error('[Registration][decodeClientKey][Line: %d] Message: %s' %
                  (exc_tb.tb_lineno, e.message))
        db.session.rollback()
        return None
示例#42
0
文件: key_utils.py 项目: zzzzpaul/grr
def MakeCSR(bits, common_name):
  """Create an X509 request.

  Args:
    bits: Number of RSA key bits.
    common_name: common name in the request

  Returns:
    An X509 request and the priv key.
  """
  pk = EVP.PKey()
  req = X509.Request()
  rsa = RSA.gen_key(bits, 65537, lambda: None)
  pk.assign_rsa(rsa)
  req.set_pubkey(pk)
  options = req.get_subject()
  options.C = "US"
  options.CN = common_name
  req.sign(pk, "sha256")
  return req, pk
示例#43
0
    def initalize_security(self):
        if self.data_dir is not None:
            if not path.isdir(self.data_dir):
                logging.error(
                    'Security Data Directory does not exist or is not a directory: %s'
                    % self.data_dir)
            else:
                key_path = path.join(self.data_dir, self.key_file)

                if path.isfile(key_path):
                    logging.info("Loading existing keys from %s. PEM: %s" %
                                 (self.data_dir, self.key_file))
                    self._key = EVP.load_key(key_path)
                    self.ready = True
                else:
                    logging.info("No keys found. Generating New Keys")
                    # TODO magic strings and such
                    self._key = RSA.gen_key(self.key_size, 65537)
                    self._key.save_pem(key_path, cipher=None)
                    self.ready = True
示例#44
0
def generate_rsa_key(length = 1024):
   """
   Generate new RSA key and return (PEM, fingerprint).
   """
   key = RSA.gen_key(length, m2.RSA_F4, callback = lambda: None)

   kmem = BIO.MemoryBuffer()
   key.save_key_bio(kmem, cipher = None)
   keypem = kmem.getvalue()

   pub_kmem = BIO.MemoryBuffer()
   key.save_pub_key_bio(pub_kmem)
   pub_keypem = pub_kmem.getvalue()

   pkey = EVP.PKey(md = "sha1")
   pkey.assign_rsa(key)

   fingerprint = key_fingerprint(pkey)

   return (keypem, pub_keypem, fingerprint)
示例#45
0
    def new(self, identifier):
        # New key of the correct size
        key = EVP.PKey()
        key.assign_rsa(RSA.gen_key(self.key_size, 0x10001, lambda: None))

        # Generate the certreq
        request = X509.Request()
        request.set_pubkey(key)

        # Set the request's DN
        subject = request.get_subject()
        for k, v in self.dnbase.iteritems():
            # INI style parsers frequently convert key names to all lowercase
            # and M2Crypto's X509_Name class doesn't like that.
            setattr(subject, k.upper(), v)
        subject.CN = identifier

        # Sign the request
        request.sign(key, self.digest_alg)
        return key, request
示例#46
0
def rsa_sign(xml, ref_uri, private_key, password=None, cert=None, c14n_exc=True,
             sign_template=SIGN_REF_TMPL, key_info_template=KEY_INFO_RSA_TMPL):
    "Sign an XML document usign RSA (templates: enveloped -ref- or enveloping)"

    # normalize the referenced xml (to compute the SHA1 hash)
    ref_xml = canonicalize(xml, c14n_exc)
    # create the signed xml normalized (with the referenced uri and hash value)
    signed_info = sign_template % {'ref_uri': ref_uri, 
                                   'digest_value': sha1_hash_digest(ref_xml)}
    signed_info = canonicalize(signed_info, c14n_exc)
    # Sign the SHA1 digest of the signed xml using RSA cipher
    pkey = RSA.load_key(private_key, lambda *args, **kwargs: password)
    signature = pkey.sign(hashlib.sha1(signed_info).digest())
    # build the mapping (placeholders) to create the final xml signed message
    return {
            'ref_xml': ref_xml, 'ref_uri': ref_uri,
            'signed_info': signed_info,
            'signature_value': base64.b64encode(signature),
            'key_info': key_info(pkey, cert, key_info_template),
            }
示例#47
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
示例#48
0
def _generate_proxy_request(key_len=2048):
    """
    Generates a X509 proxy request.
    
    Args:
        key_len: Length of the RSA key in bits

    Returns:
        A tuple (X509 request, generated private key)
    """
    key_pair = RSA.gen_key(key_len, 65537, callback=_mute_callback)
    pkey = EVP.PKey()
    pkey.assign_rsa(key_pair)
    x509_request = X509.Request()
    x509_request.set_pubkey(pkey)
    x509_request.set_subject(_populated_x509_name([('O', 'Dummy')]))
    x509_request.set_version(0)
    x509_request.sign(pkey, 'sha256')

    return x509_request, pkey
示例#49
0
    def decrypt_aes(self, payload, master_pub=True):
        '''
        This function is used to decrypt the aes seed phrase returned from
        the master server, the seed phrase is decrypted with the ssh rsa
        host key.

        Pass in the encrypted aes key.
        Returns the decrypted aes seed key, a string
        '''
        if self.opts.get('auth_trb', False):
            log.warning(
                    'Auth Called: {0}'.format(
                        ''.join(traceback.format_stack())
                        )
                    )
        else:
            log.debug('Decrypting the current master AES key')
        key = self.get_keys()
        key_str = key.private_decrypt(payload['aes'], RSA.pkcs1_oaep_padding)
        if 'sig' in payload:
            m_path = os.path.join(self.opts['pki_dir'], self.mpub)
            if os.path.exists(m_path):
                try:
                    mkey = RSA.load_pub_key(m_path)
                except Exception:
                    return '', ''
                digest = hashlib.sha256(key_str).hexdigest()
                m_digest = mkey.public_decrypt(payload['sig'], 5)
                if m_digest != digest:
                    return '', ''
        else:
            return '', ''
        if '_|-' in key_str:
            return key_str.split('_|-')
        else:
            if 'token' in payload:
                token = key.private_decrypt(payload['token'], RSA.pkcs1_oaep_padding)
                return key_str, token
            elif not master_pub:
                return key_str, ''
        return '', ''
示例#50
0
文件: m.py 项目: mmcgarr/email
def decrypt(cipher):
    ReadRSA = RSA.load_key(REC_KEY_FILE)
    index = cipher.find("--digsig")

    if cipher.find("--RSA ENCRYPTED MESSAGE--") != -1:
        isEnc = True
        startingIndex = 27
    else:
        startingIndex = 0
        isEnc = False

    plaintext = cipher

    # if the message is signed.
    if index != -1:
        signiture = cipher[index + 10:]
        cipher = cipher[startingIndex:index - 4]

        startingIndex = 0
        print "Cipher: " + cipher
        print "Signiture: " + signiture

        signiture = base64.b64decode(signiture)

        print "Verifiing Signiture..."
        verify(cipher, signiture)
        print "Verified."
        plaintext = cipher

    # if the message is encrypted
    if isEnc:
        cipher = base64.b64decode(cipher[startingIndex:])
        try:
            print "Decrypting Message..."
            plaintext = "Message:\n	" + ReadRSA.private_decrypt(
                cipher, RSA.pkcs1_padding)
        except:
            print "Error: wrong key?"
            plaintext = ""

    return plaintext
def main():

    continua = True

    certificate.create_self_signed_cert()

    f = open("selfsigned.crt")
    cert_buffer = f.read()
    f.close()

    cert = X509.load_cert_string(cert_buffer, X509.FORMAT_PEM)
    pub_key = cert.get_pubkey()
    rsa_key = pub_key.get_rsa()

    ReadRSA = RSA.load_key('private.key')

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((sys.argv[1], 10009))

    while (continua == True):

        order = raw_input("Next Order:")
        orders = order.split(" ")
        send_data(sock, orders[0])

        if (orders[0] == "DIRSEARCH"):
            send_data(sock, orders[1])
            print recv_data(sock)

        if (orders[0] == "DOWNLOAD"):
            send_data(sock, orders[1])
            receive_file_contents(orders[1], sock, ReadRSA)

        if (orders[0] == "UPLOAD"):
            send_data(sock, orders[1])
            send_file_contents(orders[1], sock, rsa_key)

        if (orders[0] == "CLOSE"):
            continua = False

    return
    def get_contracts_xml_signature(self, documento):
        self.get_contracts()
        #, datetime.now().replace(microsecond=0).isoformat('T')
        fiel_pass = "******"
        if str(documento).upper() == 'C':
            document = open('Contracts/contract.txt')
        elif documento.upper() == 'P':
            document = open('Contracts/privacy.txt')
        aviso_tmpl = '''<?xml version="1.0" encoding="UTF-8"?>
        <documento><contrato rfc="%s" fecha="2019-09-24T16:00:00">%s</contrato><ds:Signature 
        xmlns:ds="http://www.w3.org/2000/09/xmldsig#">''' 
        aviso = aviso_tmpl % (self.taxpayer_id, document.read())

        digest_value = base64.encodestring(hashlib.sha1(aviso).digest())
        
        signed_info_digest_tmpl = '''<ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/><ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/><ds:Reference URI=""><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><ds:DigestValue>%s</ds:DigestValue></ds:Reference></ds:SignedInfo>'''
        signed_info_digest = signed_info_digest_tmpl % (digest_value)

        signed_info_digest_value = hashlib.sha1(signed_info_digest).digest().strip()
        
        try:
            pri_key = RSA.load_key_string(self.key)
        except Exception as e:
            print "Error en key get_contracts_xml_signature =>" + str(e)
        
        try:
            pri_cer = X509.load_cert_string(self.cer, X509.FORMAT_PEM)
        except Exception as e:
            print "Error en cer get_contracts_xml_signature =>" + str(e)

        signature_value = pri_key.sign(signed_info_digest_value)
       
        cert = self.cer.replace('-----BEGIN CERTIFICATE-----', '')
        cert = cert.replace('-----END CERTIFICATE-----', '').strip()

        signature_template_tmpl = '''%s<ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/><ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/><ds:Reference URI=""><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><ds:DigestValue>+%s</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue>%s</ds:SignatureValue><ds:KeyInfo><ds:X509Data><ds:X509Certificate>%s</ds:X509Certificate></ds:X509Data></ds:KeyInfo></ds:Signature></documento>'''
        signature_template = signature_template_tmpl % (aviso, digest_value, base64.encodestring(signature_value).strip(), cert)

        with open('Contracts/sign_template_{}.xml'.format(documento.upper()), 'w') as sign_template:
            sign_template.write(signature_template)
            sign_template.close()
示例#53
0
def verify_notary_signature(service_id, notary_xml_text, notary_pub_key_text): 
 
	notary_reply = parseString(notary_xml_text).documentElement
	packed_data = ""

	keys = notary_reply.getElementsByTagName("key")
	for k in keys:
        	timespans = k.getElementsByTagName("timestamp")
        	num_timespans = len(timespans)
        	head = struct.pack("BBBBB", (num_timespans >> 8) & 255, num_timespans & 255, 0, 16,3)
        	fingerprint = k.getAttribute("fp")
        	fp_bytes = ""
		for hex_byte in fingerprint.split(":"):
                	fp_bytes += struct.pack("B", int(hex_byte,16))
		ts_bytes = ""
        	for ts in timespans:
                	ts_start = int(ts.getAttribute("start"))
                	ts_end  = int(ts.getAttribute("end"))
                	ts_bytes += struct.pack("BBBB", ts_start >> 24 & 255,
                                                   ts_start >> 16 & 255,
                                                   ts_start >> 8 & 255,
                                                   ts_start & 255)
                	ts_bytes += struct.pack("BBBB", ts_end >> 24 & 255,
                                                   ts_end >> 16 & 255,
                                                   ts_end >> 8 & 255,
                                                   ts_end & 255)
		packed_data =(head + fp_bytes + ts_bytes) + packed_data   


	packed_data = service_id +  struct.pack("B",0) + packed_data

	sig_raw = base64.standard_b64decode(notary_reply.getAttribute("sig")) 
	bio = BIO.MemoryBuffer(notary_pub_key_text)
	rsa_pub = RSA.load_pub_key_bio(bio)
	pubkey = EVP.PKey()
	pubkey.assign_rsa(rsa_pub)

	pubkey.reset_context(md='md5')
	pubkey.verify_init()
	pubkey.verify_update(packed_data)
	return pubkey.verify_final(sig_raw)
示例#54
0
    def test_public_encrypt(self):
        priv = RSA.load_key(self.privkey)
        # pkcs1_padding, pkcs1_oaep_padding
        for padding in self.e_padding_ok:
            p = getattr(RSA, padding)
            ctxt = priv.public_encrypt(self.data, p)
            ptxt = priv.private_decrypt(ctxt, p)
            self.assertEqual(ptxt, self.data)

        # sslv23_padding
        ctxt = priv.public_encrypt(self.data, RSA.sslv23_padding)
        res = priv.private_decrypt(ctxt, RSA.sslv23_padding)
        self.assertEqual(res, self.data)

        # no_padding
        with six.assertRaisesRegex(self, RSA.RSAError, 'data too small'):
            priv.public_encrypt(self.data, RSA.no_padding)

        # Type-check the data to be encrypted.
        with self.assertRaises(TypeError):
            priv.public_encrypt(self.gen_callback, RSA.pkcs1_padding)
示例#55
0
 def minion_sign_in_payload(self):
     '''
     Generates the payload used to authenticate with the master
     server. This payload consists of the passed in id_ and the ssh
     public key to encrypt the AES key sent back form the master.
     '''
     payload = {}
     payload['enc'] = 'clear'
     payload['load'] = {}
     payload['load']['cmd'] = '_auth'
     payload['load']['id'] = self.opts['id']
     try:
         pub = RSA.load_pub_key(
             os.path.join(self.opts['pki_dir'], self.mpub))
         payload['load']['token'] = pub.public_encrypt(
             self.token, RSA.pkcs1_oaep_padding)
     except Exception:
         pass
     with salt.utils.fopen(self.pub_path, 'r') as fp_:
         payload['load']['pub'] = fp_.read()
     return payload
示例#56
0
    def sign(self, filename):
        '''
    Restituisce la stringa contenente la firma del digest SHA1 del
    file da firmare
    '''
        try:
            from M2Crypto import RSA
        except Exception:
            logger.debug('Impossibile importare il modulo M2Crypto')
            return None

        data = open(filename, 'rb').read()
        digest = hashlib.sha1(data).digest()

        rsa = RSA.load_key(self._certificate)

        signature = rsa.sign(digest)
        if rsa.verify(digest, signature):
            return signature
        else:
            return None
示例#57
0
def sella_xml(cfdi, numero_certificado, archivo_cer, archivo_pem):
  keys = RSA.load_key(archivo_pem)
  cert_file = open(archivo_cer, 'r')
  cert = base64.b64encode(cert_file.read())
  xdoc = ET.fromstring(cfdi)

  comp = xdoc.get('Comprobante')
  xdoc.attrib['Certificado'] = cert
  xdoc.attrib['NoCertificado'] = numero_certificado

  xsl_root = ET.parse('utilerias/xslt33/cadenaoriginal_3_3.xslt')
  xsl = ET.XSLT(xsl_root)
  cadena_original = xsl(xdoc)
  digest = hashlib.new('sha256', str(cadena_original)).digest()
  sello = base64.b64encode(keys.sign(digest, "sha256"))

  comp = xdoc.get('Comprobante')
  xdoc.attrib['Sello'] = sello
  
  print ET.tostring(xdoc)
  return ET.tostring(xdoc)
示例#58
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()
示例#59
0
文件: identity.py 项目: hufman/jongau
def _generate_key(bits=None):
    """ Create a new RSA key """
    if not bits:
        bits = jongau.settings.key_size
    key_dir = jongau.settings.key_dir
    newkey = {}
    now = time.time()
    timeformat = '%Y%m%d_%H%M_{0:07}.key'.format(long(now % 60 * 10000))
    newkey['filename'] = time.strftime(timeformat, time.gmtime(now))
    newkey['created'] = long(now)
    newkey['bits'] = bits
    newpath = os.path.join(key_dir, newkey['filename'])
    exponent = 65537
    rsa = RSA.gen_key(bits, exponent, lambda: None)
    rsa.save_pem(newpath, cipher=None)
    pk = EVP.PKey()
    pk.assign_rsa(rsa)
    newkey['modulus'] = pk.get_modulus().lower()
    newkey['exponent'] = exponent
    newkey['format'] = 'rsa'
    return newkey
示例#60
0
def mk_request(bits, cn='localhost'):
    """
	Create a X509 request with the given number of bits in they key.
	Args:
	  bits -- number of RSA key bits
	  cn -- common name in the request
	Returns a X509 request and the private key (EVP)
	"""
    pk = EVP.PKey()
    x = X509.Request()
    rsa = RSA.gen_key(bits, 65537, lambda: None)
    pk.assign_rsa(rsa)
    x.set_pubkey(pk)
    name = x.get_subject()
    name.C = "US"
    name.CN = cn
    name.ST = 'CA'
    name.O = 'yelp'
    name.OU = 'testing'
    x.sign(pk, 'sha1')
    return x, pk