def test_compute_key(self): a = EC.load_key(self.privkey) b = EC.gen_params(EC.NID_sect233k1) b.gen_key() ak = a.compute_dh_key(b.pub()) bk = b.compute_dh_key(a.pub()) self.assertEqual(ak, bk)
def _has_EC_support(self): has_ec_support = True # U2F needs OpenSSL 1.0.0 or higher # The EC OpenSSL API calls made by M2Crypto don't work with OpenSSl 0.9.8! version_text = m2.OPENSSL_VERSION_TEXT match = re.match(r"OpenSSL (?P<version>\d\.\d\.\d)", version_text) if match is None: # Fail on unknown OpenSSL version string format self.fail( "Could not detect OpenSSL version - unknown version string format: '%s'" % version_text) else: if match.group('version')[0] == '0': has_ec_support = False # The following command needs support for ECDSA in openssl! # Since Red Hat systems (including Fedora) use an openssl version without # support for the NIST P-256 elliptic curve (as of March 2015), # this command will fail with a NULL pointer exception on these systems try: EC.load_key_bio(BIO.MemoryBuffer(self.ATTESTATION_PRIVATE_KEY_PEM)) except ValueError: has_ec_support = False return has_ec_support
def test_compute_key(self): a = EC.load_key(self.privkey) b = EC.gen_params(EC.NID_sect233k1) b.gen_key() ak = a.compute_dh_key(b.pub()) bk = b.compute_dh_key(a.pub()) assert ak == bk
def test_compute_key(self): a = EC.load_key(self.privkey) b = EC.gen_params(tested_curve[0]) b.gen_key() ak = a.compute_dh_key(b.pub()) bk = b.compute_dh_key(a.pub()) self.assertEqual(ak, bk)
def test_compute_key(self): a = EC.load_key(self.privkey) b = EC.gen_params(EC.NID_X9_62_prime256v1) b.gen_key() ak = a.compute_dh_key(b.pub()) bk = b.compute_dh_key(a.pub()) assert ak == bk
def _register(self, data): client_param = data[:32] app_param = data[32:] # ECC key generation privu = EC.gen_params(CURVE) privu.gen_key() pub_key = str(privu.pub().get_der())[-65:] # Store key_handle = os.urandom(64) bio = BIO.MemoryBuffer() privu.save_key_bio(bio, None) self.data['keys'][key_handle.encode('hex')] = { 'priv_key': bio.read_all(), 'app_param': app_param.encode('hex') } self._persist() # Attestation signature cert_priv = EC.load_key_bio(BIO.MemoryBuffer(CERT_PRIV)) cert = CERT digest = H(chr(0x00) + app_param + client_param + key_handle + pub_key) signature = cert_priv.sign_dsa_asn1(digest) raw_response = chr(0x05) + pub_key + chr(len(key_handle)) + \ key_handle + cert + signature return raw_response
def _test_sign_dsa(self): ec = EC.gen_params(EC.NID_sect233k1) # ec.gen_key() self.assertRaises(EC.ECError, ec.sign_dsa, self.data) ec = EC.load_key(self.privkey) r, s = ec.sign_dsa(self.data) assert ec.verify_dsa(self.data, r, s) assert not ec.verify_dsa(self.data, s, r)
def _test_sign_dsa(self): ec = EC.gen_params(EC.NID_X9_62_prime256v1) # ec.gen_key() self.assertRaises(EC.ECError, ec.sign_dsa, self.data) ec = EC.load_key(self.privkey) r, s = ec.sign_dsa(self.data) assert ec.verify_dsa(self.data, r, s) assert not ec.verify_dsa(self.data, s, r)
def _test_sign_dsa(self): ec = EC.gen_params(tested_curve[0]) # ec.gen_key() with self.assertRaises(EC.ECError): ec.sign_dsa(self.data) ec = EC.load_key(self.privkey) r, s = ec.sign_dsa(self.data) assert ec.verify_dsa(self.data, r, s) assert not ec.verify_dsa(self.data, s, r)
def __init__(self,port,testcase): Thread.__init__(self) self.setDaemon(True) self.testcase = testcase self.port = port self.my_keypair = EC.gen_params(EC.NID_sect233k1) self.my_keypair.gen_key() self.other_keypair = EC.gen_params(EC.NID_sect233k1) self.other_keypair.gen_key()
def test_pubkey_from_der(self): a = EC.gen_params(EC.NID_sect233k1) a.gen_key() b = EC.gen_params(EC.NID_sect233k1) b.gen_key() a_pub_der = a.pub().get_der() a_pub = EC.pub_key_from_der(a_pub_der) ak = a.compute_dh_key(b.pub()) bk = b.compute_dh_key(a_pub) assert ak == bk
def __init__(self, port, testcase): Thread.__init__(self) self.setDaemon(True) self.testcase = testcase self.port = port self.my_keypair = EC.gen_params(EC.NID_sect233k1) self.my_keypair.gen_key() self.other_keypair = EC.gen_params(EC.NID_sect233k1) self.other_keypair.gen_key()
def test_pubkey_from_der(self): a = EC.gen_params(EC.NID_X9_62_prime256v1) a.gen_key() b = EC.gen_params(EC.NID_X9_62_prime256v1) b.gen_key() a_pub_der = a.pub().get_der() a_pub = EC.pub_key_from_der(a_pub_der) ak = a.compute_dh_key(b.pub()) bk = b.compute_dh_key(a_pub) assert ak == bk
def test_pubkey_from_der(self): a = EC.gen_params(tested_curve[0]) a.gen_key() b = EC.gen_params(tested_curve[0]) b.gen_key() a_pub_der = a.pub().get_der() a_pub = EC.pub_key_from_der(a_pub_der) ak = a.compute_dh_key(b.pub()) bk = b.compute_dh_key(a_pub) self.assertEqual(ak, bk)
def test_pubkey_from_der(self): a = EC.gen_params(EC.NID_sect233k1) a.gen_key() b = EC.gen_params(EC.NID_sect233k1) b.gen_key() a_pub_der = a.pub().get_der() a_pub = EC.pub_key_from_der(a_pub_der) ak = a.compute_dh_key(b.pub()) bk = b.compute_dh_key(a_pub) self.assertEqual(ak, bk)
def test_pub_key_from_params(self): curve = EC.NID_prime256v1 ec = EC.gen_params(curve) ec.gen_key() ec_pub = ec.pub() k = ec_pub.get_key() ec2 = EC.pub_key_from_params(curve, k) assert ec2.check_key() r, s = ec.sign_dsa(self.data) assert ec2.verify_dsa(self.data, r, s)
def test_u2f_unsupported_openssl_missing_curve(self): """ Try registration with an OpenSSL missing the NIST P-256 curve and check the error messages """ skip_test = True # Only allow OpenSSL >=1.0.0 with missing EC support version_text = m2.OPENSSL_VERSION_TEXT match = re.match(r"OpenSSL (?P<version>\d\.\d\.\d)", version_text) if match is None: # Fail on unknown OpenSSL version string format self.fail("Could not detect OpenSSL version - unknown version string format: '%s'" % version_text) else: if match.group("version")[0] != "0": # Only run test on missing NIST P-256 curve support try: EC.load_key_bio(BIO.MemoryBuffer(self.ATTESTATION_PRIVATE_KEY_PEM)) except ValueError: skip_test = False if skip_test: self.skipTest("This test can only be run with OpenSSL missing the " "NIST P-256 curve!") # Initial token registration step response_registration1_JSON = self._registration1() self.assertTrue('"value": true' in response_registration1_JSON, "Response: %r" % response_registration1_JSON) self.assertTrue('"challenge":' in response_registration1_JSON, "Response: %r" % response_registration1_JSON) self.assertTrue('"serial":' in response_registration1_JSON, "Response: %r" % response_registration1_JSON) response_registration1 = json.loads(response_registration1_JSON.body) challenge_registration = response_registration1.get("detail", {}).get("challenge") self.serial = response_registration1.get("detail", {}).get("serial") self.serials.add(self.serial) client_data_registration = self._createClientDataObject("registration", challenge_registration) # Since we have no supported OpenSSL version to calculate the registration response # we use a hard-coded correctly-formed fake registration response registration_response = binascii.unhexlify(self.FAKE_REGISTRATION_DATA_HEX) registration_response_message = { "registrationData": base64.urlsafe_b64encode(registration_response), "clientData": base64.urlsafe_b64encode(client_data_registration), } # Complete the token registration response_registration2_JSON = self._registration2(json.dumps(registration_response_message)) # Registration must fail self.assertTrue('"status": false' in response_registration2_JSON, "Response: %r" % response_registration2_JSON) # Check for correct error messages self.assertTrue( "missing ECDSA support for the NIST P-256 curve in OpenSSL" in response_registration2_JSON, "Response: %r" % response_registration2_JSON, )
def __init__(self, s6a_proxy_stub: s6a_proxy_pb2_grpc.S6aProxyStub): logging.info("starting brokerd servicer") self._s6a_proxy_stub = s6a_proxy_stub key_dir = os.getenv('KEY_DIR', '/var/opt/magma/key_files') self.br_rsa_pri_key = RSA.load_key(os.path.join(key_dir, 'br_rsa_pri.pem')) self.br_ecdsa_pri_key = EC.load_key(os.path.join(key_dir, 'br_ec_pri.pem')) self.ue_rsa_pub_key = RSA.load_pub_key(os.path.join(key_dir, 'ue_rsa_pub.pem')) self.ue_ecdsa_pub_key = EC.load_pub_key(os.path.join(key_dir, 'ue_ec_pub.pem')) self.ut_rsa_pub_key = RSA.load_pub_key(os.path.join(key_dir, 'ut_rsa_pub.pem')) self.ut_ecdsa_pub_key = EC.load_pub_key(os.path.join(key_dir, 'ut_ec_pub.pem')) self.br_id = 0 logging.info("done loading broker keys")
def test(): print 'generating ec keys:' a=EC.gen_params(EC.NID_sect233k1) a.gen_key() b=EC.gen_params(EC.NID_sect233k1) b.gen_key() a_shared_key = a.compute_dh_key(b.pub()) b_shared_key = b.compute_dh_key(a.pub()) print 'shared key according to a = ', `a_shared_key` print 'shared key according to b = ', `b_shared_key` if a_shared_key == b_shared_key: print 'ok' else: print 'not ok'
def register( self, data, facet="https://www.example.com", ): """ data = { "version": "U2F_V2", "challenge": string, //b64 encoded challenge "appId": string, //app_id } """ if isinstance(data, basestring): data = json.loads(data) if data['version'] != "U2F_V2": raise ValueError("Unsupported U2F version: %s" % data['version']) # Client data client_data = { 'typ': "navigator.id.finishEnrollment", 'challenge': data['challenge'], 'origin': facet } client_data = json.dumps(client_data) client_param = H(client_data) # ECC key generation privu = EC.gen_params(CURVE) privu.gen_key() pub_key = str(privu.pub().get_der())[-65:] # Store key_handle = rand_bytes(64) app_param = H(data['appId']) self.keys[key_handle] = (privu, app_param) # Attestation signature cert_priv = EC.load_key_bio(BIO.MemoryBuffer(CERT_PRIV)) cert = CERT digest = H(chr(0x00) + app_param + client_param + key_handle + pub_key) signature = cert_priv.sign_dsa_asn1(digest) raw_response = chr(0x05) + pub_key + chr(len(key_handle)) + \ key_handle + cert + signature return json.dumps({ "registrationData": websafe_encode(raw_response), "clientData": websafe_encode(client_data), })
def __init__(self, curve=None, keystring=None, filename=None): if curve: self.ec = EC.gen_params(curve) self.ec.gen_key() elif keystring: self.ec = self.key_from_pem( "-----BEGIN EC PRIVATE KEY-----\n%s-----END EC PRIVATE KEY-----\n" % keystring.encode("BASE64")) elif filename: # this workaround is needed to run Tribler on Windows 64 bit membuf = BIO.MemoryBuffer(open(filename, 'rb').read()) self.ec = EC.load_key_bio(membuf) membuf.close()
def load_pub_key(pem_x509): """ PEM形式のX.509 証明書から、ECパブリックキーを取得します""" from M2Crypto import X509 from M2Crypto import EC x509 = X509.load_cert_string(pem_x509) return EC.pub_key_from_der(x509.get_pubkey().as_der())
def verify_data(message, signature, bitcoin_address, cs_pem_data=None): if cs_pem_data is None: # Get CS from the ACA (pem data base64 encoded) cs_pem_data = get_cs_pem_data(bitcoin_address) # Get CA certificates from the ACA (pem data base64 encoded) ca_pem_data = get_ca_pem_data() # If the data could not be obtained from the server if type(ca_pem_data) is urllib2.URLError or type( cs_pem_data) is urllib2.URLError: ca_verify = cs_verify = False else: # Store received data in X509 structure cs_certificate = X509.load_cert_string(cs_pem_data) ca_certificate = X509.load_cert_string(ca_pem_data) # Get CS public key from received data cs_public_key = EC.pub_key_from_der( cs_certificate.get_pubkey().as_der()) # Verify CA signature in CS certificate and CS signature in data sent ca_verify = cs_certificate.verify(ca_certificate.get_pubkey()) cs_verify = cs_public_key.verify_dsa_asn1(message, signature) return {'ca': ca_verify, 'cs': cs_verify}
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 check_response1(self, resp1_data, rB, myid): resp1 = bdecode(resp1_data) self.assert_(type(resp1) == DictType) self.assert_(resp1.has_key('certA')) self.assert_(resp1.has_key('rA')) self.assert_(resp1.has_key('B')) self.assert_(resp1.has_key('SA')) # show throw exception when key no good pubA = EC.pub_key_from_der(resp1['certA']) rA = resp1['rA'] self.assert_(type(rA) == StringType) self.assert_(len(rA) == random_size) B = resp1['B'] self.assert_(type(B) == StringType) self.assert_(B, myid) SA = resp1['SA'] self.assert_(type(SA) == StringType) # verify signature sig_list = [rA, rB, myid] sig_data = bencode(sig_list) sig_hash = sha(sig_data).digest() self.assert_(pubA.verify_dsa_asn1(sig_hash, SA)) # Cannot resign the data with his keypair to double check. Signing # appears to yield different, supposedly valid sigs each time. return resp1
def ec_generate_key(security): """ Generate a new Elliptic Curve object with a new public / private key pair. Security can be u'low', u'medium', or u'high' depending on how secure you need your Elliptic Curve to be. Currently these values translate into: - very-low: NID_sect163k1 ~42 byte signatures - low: NID_sect233k1 ~60 byte signatures - medium: NID_sect409k1 ~104 byte signatures - high: NID_sect571r1 ~144 byte signatures Besides these predefined curves, all other curves provided by M2Crypto are also available. For a full list of available curves, see ec_get_curves(). @param security: Level of security {u'very-low', u'low', u'medium', or u'high'}. @type security: unicode @note that the NID must always be 160 bits or more, otherwise it will not be able to sign a sha1 digest. """ assert isinstance(security, unicode) assert security in _CURVES ec = EC.gen_params(_CURVES[security]) ec.gen_key() return ec
def __init__(self, nid_or_path=None): """nid_or_path is either a nid to create a new key or a path to a pem encoded key""" self._key = None # we don't have anything to initialize anymore if type(nid_or_path) == type(None): return # do nothing elif type(nid_or_path) == int: self._key = EC.gen_params(nid_or_path) self._key.gen_key() elif type(nid_or_path) == str: # the string is a DER public key ? # OID == 1.2.840.10045.2.1 # encoder.encode(univ.ObjectIdentifier("1.2.840.10045.2.1")) if nid_or_path.startswith("\x30") and "\x06\x07\x2a\x86\x48\xce\x3d\x02\x01" in nid_or_path: self.PubKey_from_DER(nid_or_path) # the string is a PEM key ? elif "-----BEGIN EC PRIVATE KEY-----" in nid_or_path: self.from_PEM(nid_or_path) elif "-----BEGIN PUBLIC KEY-----" in nid_or_path: self.PubKey_from_PEM(nid_or_path) else: # the string is a path ? with open(nid_or_path) as f: self.from_PEM(f.read()) elif isinstance(nid_or_path, ECCkey): self.from_PEM(nid_or_path.to_PEM()) else: raise ECCException("ECCkey should be instanciated py a NID number or a path to a valid EC key" "")
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 key_from_pem(self, pem): "Get the EC from a public/private keypair stored in the PEM." def get_password(*args): return "" return EC.load_key_bio(BIO.MemoryBuffer(pem), get_password)
def mk_ec_pair(): priv_key = EC.gen_params(tested_curve[0]) priv_key.gen_key() priv_key.save_key('ec.priv.pem', callback=util.no_passphrase_callback) pub_key = priv_key.pub() pub_key.save_pub_key('ec.pub.pem')
def genkey(self, curveName, curveLen): curve = getattr(EC, 'NID_' + curveName) ec = EC.gen_params(curve) assert len(ec) == curveLen ec.gen_key() assert ec.check_key(), 'check_key() failure for "%s"' % curveName return ec
def load_key(pem): """ PEM形式のECプライベートキーを読み込みます """ from M2Crypto import EC, BIO bio = BIO.IOBuffer(BIO.MemoryBuffer(pem)) key = EC.load_key_bio(bio) return key
def _authenticate(self, data): client_param = data[:32] app_param = data[32:64] kh_len = ord(data[64]) key_handle = data[65:65 + kh_len].encode('hex') if key_handle not in self.data['keys']: raise ValueError("Unknown key handle!") # Unwrap: unwrapped = self.data['keys'][key_handle] if app_param != unwrapped['app_param'].decode('hex'): raise ValueError("Incorrect app param!") priv_pem = unwrapped['priv_key'].encode('ascii') privu = EC.load_key_bio(BIO.MemoryBuffer(priv_pem)) # Increment counter self.data['counter'] += 1 self._persist() # Create signature touch = chr(1) # Always indicate user presence counter = struct.pack('>I', self.data['counter']) digest = H(app_param + touch + counter + client_param) signature = privu.sign_dsa_asn1(digest) raw_response = touch + counter + signature return raw_response
def encrypt(self,message,encryptor): if self._pubkey == None or self._pubkey_curve == None: # To send message via PublicKey, We must know it's curve. return False # Get a temp. key tempkey = EC.gen_params(self._pubkey_curve) tempkey.gen_key() sharedsecret = tempkey.compute_dh_key(self._pubkey) log.debug("Length of key is: %d",(len(sharedsecret) * 8)) # Encrypt ciphertext = encryptor(sharedsecret,message) # Get tempkey's public key. membuff = BIO.MemoryBuffer() tempkey.save_pub_key_bio(membuff) publickey = membuff.read_all() #open(filename).read() # Return with serializer. ret = serializer.dumps( { 'type':'EC_Encrypted', 'public_key':publickey, 'ciphertext':ciphertext, } ) return ret
def ec_from_private_pem(pem, password=None): "Get the EC from a private PEM." def get_password(*args): return password or "" return EC.load_key_bio(BIO.MemoryBuffer(pem), get_password)
def genkey(self, curveName, curveLen): curve = getattr(EC, 'NID_'+curveName) ec = EC.gen_params(curve) assert len(ec) == curveLen ec.gen_key() assert ec.check_key(), 'check_key() failure for "%s"' % curveName return ec
def _constructEcFromRawKey(self, rawPublicKey): assert(len(rawPublicKey) == 64) bytes1 = a2b_hex("3059301306072a8648ce3d020106082a8648ce3d03010703420004") asn1KeyBytes = bytes1 + rawPublicKey pemPubKeyBytes = PEMEncoder(asn1KeyBytes).getEncoded("PUBLIC KEY") return EC.load_pub_key_bio(BIO.MemoryBuffer(pemPubKeyBytes))
def mk_ec_pair(): priv_key = EC.gen_params(EC.NID_secp384r1) priv_key.gen_key() priv_key.save_key('ec.priv.pem', callback=util.no_passphrase_callback) pub_key = priv_key.pub() pub_key.save_pub_key('ec.pub.pem')
def __init__(self): """ Initialize the s1aplibrary and its callbacks. """ lib_path = os.environ["S1AP_TESTER_ROOT"] lib = os.path.join(lib_path, "bin", S1ApUtil.lib_name) os.chdir(lib_path) self._test_lib = ctypes.cdll.LoadLibrary(lib) self._callback_type = ctypes.CFUNCTYPE(None, ctypes.c_short, ctypes.c_void_p, ctypes.c_short) # Maintain a reference to the function object so GC doesn't release it. self._callback_fn = self._callback_type(S1ApUtil.s1ap_callback) self._test_lib.initTestFrameWork(self._callback_fn) self._test_api = self._test_lib.tfwApi self._test_api.restype = ctypes.c_int16 self._test_api.argtypes = [ctypes.c_uint16, ctypes.c_void_p] # Mutex for state change operations self._lock = threading.RLock() # Maintain a map of UE IDs to IPs self._ue_ip_map = {} # added for brokerd utelco self.br_rsa_pub_key = RSA.load_pub_key( expanduser('~/key_files/br_rsa_pub.pem')) self.ue_ecdsa_pri_key = EC.load_key( expanduser('~/key_files/ue_ec_pri.pem')) self.ut_rsa_pub_key = RSA.load_pub_key( expanduser('~/key_files/ut_rsa_pub.pem'))
def setUpPostSession(self): """ override TestAsServer """ TestCrawler.setUpPostSession(self) self.some_keypair = EC.gen_params(EC.NID_sect233k1) self.some_keypair.gen_key() self.some_permid = str(self.some_keypair.pub().get_der()) self.friendshipStatistics_db = FriendshipStatisticsDBHandler.getInstance( ) self.friendshipStatistics_db.insertFriendshipStatistics( bin2str(self.his_permid), bin2str(self.some_permid), int(time.time()), 0, commit=True) self.friendshipStatistics_db.insertFriendshipStatistics( bin2str(self.my_permid), bin2str(self.some_permid), int(time.time()), 0, commit=True) # make sure that the OLConnection IS in the crawler_db crawler_db = CrawlerDBHandler.getInstance() crawler_db.temporarilyAddCrawler(self.my_permid)
def check_response1(self, resp1_data, rB, myid): resp1 = bdecode(resp1_data) self.assert_(type(resp1) == DictType) self.assert_(resp1.has_key("certA")) self.assert_(resp1.has_key("rA")) self.assert_(resp1.has_key("B")) self.assert_(resp1.has_key("SA")) # show throw exception when key no good pubA = EC.pub_key_from_der(resp1["certA"]) rA = resp1["rA"] self.assert_(type(rA) == StringType) self.assert_(len(rA) == random_size) B = resp1["B"] self.assert_(type(B) == StringType) self.assert_(B, myid) SA = resp1["SA"] self.assert_(type(SA) == StringType) # verify signature sig_list = [rA, rB, myid] sig_data = bencode(sig_list) sig_hash = sha(sig_data).digest() self.assert_(pubA.verify_dsa_asn1(sig_hash, SA)) # Cannot resign the data with his keypair to double check. Signing # appears to yield different, supposedly valid sigs each time. return resp1
def _derive_pubkey(self): # derive EC public key instance from self._key if self._key == None: return False membuff = BIO.MemoryBuffer() self._key.save_pub_key_bio(membuff) #(filename) self._pubkey = EC.load_pub_key_bio(membuff) #filename)
def create_torrent_signature(metainfo,keypairfilename): keypair = EC.load_key(keypairfilename) bmetainfo = bencode(metainfo) digester = sha(bmetainfo[:]) digest = digester.digest() sigstr = keypair.sign_dsa_asn1(digest) metainfo['signature'] = sigstr metainfo['signer'] = str(keypair.pub().get_der())
def register(self, data, facet="https://www.example.com", ): """ data = { "version": "U2F_V2", "challenge": string, //b64 encoded challenge "appId": string, //app_id } """ if isinstance(data, basestring): data = json.loads(data) if data['version'] != "U2F_V2": raise ValueError("Unsupported U2F version: %s" % data['version']) # Client data client_data = { 'typ': "navigator.id.finishEnrollment", 'challenge': data['challenge'], 'origin': facet } client_data = json.dumps(client_data) client_param = H(client_data) # ECC key generation privu = EC.gen_params(CURVE) privu.gen_key() pub_key = str(privu.pub().get_der())[-65:] # Store key_handle = rand_bytes(64) app_param = H(data['appId']) self.keys[key_handle] = (privu, app_param) # Attestation signature cert_priv = EC.load_key_bio(BIO.MemoryBuffer(CERT_PRIV)) cert = CERT digest = H(chr(0x00) + app_param + client_param + key_handle + pub_key) signature = cert_priv.sign_dsa_asn1(digest) raw_response = chr(0x05) + pub_key + chr(len(key_handle)) + \ key_handle + cert + signature return json.dumps({ "registrationData": websafe_encode(raw_response), "clientData": websafe_encode(client_data), })
def main(curve, hashalg): global ec, dgst # this exists ONLY for speed testing Rand.load_file('randpool.dat', -1) if curve in curves2: curve = 'X9_62_' + curve ec_curve = eval('EC.NID_%s' % curve) pvtkeyfilename = '%spvtkey.pem' % (curve) pubkeyfilename = '%spubkey.pem' % (curve) if makenewkey: print ' making and saving a new key' ec = EC.gen_params(ec_curve) ec.gen_key() ec.save_key(pvtkeyfilename, None) ec.save_pub_key(pubkeyfilename) else: print ' loading an existing key' ec = EC.load_key(pvtkeyfilename) print ' ecdsa key length:', len(ec) print ' curve: %s' % curve if not ec.check_key(): raise 'key is not initialised' if showpubkey: ec_pub = ec.pub() pub_der = ec_pub.get_der() pub_pem = base64.encodestring(pub_der) 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' % (base64.encodestring(dgst)) test(ec, dgst) # test_asn1(ec, dgst) test_speed(ec, dgst) Rand.save_file('randpool.dat')
def create_torrent_signature(response, keypairfilename): keypair = EC.load_key(keypairfilename) bresponse = bencode(response) digester = sha(bresponse[:]) digest = digester.digest() sigstr = keypair.sign_dsa_asn1(digest) response['signature'] = sigstr response['signer'] = str(keypair.pub().get_der())
def main(curve, hashalg): global ec, dgst # this exists ONLY for speed testing Rand.load_file('randpool.dat', -1) if curve in curves2: curve = 'X9_62_' + curve ec_curve = eval('EC.NID_%s' % curve) pvtkeyfilename = '%spvtkey.pem' % (curve) pubkeyfilename = '%spubkey.pem' % (curve) if makenewkey: print ' making and saving a new key' ec = EC.gen_params(ec_curve) ec.gen_key() ec.save_key(pvtkeyfilename, None ) ec.save_pub_key(pubkeyfilename) else: print ' loading an existing key' ec=EC.load_key(pvtkeyfilename) print ' ecdsa key length:', len(ec) print ' curve: %s' % curve if not ec.check_key(): raise 'key is not initialised' if showpubkey: ec_pub = ec.pub() pub_der = ec_pub.get_der() pub_pem = base64.encodestring(pub_der) 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' % (base64.encodestring(dgst)) test(ec, dgst) # test_asn1(ec, dgst) test_speed(ec, dgst) Rand.save_file('randpool.dat')
def _constructEcFromRawKey(self, rawPublicKey): assert (len(rawPublicKey) == 64) bytes1 = a2b_hex( "3059301306072a8648ce3d020106082a8648ce3d03010703420004") asn1KeyBytes = bytes1 + rawPublicKey pemPubKeyBytes = PEMEncoder(asn1KeyBytes).getEncoded("PUBLIC KEY") return EC.load_pub_key_bio(BIO.MemoryBuffer(pemPubKeyBytes))
def register(self, request, facet="https://www.example.com"): """ RegisterRequest = { "version": "U2F_V2", "challenge": string, //b64 encoded challenge "appId": string, //app_id } """ if not isinstance(request, RegisterRequest): request = RegisterRequest(request) if request.version != "U2F_V2": raise ValueError("Unsupported U2F version: %s" % request.version) # Client data client_data = ClientData( typ='navigator.id.finishEnrollment', challenge=request['challenge'], origin=facet ) client_data = client_data.json client_param = H(client_data) # ECC key generation privu = EC.gen_params(CURVE) privu.gen_key() pub_key = str(privu.pub().get_der())[-65:] # Store key_handle = rand_bytes(64) app_param = request.appParam self.keys[key_handle] = (privu, app_param) # Attestation signature cert_priv = EC.load_key_bio(BIO.MemoryBuffer(CERT_PRIV)) cert = CERT digest = H(chr(0x00) + app_param + client_param + key_handle + pub_key) signature = cert_priv.sign_dsa_asn1(digest) raw_response = chr(0x05) + pub_key + chr(len(key_handle)) + \ key_handle + cert + signature return RegisterResponse( registrationData=websafe_encode(raw_response), clientData=websafe_encode(client_data), )
def register(self, request, facet="https://www.example.com"): """ RegisterRequest = { "version": "U2F_V2", "challenge": string, //b64 encoded challenge "appId": string, //app_id } """ if not isinstance(request, RegisterRequest): request = RegisterRequest(request) if request.version != "U2F_V2": raise ValueError("Unsupported U2F version: %s" % request.version) # Client data client_data = ClientData(typ='navigator.id.finishEnrollment', challenge=request['challenge'], origin=facet) client_data = client_data.json client_param = H(client_data) # ECC key generation privu = EC.gen_params(CURVE) privu.gen_key() pub_key = str(privu.pub().get_der())[-65:] # Store key_handle = rand_bytes(64) app_param = request.appParam self.keys[key_handle] = (privu, app_param) # Attestation signature cert_priv = EC.load_key_bio(BIO.MemoryBuffer(CERT_PRIV)) cert = CERT digest = H(chr(0x00) + app_param + client_param + key_handle + pub_key) signature = cert_priv.sign_dsa_asn1(digest) raw_response = chr(0x05) + pub_key + chr(len(key_handle)) + \ key_handle + cert + signature return RegisterResponse( registrationData=websafe_encode(raw_response), clientData=websafe_encode(client_data), )
def generateECKeyPair(self): # Generate M2Crypto.EC.EC object ec = EC.gen_params(EC.NID_X9_62_prime256v1) ec.gen_key() rawPrivateKey, rawPublicKey = self._constructRawKeysFromEc(ec) return ECPublicKey(rawPublicKey, ec), ECPrivateKey(rawPrivateKey, rawPublicKey, ec)
def _dnskey_to_ec(alg, key): if alg == 13: curve = EC.NID_X9_62_prime256v1 elif alg == 14: curve = EC.NID_secp384r1 else: raise ValueError('Algorithm not supported') return EC.pub_key_from_params(curve, EC_NOCOMPRESSION + key)