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
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
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
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
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'))
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)
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)
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
def check_key_password(key_filename,password=""): """Check if provided password is valid to read the PEM private key >>> if not os.path.isfile('c:/private/test.pem'): ... create_self_signed_key('test',organization='Tranquil IT',locality=u'St Sebastien sur Loire',commonname='wapt.tranquil.it',email='*****@*****.**') >>> check_key_password('c:/private/test.pem','') True >>> check_key_password('c:/private/ko.pem','') False """ def callback(*args): return password try: EVP.load_key(key_filename, callback) except EVPError: return False return True
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))
def generate(cls, servers, scopeurls, expires, keydata, blaster=None): '''Generate and return a new ScopeCookie. servers and scopeurls are lists of strings, already Punycoded/URL-encoded as appropriate. expires is a timezone-aware datetime. keydata is a PEM-encoded private key. blaster is an optional string, already URL-encoded.''' # Unicode strings can cause signature validation errors servers = [str(s) for s in servers] scopeurls = [str(u) for u in scopeurls] if blaster is not None: blaster = str(blaster) # Generate scope data serial = str(uuid.uuid4()) headers = [('Version', COOKIE_VERSION), ('Serial', serial), ('Expires', expires.isoformat()), ('Servers', ';'.join(servers))] if blaster is not None: headers.append(('Blaster', blaster)) hdrbuf = ''.join('%s: %s\n' % (k, v) for k, v in headers) data = hdrbuf + '\n' + '\n'.join(scopeurls) + '\n' # Load the signing key key = EVP.load_key_string(keydata) # Sign the data key.sign_init() key.sign_update(data) sig = key.sign_final() # Return the scope cookie return cls(serial, expires, blaster, servers, scopeurls, data, sig)
def _get_hmac_prf(digest): "helper to return HMAC prf for specific digest" #check if m2crypto is present and supports requested digest if _EVP: 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): "prf(key,msg)->digest; generated by passlib.utils.pbkdf2.get_prf()" return hmac_const(key, msg, digest) prf.__name__ = "hmac_" + digest digest_size = len(result) return prf, digest_size #fall back to stdlib implementation digest_const = getattr(hashlib, digest, None) if not digest_const: raise ValueError("unknown hash algorithm: %r" % (digest,)) digest_size = digest_const().digest_size hmac_const = hmac.new def prf(key, msg): "prf(key,msg)->digest; generated by passlib.utils.pbkdf2.get_prf()" return hmac_const(key, msg, digest_const).digest() prf.__name__ = "hmac_" + digest return prf, digest_size
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*
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) }
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
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
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
def create_account(request): if request.method == 'POST': with open('certs/cert-admin.pem', 'r') as pem: ca_crt = pem.read() cert = X509.load_cert_string(ca_crt) with open('certs/key-admin.pem', 'r') as pem: ca_pkey = pem.read() pkey = EVP.load_key_string(ca_pkey) # ne = X509.new_extension email = request.params['email'] username = request.params['username'] spkac = SPKAC(request.params['spkac'], None, # ne, CN=username, Email=email ) serial = 1000 # XXX must be incremented try: crt = spkac.gen_crt(pkey, cert, serial, hash_algo='sha512') except TypeError: crt = spkac.gen_crt(pkey, cert, serial) response = Response(body=crt.as_pem(), headers={'Accept-Ranges': 'bytes', 'Content-Type': 'application/x-x509-user-cert' }, content_type='application/x-x509-user-cert') return response return {}
def test_verify_final(self): from M2Crypto import X509 pkey = EVP.load_key('tests/signer_key.pem') pkey.sign_init() pkey.sign_update('test message') sig = pkey.sign_final() # OK x509 = X509.load_cert('tests/signer.pem') pubkey = x509.get_pubkey() pubkey.verify_init() pubkey.verify_update('test message') assert pubkey.verify_final(sig) == 1 # wrong cert x509 = X509.load_cert('tests/x509.pem') pubkey = x509.get_pubkey() pubkey.verify_init() pubkey.verify_update('test message') assert pubkey.verify_final(sig) == 0 # wrong message x509 = X509.load_cert('tests/signer.pem') pubkey = x509.get_pubkey() pubkey.verify_init() pubkey.verify_update('test message not') assert pubkey.verify_final(sig) == 0
def test_rfc3211_test_vectors(self): from binascii import hexlify, unhexlify password = '******' salt = unhexlify('12 34 56 78 78 56 34 12'.replace(' ', '')) iter = 5 keylen = 8 ret = EVP.pbkdf2(password, salt, iter, keylen) self.assertEqual(hexlify(ret), 'D1 DA A7 86 15 F2 87 E6'.replace(' ', '').lower()) password = '******' salt = unhexlify('12 34 56 78 78 56 34 12'.replace(' ', '')) iter = 500 keylen = 16 ret = EVP.pbkdf2(password, salt, iter, keylen) self.assertEqual(hexlify(ret), '6A 89 70 BF 68 C9 2C AE A8 4A 8D F2 85 10 85 86'.replace(' ', '').lower())
def add_pem(self,filename,load_keys=False): # parse a bundle PEM with multiple key / certificates lines = open(filename,'r').read().splitlines() inkey = False incert = False tmplines = [] for line in lines: if line == self.BEGIN_CERTIFICATE: tmplines = [line] incert = True elif line == self.END_CERTIFICATE: tmplines.append(line) crt = X509.load_cert_string('\n'.join(tmplines)) self._certificates[crt.get_fingerprint(md='sha1')] = SSLCertificate(filename,crt=crt) incert = False tmplines = [] elif line == self.BEGIN_KEY: tmplines = [line] inkey = True elif line == self.END_KEY: tmplines.append(line) if load_keys: key = EVP.load_key_string('\n'.join(tmplines),callback=self.callback) self._keys[key.get_modulus()] = SSLPrivateKey(filename,key=key,callback=self.callback) inkey = False tmplines = [] else: if inkey or incert: tmplines.append(line)
def crypt_init(cfg): global _crypt_keys global _public_keys global _ca_file # load the signing keys certs = cfg['CERTS'] for c in certs: id = c['ID'] crt = {} crt['url'] = c['URL'] crt['key'] = EVP.load_key(c['KEYFILE']) _private_keys[id] = crt # load the cryption key keys = cfg['CRYPTS'] for k in keys: id = k['ID'] k64 = k['KEY'] logger.debug('adding crypt key ' + id) kbin = base64.b64decode(k64) _crypt_keys[id] = kbin # are we verifying certs ( just for the signing cert ) if 'ca_file' in cfg: _ca_file = cfg['CA_FILE']
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 :'******'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
def sign_string(message, priv_key_string): key = EVP.load_key_string(priv_key_string) key.reset_context(md='sha1') key.sign_init() key.sign_update(message) signature = key.sign_final() return signature
def generate_certificate(csr, serial, cn): """Generate a certificate and sign it with CA. :param csr: Certificate Signing Request. See :class:`M2Crypto.X509.Request`. :param serial: Serial number of the certificate as long int. :param cn: Common Name of the certificate. :return: Generated + signed certificate. See :class:`M2Crypto.X509.X509`. """ ca_key = EVP.load_key(settings.PKI_CA_KEYFILE, lambda *args: None) ca_cert = X509.load_cert(settings.PKI_CA_CERTFILE) cert = X509.X509() cert.set_serial_number(serial) cert.set_version(2) csr_subject = csr.get_subject() subject = X509.X509_Name() for key in ("C", "ST", "L", "O", "OU"): original_value = getattr(csr_subject, key) if original_value: setattr(subject, key, original_value) subject.CN = cn cert.set_subject(subject) t = long(time.time()) + time.timezone now = ASN1.ASN1_UTCTIME() now.set_time(t) now_plus_year = ASN1.ASN1_UTCTIME() now_plus_year.set_time(t + 60 * 60 * 24 * 365) cert.set_not_before(now) cert.set_not_after(now_plus_year) cert.set_issuer(ca_cert.get_subject()) cert.set_pubkey(csr.get_pubkey()) cert.sign(ca_key, "sha1") return cert
def __init__(self): self.cont_cert = None self.cont_key = None self.root_cert = None self.white_list = [] # Look for certificates and keys in "the usual places" certstore_path = self.certstore = CFG.get_safe('authentication.certstore', CERTSTORE_PATH) log.debug("certstore_path: %s" % str(certstore_path)) keystore_path = self.certstore = CFG.get_safe('authentication.keystore', KEYSTORE_PATH) log.debug("keystore_path: %s" % str(keystore_path)) if certstore_path and keystore_path: if certstore_path == 'directory': log.debug("Container.instance.directory: " % str(Container.instance.directory)) Container.instance.directory.load_authentication() else: cont_cert_path = os.path.join(certstore_path, CONTAINER_CERT_NAME) log.debug("cont_cert_path: %s" % cont_cert_path) cont_key_path = os.path.join(keystore_path, CONTAINER_KEY_NAME) log.debug("cont_key_path: %s" % cont_key_path) root_cert_path = os.path.join(certstore_path, ORG_CERT_NAME) log.debug("root_cert_path: %s" % root_cert_path) if os.path.exists(cont_cert_path) and os.path.exists(cont_key_path) and os.path.exists(root_cert_path): with open(cont_cert_path, 'r') as f: self.cont_cert = f.read() log.debug("cont_cert: %s" % self.cont_cert) self.cont_key = EVP.load_key(cont_key_path) with open(root_cert_path, 'r') as f: self.root_cert = f.read() log.debug("root_cert: %s" % self.root_cert) self.add_to_white_list(self.root_cert)
def load_key_bio(self, keybio, certbio=None, callback=util.passphrase_callback): # type: (BIO.BIO, Optional[BIO.BIO], Callable) -> None if certbio is None: certbio = keybio self.pkey = EVP.load_key_bio(keybio, callback) self.x509 = X509.load_cert_bio(certbio)
def make_request(private_key_path, username, user_context, critical, output, is_printed): check_path(private_key_path) private_key = EVP.load_key(private_key_path, callback=password) 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 = check_output("id -Z", shell=True).split('\n')[0] if not context: print('Command `id -Z` return with error code') 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)
def _get_hmac_prf(digest): """helper for get_prf() -- returns HMAC-based prf for specified digest""" # helpers def tag_wrapper(prf): """helper to document generated wrappers""" prf.__name__ = "hmac_" + digest prf.__doc__ = ("hmac_%s(key, msg) -> digest;" " generated by passlib.utils.pbkdf2.get_prf()" % digest) # use m2crypto if it's present and supports requested digest if _EVP: # use m2crypto function directly for sha1, since that's its default digest if digest == "sha1": if _EVP.hmac(b'x', b'y') != _TEST_HMAC_SHA1: # don't expect to ever get here, but just in case raise RuntimeError("M2Crypto.EVP.hmac() failed sanity check") return _EVP.hmac, 20 # else check if it supports given digest as an option try: result = _EVP.hmac(b'x', b'y', digest) except ValueError: pass else: const = _EVP.hmac def prf(key, msg): return const(key, msg, digest) digest_size = len(result) tag_wrapper(prf) return prf, digest_size # fall back to hashlib-based implementation -- # this is a simplified version of stdlib's hmac module. const, digest_size, block_size = get_hash_info(digest) assert block_size >= 16, "unacceptably low block size" def prf(key, msg): klen = len(key) if klen > block_size: key = const(key).digest() klen = digest_size if klen < block_size: key += _BNULL * (block_size - klen) tmp = const(key.translate(_TRANS_36) + msg).digest() return const(key.translate(_TRANS_5C) + tmp).digest() tag_wrapper(prf) return prf, digest_size
def load_certnkey_files(self, cert_file, key_file): ''' This function loads the content of the certificate file and initializes paths to the certificate and the key. ''' cert = X509.load_cert(cert_file) pkey = EVP.load_key(key_file) return CertAndKey(cert.get_subject().CN, cert_file, key_file, cert, pkey)
def rsa_verify(xml, signature, key, c14n_exc=True): "Verify a XML document signature usign RSA-SHA1, return True if valid" # load the public key (from buffer or filename) if key.startswith("-----BEGIN PUBLIC KEY-----"): bio = BIO.MemoryBuffer(key) rsa = RSA.load_pub_key_bio(bio) else: rsa = RSA.load_pub_key(certificate) # create the digital envelope pubkey = EVP.PKey() pubkey.assign_rsa(rsa) # do the cryptographic validation (using the default sha1 hash digest) pubkey.reset_context(md='sha1') pubkey.verify_init() # normalize and feed the signed xml to be verified pubkey.verify_update(canonicalize(xml, c14n_exc)) ret = pubkey.verify_final(base64.b64decode(signature)) return ret == 1
def cmd_mkcert(workingdir, name): cwd = os.getcwd() try: common.ch_dir(workingdir, logger) priv = read_private() cacert = X509.load_cert('cacert.crt') ca_pk = EVP.load_key_string(priv[0]['ca']) cert, pk = ca_impl.mk_signed_cert(cacert, ca_pk, name, priv[0]['lastserial'] + 1) with open('%s-cert.crt' % name, 'wb') as f: f.write(cert.as_pem()) f = BIO.MemoryBuffer() pk.save_key_bio(f, None) priv[0][name] = f.getvalue() f.close() #increment serial number after successful creation priv[0]['lastserial'] += 1 write_private(priv) # write out the private key with password with os.fdopen( os.open("%s-private.pem" % name, os.O_WRONLY | os.O_CREAT, 0o600), 'wb') as f: biofile = BIO.File(f) pk.save_key_bio(biofile, 'aes_256_cbc', globalcb) biofile.close() pk.get_rsa().save_pub_key('%s-public.pem' % name) cc = X509.load_cert('%s-cert.crt' % name) if cc.verify(cacert.get_pubkey()): logger.info("Created certificate for name %s successfully in %s" % (name, workingdir)) else: logger.error("ERROR: Cert does not validate against CA") finally: os.chdir(cwd)
def decrypt_image(self, encrypted_filename, encrypted_key, encrypted_iv, private_key_path): user_priv_key = RSA.load_key(private_key_path) key = user_priv_key.private_decrypt(unhexlify(encrypted_key), RSA.pkcs1_padding) iv = user_priv_key.private_decrypt(unhexlify(encrypted_iv), RSA.pkcs1_padding) k = EVP.Cipher(alg='aes_128_cbc', key=unhexlify(key), iv=unhexlify(iv), op=0) decrypted_filename = encrypted_filename.replace('.enc', '') decrypted_file = open(decrypted_filename, 'wb') encrypted_file = open(encrypted_filename, 'rb') self.crypt_file(k, encrypted_file, decrypted_file) encrypted_file.close() decrypted_file.close() return decrypted_filename
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
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
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)
def load_certnkey_files(self, cert_file, key_file): ''' This function loads the content of the certificate file and initializes paths to the certificate and the key. ''' try: cert = X509.load_cert(cert_file) except M2Crypto.X509.X509Error as ex: raise ConfigError('failed to parse cert file %s, exception: %s' % (cert_file, ex)) try: pkey = EVP.load_key(key_file) except M2Crypto.EVP.EVPError as ex: raise ConfigError('failed to parse key file %s, exception: %s' % (key_file, ex)) return CertAndKey(cert.get_subject().CN, cert_file, key_file, cert, pkey)
def encrypt_image(self, file): print('Encrypting image') enc_file = '%s.part' % file.replace('.tar.gz', '') # get 17 bytes of randomness with top bit a '1'. # convert to a hex string like '0x<34 hex chars>L' # then take the last 32 of the hex digits, giving 32 random hex chars gen_key = hex(BN.rand(17 * 8, top=0)) key = gen_key[4:36] if self.euca.debug: print('Key: %s' % gen_key) gen_iv = hex(BN.rand(17 * 8, top=0)) iv = gen_iv[4:36] if self.euca.debug: print('IV: %s' % gen_iv) try: k = EVP.Cipher(alg='aes_128_cbc', key=unhexlify(key), iv=unhexlify(iv), op=1) except TypeError: print(file=sys.stderr) print('WARNING: retrying encryption to work around a rare RNG bug', file=sys.stderr) print( 'Please report the following values to Eucalyptus Systems at', file=sys.stderr) print('https://eucalyptus.atlassian.net/browse/TOOLS-103 to help', file=sys.stderr) print('diagnose this issue.', file=sys.stderr) print('k: ', key, file=sys.stderr) print('iv:', iv, file=sys.stderr) print(file=sys.stderr) return self.encrypt_image(file) in_file = open(file, 'rb') out_file = open(enc_file, 'wb') self.crypt_file(k, in_file, out_file) in_file.close() out_file.close() bundled_size = os.path.getsize(enc_file) return (enc_file, key, iv, bundled_size)
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
def _validate_rrsig_ec(alg, sig, msg, key): pubkey = _dnskey_to_ec(alg, key) # if the key is invalid, then the signature is also invalid if pubkey is None: return False if alg in (13, ): alg = 'sha256' sigsize = 64 elif alg in (14, ): alg = 'sha384' sigsize = 96 else: raise ValueError('EC hash algorithm unknown!') if sigsize != len(sig): return False offset = 0 # get R new_offset = offset + sigsize // 2 r = b'' for c in sig[offset:new_offset]: r += b'%02x' % struct.unpack(b'B', c)[0] r = bn_to_mpi(hex_to_bn(r)) offset = new_offset # get S new_offset = offset + sigsize // 2 s = b'' for c in sig[offset:new_offset]: s += b'%02x' % struct.unpack(b'B', c)[0] s = bn_to_mpi(hex_to_bn(s)) offset = new_offset md = EVP.MessageDigest(alg) md.update(msg) digest = md.final() return pubkey.verify_dsa(digest, r, s) == 1
def _generate_ssl_keypair(self, rsa_key, ca_key, ca_cert, role='CONTROL', client=False, serial=2): t = long(time.time()) now = ASN1.ASN1_UTCTIME() now.set_time(t) expire = ASN1.ASN1_UTCTIME() expire.set_time(t + 365 * 24 * 60 * 60) pk = EVP.PKey() pk.assign_rsa(rsa_key) cert = X509.X509() cert.get_subject().O = self._generate_id(10) cert.get_subject().OU = role cert.set_serial_number(serial) cert.set_version(3) cert.set_not_before(now) cert.set_not_after(expire) cert.set_issuer(ca_cert.get_subject()) cert.set_pubkey(pk) cert.add_ext( X509.new_extension('basicConstraints', 'critical,CA:FALSE')) cert.add_ext( X509.new_extension('subjectKeyIdentifier', str(cert.get_fingerprint()))) if client: cert.add_ext( X509.new_extension('keyUsage', 'critical,digitalSignature')) cert.add_ext(X509.new_extension('nsCertType', 'client')) else: cert.add_ext( X509.new_extension('keyUsage', 'critical,keyEncipherment')) cert.add_ext(X509.new_extension('nsCertType', 'server')) cert.sign(ca_key, 'sha256') return pk.as_pem(cipher=None), cert.as_pem()
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 encrypt(string, password): '''Encrypt with AES some string''' prefix = 'Salted__' salt = os.urandom(8) hash = [''] for i in range(4): hash.append(md5(hash[i] + password.encode('ascii') + salt).digest()) key, iv = hash[1] + hash[2], hash[3] + hash[4] del hash cipher = EVP.Cipher(alg='aes_256_cbc', key=key, iv=iv, op=1) inpb, outb = StringIO(string), StringIO() while 1: buf = inpb.read() if not buf: break outb.write(cipher.update(buf)) outb.write(cipher.final()) ciphertext = outb.getvalue() inpb.close() outb.close() return (prefix + salt + ciphertext).encode('base64')
def create_Signed_Certificate_Request(csr_info, key_len=2048, sign_method="sha256"): # Step 1: Create a RSA key pair (public/private key) rsa_keypair = generate_rsa_keypair(key_len, 65537) evp_private_key = EVP.PKey() evp_private_key.assign_rsa(rsa_keypair) # Step 2: Create a X.509 request csr = X509.Request() csr.set_pubkey(evp_private_key) # Step 3: Set CSR information x509_name = csr.get_subject() x509_name.C = csr_info['C'] x509_name.CN = csr_info['CN'] x509_name.ST = csr_info['ST'] x509_name.O = csr_info['O'] x509_name.OU = csr_info['OU'] # Step 4: Use RSA private key to sign it csr.sign(evp_private_key, sign_method) return csr, evp_private_key
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
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)
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
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
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
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)
def encrypt_image(self, file): self._logger.info('Encrypting image') enc_file = '%s.part' % file.replace('.tar.gz', '') key = hex(BN.rand(16 * 8))[2:34].replace('L', 'c') iv = hex(BN.rand(16 * 8))[2:34].replace('L', 'c') self._logger.debug('Key: %s', key) self._logger.debug('IV: %s', iv) k = EVP.Cipher(alg='aes_128_cbc', key=unhexlify(key), iv=unhexlify(iv), op=1) in_file = open(file) out_file = open(enc_file, 'wb') self.crypt_file(k, in_file, out_file) in_file.close() out_file.close() bundled_size = os.path.getsize(enc_file) return (enc_file, key, iv, bundled_size)
def __cipher__(self, data): if not 'public_key' in self.__config.keys(): Output.warning( 'Output data cannot be encrypted: cannot find the cipher key file' ) return None # Create a random initialization vector and our AES cipher object. iv = '\0' * 16 random_key = ''.join( chr(random.randint(0x20, 0x7E)) for i in range(16)) aes_cipher = EVP.Cipher(alg='aes_128_cbc', key=random_key, iv=iv, op=1) try: if len(data) % 16 != 0: data += '\0' * (16 - (len(data) % 16)) ciphered_log = aes_cipher.update(data) ciphered_log = ciphered_log + aes_cipher.final() except Exception, e: Output.warning('Output data cannot be encrypted: %s' % str(e)) return None
def round_encrypt(self, text): self.load_pub() uid = str(uuid.uuid4()) text = uid + "\n" + text for cert in self.cert: pad = m2.no_padding if len(text) != 128: pad = m2.pkcs1_padding while True: try: text = cert.get_pubkey().get_rsa().public_encrypt( text, pad) except: pass finally: break md = EVP.MessageDigest('sha1') md.update(text) md = md.final() sign = self.akey.sign(md, 'sha1') return {'uuid': uid, 'evp': base64.b64encode(text + sign)}
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
def decrypt_secret(secret, password, username): """ We will get passed in a 16 byte block of data that has been enrypted with AES using the PIN the first 10 bytes are the secret and the remaining 6 are padding :param secret: The secret. :type secret: str :param password: The password. :type password: str :param username: The user this is for. :type username: str :returns: str """ secret = base64.b32decode(secret) pw_hash = pbkdf2(password.encode('ascii'), username.encode('ascii'), 10000) crypt_object = EVP.Cipher('aes_128_ecb', pw_hash, '', 0, padding=0) tmp = crypt_object.update(secret) return tmp[:10]
def mkreq(bits, ca=0, cn=cert_cn, c=cert_c): pk = EVP.PKey() x = X509.Request() rsa = RSA.gen_key(bits, 65537, callback) pk.assign_rsa(rsa) x.set_pubkey(pk) name = x.get_subject() name.C = c name.CN = cn if not ca: ext1 = X509.new_extension('subjectAltName', 'DNS:' + cn) ext2 = X509.new_extension('nsComment', 'Hello there') extstack = X509.X509_Extension_Stack() extstack.push(ext1) extstack.push(ext2) x.add_extensions(extstack) x.sign(pk, 'sha256') assert x.verify(pk) pk2 = x.get_pubkey() assert x.verify(pk2) return x, pk
def mk_request(bits, country, state, city, common_name, organization, organziation_unit): """ 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 = country name.CN = common_name name.ST = state name.O = organization name.OU = organziation_unit x.sign(pk,'sha256') return x, pk
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
def decryptDecodeScryptKey(cf, password): derived = scrypt.hash(password, cf.cryptoSalt, cf.N, cf.r, cf.p) key = derived[:KEY_LEN_BYTES] iv = derived[KEY_LEN_BYTES:] #print('key : %s' % str(codecs.encode(key,"hex")).upper()) scrypted_intermediate_key = scrypt.hash(key, cf.cryptoSalt, cf.N, cf.r, cf.p) scrypted_intermediate_key_iv = scrypt.hash(derived, cf.cryptoSalt, cf.N, cf.r, cf.p) #print('scrypted IK_key : %s' % str(codecs.encode(scrypted_intermediate_key,"hex")).upper()) #print('scrypted IK_key_iv : %s' % str(codecs.encode(scrypted_intermediate_key_iv,"hex")).upper()) # do the decrypt cipher = EVP.Cipher(alg='aes_128_cbc', key=key, iv=iv, op=0) # 0 is DEC cipher.set_padding(padding=0) decKey = cipher.update(cf.cryptoKey) decKey = decKey + cipher.final() #print('DKEY : %s' % str(codecs.encode(decKey,"hex")).upper()) return decKey
def main(keylen, hashalg): global dsa, dgst # this exists ONLY for speed testing Rand.load_file('randpool.dat', -1) pvtkeyfilename = 'DSA%dpvtkey.pem' % (keylen) pubkeyfilename = 'DSA%dpubkey.pem' % (keylen) if makenewkey: print ' making and saving a new key' dsa = DSA.gen_params(keylen) dsa.gen_key() dsa.save_key(pvtkeyfilename, None) # no pswd callback dsa.save_pub_key(pubkeyfilename) else: print ' loading an existing key' dsa = DSA.load_key(pvtkeyfilename) print ' dsa key length:', len(dsa) if not dsa.check_key(): raise 'key is not initialised' if showpubkey: dsa_pub = dsa.pub pub_pem = base64.encodestring(dsa_pub) print ' PEM public key is: \n', pub_pem # 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(dsa, dgst) # test_asn1(dsa, dgst) test_speed(dsa, dgst) Rand.save_file('randpool.dat')