当前位置: 首页>>代码示例>>Python>>正文


Python M2Crypto.EVP类代码示例

本文整理汇总了Python中M2Crypto.EVP的典型用法代码示例。如果您正苦于以下问题:Python EVP类的具体用法?Python EVP怎么用?Python EVP使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了EVP类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _sign_string

 def _sign_string(message, private_key_file=None, private_key_string=None):
     """
     Signs a string for use with Amazon CloudFront.  Requires the M2Crypto
     library be installed.
     """
     try:
         from M2Crypto import EVP
     except ImportError:
         raise NotImplementedError("Boto depends on the python M2Crypto "
                                   "library to generate signed URLs for "
                                   "CloudFront")
     # Make sure only one of private_key_file and private_key_string is set
     if private_key_file and private_key_string:
         raise ValueError("Only specify the private_key_file or the private_key_string not both")
     if not private_key_file and not private_key_string:
         raise ValueError("You must specify one of private_key_file or private_key_string")
     # if private_key_file is a file object read the key string from there
     if isinstance(private_key_file, file):
         private_key_string = private_key_file.read()
     # Now load key and calculate signature
     if private_key_string:
         key = EVP.load_key_string(private_key_string)
     else:
         key = EVP.load_key(private_key_file)
     key.reset_context(md='sha1')
     key.sign_init()
     key.sign_update(str(message))
     signature = key.sign_final()
     return signature
开发者ID:ByteInternet,项目名称:boto,代码行数:29,代码来源:distribution.py

示例2: make_chain_hmac

 def make_chain_hmac(self, key, start, input, algo='sha1'):
     chain = []
     digest = EVP.hmac(key, start, algo)
     chain.append((digest, start))
     for i in input:
         digest = EVP.hmac(digest, i, algo)
         chain.append((digest, i))
     return chain
开发者ID:mcepl,项目名称:M2Crypto,代码行数:8,代码来源:test_evp.py

示例3: verify_chain_hmac

 def verify_chain_hmac(self, key, start, chain, algo='sha1'):
     digest = EVP.hmac(key, start, algo)
     c = chain[0]
     if c[0] != digest or c[1] != start:
         return 0
     for d, v in chain[1:]:
         digest = EVP.hmac(digest, v, algo)
         if digest != d:
             return 0
     return 1
开发者ID:mcepl,项目名称:M2Crypto,代码行数:10,代码来源:test_evp.py

示例4: _get_hmac_prf

def _get_hmac_prf(digest):
    "helper to return HMAC prf for specific digest"
    def tag_wrapper(prf):
        prf.__name__ = "hmac_" + digest
        prf.__doc__ = ("hmac_%s(key, msg) -> digest;"
                       " generated by passlib.utils.pbkdf2.get_prf()" %
                       digest)

    if _EVP and digest == "sha1":
        # use m2crypto function directly for sha1, since that's it's default digest
        try:
            result = _EVP.hmac(b('x'),b('y'))
        except ValueError: # pragma: no cover
            pass
        else:
            if result == _XY_DIGEST:
                return _EVP.hmac, 20
        # don't expect to ever get here, but will fall back to pure-python if we do.
        warn("M2Crypto.EVP.HMAC() returned unexpected result " # pragma: no cover -- sanity check
             "during Passlib self-test!", PasslibRuntimeWarning)
    elif _EVP:
        # use m2crypto if it's present and supports requested digest
        try:
            result = _EVP.hmac(b('x'), b('y'), digest)
        except ValueError:
            pass
        else:
            # it does. so use M2Crypto's hmac & digest code
            hmac_const = _EVP.hmac
            def prf(key, msg):
                return hmac_const(key, msg, digest)
            digest_size = len(result)
            tag_wrapper(prf)
            return prf, digest_size

    # fall back to hashlib-based implementation
    digest_const = getattr(hashlib, digest, None)
    if not digest_const:
        raise ValueError("unknown hash algorithm: %r" % (digest,))
    tmp = digest_const()
    block_size = tmp.block_size
    assert block_size >= 16, "unacceptably low block size"
    digest_size = tmp.digest_size
    del tmp
    def prf(key, msg):
        # simplified version of stdlib's hmac module
        if len(key) > block_size:
            key = digest_const(key).digest()
        key += _BNULL * (block_size - len(key))
        tmp = digest_const(key.translate(_trans_36) + msg).digest()
        return digest_const(key.translate(_trans_5C) + tmp).digest()
    tag_wrapper(prf)
    return prf, digest_size
开发者ID:Glottotopia,项目名称:aagd,代码行数:53,代码来源:pbkdf2.py

示例5: _query_string

    def _query_string(self):
        '''Generate a signed query string for an Amazon CloudFront Object

        :param cf_obj: A cloudfront Object or StreamingObject
        :type cf_obj: boto.cloudfront.object.Object
        :param json_policy: JSON Policy to be signed in the query string
        :type json_policy: str
        This is just the query string part of making signed URLs
        '''
        json_policy = self.json_policy
        b64_json_policy = b64awsencode(json_policy)

        key = EVP.load_key_string(settings.AWS_CLOUDFRONT_SIGNING_KEY)
        # Explicitly use sha1 for signing, per AWS requirements
        key.reset_context(md='sha1')
        key.sign_init()
        key.sign_update(json_policy)
        signature = key.sign_final()

        b64_signature = b64awsencode(signature)

        query_string = "Policy=%s&Signature=%s&Key-Pair-Id=%s" % (
            b64_json_policy, b64_signature, settings.AWS_COULDFRONT_SIGNING_KEY_ID
        )

        return query_string
开发者ID:AmericanResearchInstitute,项目名称:poweru-server,代码行数:26,代码来源:awsutils.py

示例6: EncryptCode

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
开发者ID:avyou,项目名称:webPublisher,代码行数:7,代码来源:passEncrypt.py

示例7: make_request

def make_request(private_key_path, username, user_context, critical, output, is_printed):
    private_key = None
    try:
        private_key = EVP.load_key(private_key_path, callback=password)
    except EVP.EVPError:
        print('ERROR request: Could not load key pair from %s' % private_key_path)
        exit(1)
    request = X509.Request()
    request.set_pubkey(private_key)
    request.set_version(2)
    name = X509.X509_Name()
    name.C = DEFAULT_FIELDS['C']
    name.ST = DEFAULT_FIELDS['ST']
    name.L = DEFAULT_FIELDS['L']
    name.O = DEFAULT_FIELDS['O']
    name.OU = DEFAULT_FIELDS['OU']
    name.CN = username
    if user_context:
        context = user_context
    else:
        context = getcon_raw()[1]
    if not context:
        print('ERROR request: Could not get SELinux context for user %s' % username)
        exit(1)
    request.set_subject_name(name)
    stack = X509.X509_Extension_Stack()
    stack.push(X509.new_extension('selinuxContext', context, int(critical)))
    request.add_extensions(stack)
    request.sign(private_key, 'sha1')
    if not output:
        output = path.abspath(path.curdir) + '/%s.csr' % DEFAULT_FIELDS['CN']
    request.save_pem(output)
    if is_printed:
        print(request.as_text())
    print('Request was saved to %s' % output)
开发者ID:dimV36,项目名称:UIR,代码行数:35,代码来源:pgcert_rsa.py

示例8: test_rfc3211_test_vectors

    def test_rfc3211_test_vectors(self):

        password = b'password'
        salt = unhexlify('1234567878563412')
        iter = 5
        keylen = 8
        ret = EVP.pbkdf2(password, salt, iter, keylen)
        self.assertEqual(ret, unhexlify(b'd1daa78615f287e6'))

        password = b'All n-entities must communicate with other n-entities' + \
            b' via n-1 entiteeheehees'
        salt = unhexlify('1234567878563412')
        iter = 500
        keylen = 16
        ret = EVP.pbkdf2(password, salt, iter, keylen)
        self.assertEqual(ret, unhexlify(b'6a8970bf68c92caea84a8df285108586'))
开发者ID:mcepl,项目名称:M2Crypto,代码行数:16,代码来源:test_evp.py

示例9: createEncryptionWithPassphrase

def createEncryptionWithPassphrase(secret_key, passphrase):
  iv_and_salt = rand_bytes(128 / 8)
  password_derived_key = EVP.pbkdf2(passphrase, iv_and_salt, 1000, 256 / 8)

  cipher = EVP.Cipher(alg="aes_256_cbc", key=password_derived_key, iv=iv_and_salt, op=M2Crypto.encrypt)
  encrypted_key = cipher.update(secret_key)
  encrypted_key += cipher.final()
  hmac = EVP.hmac(password_derived_key, iv_and_salt + secret_key, algo="sha256")

  return {
    "version": 0,
    "algorithm": "PBKDF2_SHA1_AES_256_CBC_HMAC_SHA256",
    "iv": base64.standard_b64encode(iv_and_salt),
    "ciphertext": base64.standard_b64encode(encrypted_key),
    "signature": base64.standard_b64encode(hmac)
  }
开发者ID:pmoor,项目名称:swiss-vault,代码行数:16,代码来源:crypto.py

示例10: generate_keys

    def generate_keys(self):
        # Generate the elliptic curve and the keys
        ec = EC.gen_params(EC.NID_secp256k1)
        ec.gen_key()

        # Generate a Pkey object to store the EC keys
        mem = BIO.MemoryBuffer()
        ec.save_pub_key_bio(mem)
        ec.save_key_bio(mem, None)
        pk = EVP.load_key_bio(mem)

        # Generate the bitcoin address from the public key
        public_key_hex = get_pub_key_hex(ec.pub())
        bitcoin_address = public_key_to_btc_address(public_key_hex, 'test')

        # Save both keys
        if not path.exists(self.data_path + tmp):
            mkdir(self.data_path + tmp)
        ec.save_key(self.data_path + tmp + bitcoin_address + '_key.pem', None)
        ec.save_pub_key(self.data_path + tmp + bitcoin_address + '_public_key.pem')

        # Create the WIF file
        wif = private_key_to_wif(get_priv_key_hex(self.data_path + tmp + bitcoin_address + '_key.pem'), 'image', 'test')
        wif.save(self.data_path + tmp + bitcoin_address + "_WIF.png")

        return pk, bitcoin_address
开发者ID:sr-gi,项目名称:paysense,代码行数:26,代码来源:cs.py

示例11: __init__

	def __init__(self):
		print(str(now()) + "\t" + "Server init at UTC timestamp %d" % (now()))
		
		self.users = {} # maps ids to Client instances
		self.regions = {}  # keeps a count of tokens handed out for each region
		self.regionsLimit = {"Vassar-1":5,
		                     "Mass-1":2,
		                     "Mass-2":2,
		                     "Windsor-1":2,
		                     "Main-1":4,
		                     "Main-2":2,
		                     "Main-3":2,
		                     "Albany-1":2,
		                     "Albany-2":2,
		                     "Portland-1":1,
		                     "Stata-1":1,
		} # maximum counts / limits for each region
		
		# load key
		if os.path.isfile(cert_file):
			self.key = EVP.load_key("mycert-private.pem")
			self.key.reset_context(md='sha256')
			print("Signing enabled.")
		else:
			self.key = None
			print("Signing disabled.")
		
		# sign data
		if self.key:
			self.key.sign_init()
			self.key.sign_update("from-python")
			signature = self.key.sign_final()
			print(str(now()) + "\t" + "'from-python' test signature: " + binascii.b2a_hex(signature))
开发者ID:sorlok,项目名称:RoadRunner,代码行数:33,代码来源:cloud.py

示例12: __P_hash

 def __P_hash(self, secret, seed, size, alg):
     ret = ""
     x = 1
     while len(ret) < size:
         ret += EVP.hmac(secret, self.__A(x, secret, seed, alg) + seed, algo=alg)
         x += 1
     return ret
开发者ID:0rbytal,项目名称:chopshop,代码行数:7,代码来源:sslim.py

示例13: load_key

 def load_key(self, keyfile, certfile=None,
              callback=util.passphrase_callback):
     # type: (AnyStr, Optional[AnyStr], Callable) -> None
     if certfile is None:
         certfile = keyfile
     self.pkey = EVP.load_key(keyfile, callback)
     self.x509 = X509.load_cert(certfile)
开发者ID:mcepl,项目名称:M2Crypto,代码行数:7,代码来源:SMIME.py

示例14: test_pkey_verify_crash

    def test_pkey_verify_crash(self):
        SIGN_PRIVATE = EVP.load_key('tests/rsa.priv.pem')
        SIGN_PUBLIC = RSA.load_pub_key('tests/rsa.pub.pem')

        def sign(data):
            SIGN_PRIVATE.sign_init()
            SIGN_PRIVATE.sign_update(data)
            signed_data = SIGN_PRIVATE.sign_final()
            return base64.b64encode(signed_data)

        def verify(response):
            signature = base64.b64decode(response['sign'])
            data = response['data']
            verify_evp = EVP.PKey()
            # capture parameter on the following line is required by
            # the documentation
            verify_evp.assign_rsa(SIGN_PUBLIC, capture=False)
            verify_evp.verify_init()
            verify_evp.verify_update(data)
            # m2.verify_final(self.ctx, sign, self.pkey)
            fin_res = verify_evp.verify_final(signature)
            return fin_res == 1

        data = b"test message"
        signature = sign(data)
        res = {"data": data, "sign": signature}
        self.assertTrue(verify(res))  # works fine
        self.assertTrue(verify(res))  # segmentation fault in *verify_final*
开发者ID:mcepl,项目名称:M2Crypto,代码行数:28,代码来源:test_evp.py

示例15: get_decrypted_key

def get_decrypted_key(encrypted_key, salt, password, debug=True):

  keySize = len(encrypted_key)
  assert(keySize == 16 or keySize == 32) # Other cases should be double-checked
  if keySize == 16:
    algorithm='aes_128_cbc'
  elif keySize == 32:
    algorithm='aes_256_cbc'
  else:
    print 'Error: unsupported keySize'
    return

  # Calculate the key decryption key and IV from the password
  # We encountered problems with EVP.pbkdf2 on some Windows platforms with M2Crypto-0.21.1
  # In such case, use pbkdf2.py from https://github.com/mitsuhiko/python-pbkdf2
  pbkdf2 = EVP.pbkdf2(password, salt, iter=HASH_COUNT, keylen=keySize+IV_LEN_BYTES)
  #pbkdf2 = pbkdf2_bin(data=password, salt=salt, iterations=HASH_COUNT, keylen=keySize+IV_LEN_BYTES)
  key = pbkdf2[:keySize]
  iv = pbkdf2[keySize:]

  # Decrypt the encryption key
  cipher = EVP.Cipher(alg=algorithm, key=key, iv=iv, padding=0, op=DECRYPT)
  decrypted_key = cipher.update(encrypted_key)
  decrypted_key = decrypted_key + cipher.final()
  
  # Display the decrypted key
  if debug:
    print 'Password       :', password
    print 'Derived Key    :', "0x" + key.encode("hex").upper()
    print 'Derived IV     :', "0x" + iv.encode("hex").upper()
    print 'Decrypted Key  :', "0x" + decrypted_key.encode("hex").upper()
    print '----------------'

  return decrypted_key
开发者ID:chubbymaggie,项目名称:android-fde,代码行数:34,代码来源:fde.py


注:本文中的M2Crypto.EVP类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。