示例#1
0
 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
示例#2
0
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())
示例#3
0
文件: dcs.py 项目: sr-gi/paysense
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}
示例#4
0
 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
示例#5
0
def com_auth(request):
	#the user HaiChiang is fixed in the database
	user = User.objects.get(userName='******')
	print 'LOG:Chanllenge --------------' +  user.challenge
	
	#to do 
	print 'LOG:com_auth -------------- from ' +  getClientIp(request)
	
	result = 0
	if request.method == 'POST':
		data = json.loads(request.body)
		
		#
		#processing keyhandle
		#
		keyhandle = urlsafe_b64decode(data['keyhandle'].encode('utf-8'))
 		print 'LOG:key_handle ------------- ' + keyhandle
		 
		
		#
		#processing clientdata
		#
		
		#convert the clientdata to a dict structure
		clientdata = urlsafe_b64decode(data['clientData'].encode('utf-8'))
		#clientdata_dict = eval(clientdata)
 		print 'LOG:clientData ------------- ' + clientdata
		
		#
		#processing signature
		#
		signature = urlsafe_b64decode(data['signature'].encode('utf-8'))
		print 'LOG:signature ------------- ' + signature
		
		
		#public key 
		prefix = "3059301306072a8648ce3d020106082a8648ce3d030107034200".decode('hex')
		tail_key = '04EC4FDC9FBDECFE8F21B178693703733C0E3A96BE41590CCF98DCFB2DA8A19BA8A3854E8B5E57D1E01AEDCA8F28B0B643BC890174A08018C34F91D0A79D064548'.decode('hex')
		ec = EC.pub_key_from_der(prefix + tail_key)
		
		#msg
		app_para = ''
		user_presence = ''
		counter = ''
		challen_para = ''
		#msg = app_para + user_presence + counter + challen_para
		msg = '002122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F400102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F200000000004EC4FDC9FBDECFE8F21B178693703733C0E3A96BE41590CCF98DCFB2DA8A19BA8A3854E8B5E57D1E01AEDCA8F28B0B643BC890174A08018C34F91D0A79D064548'.decode('hex')
		h = sha256()
		h.update(msg)
		
		#signature
		sig = '304402206613ECA917F891ABADEAB63054CE7DFE3F32268FCE7D0AF4B37C6000C9D13B2B022067E717B413597268EF28EC72EE79135EB87026DB14E64776C15CD7335D95402A'.decode('hex')
		
		#verify
		result =  ec.verify_dsa_asn1(h.digest(), sig)
		
	
	return HttpResponse(result)
示例#6
0
 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, piecelen, npieces, keypair = None, pubkeypem = None):
     print >> sys.stderr, 'ECDSAAuth: npieces', npieces
     Authenticator.__init__(self, piecelen, npieces)
     self.contentblocksize = piecelen - self.OUR_SIGSIZE
     self.keypair = keypair
     if pubkeypem is not None:
         self.pubkey = EC.pub_key_from_der(pubkeypem)
     else:
         self.pubkey = None
     self.startts = None
示例#8
0
 def verify_with_pub_key(pubkey, digest, r, s):
     '''Verify the given digest using ECDSA. r and s are the ECDSA signature parameters.
        if verified, return 1.
     '''
     try:
         if isinstance(pubkey, bytes):
             pubkey = EC.pub_key_from_der(buffer(pubkey))
         return pubkey.verify_dsa(digest, r, s)
     except:
         return 0
示例#9
0
 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)
示例#10
0
 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)
示例#11
0
 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)
示例#12
0
文件: encrypt.py 项目: temp321/fwlite
 def verify_with_pub_key(pubkey, digest, r, s):
     '''Verify the given digest using ECDSA. r and s are the ECDSA signature parameters.
        if verified, return 1.
     '''
     try:
         if isinstance(pubkey, bytes):
             pubkey = EC.pub_key_from_der(buffer(pubkey))
         return pubkey.verify_dsa(digest, r, s)
     except:
         return 0
示例#13
0
 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
示例#14
0
 def __init__(self, piecelen, npieces, keypair=None, pubkeypem=None):
     print >> sys.stderr, 'ECDSAAuth: npieces', npieces
     Authenticator.__init__(self, piecelen, npieces)
     self.contentblocksize = piecelen - self.OUR_SIGSIZE
     self.keypair = keypair
     if pubkeypem is not None:
         self.pubkey = EC.pub_key_from_der(pubkeypem)
     else:
         self.pubkey = None
     self.startts = None
示例#15
0
文件: u2ftoken.py 项目: eespinosa/Elm
    def _validateAuthenticationSignature(self,
                                         applicationParameter,
                                         userPresenceByte,
                                         counter,
                                         challengeParameter,
                                         publicKey,
                                         signature
                                         ):
        """
        Internal helper function to validate the authentication signature received after parsing
        the token authentication response according to the U2F specification

        :param applicationParameter: SHA-256 hash of the application identity.
        :param userPresenceByte:     The user presence byte as received in the authentication
                                     response
        :param challengeParameter:   SHA-256 hash of the Client Data, a stringified JSON data
                                     structure prepared by the FIDO Client.
        :param publicKey:            The user public key retrieved on parsing the registration data
        :param signature:            The signature to be verified as retrieved on parsing the
                                     authentication response
        """
        # add ASN1 prefix
        PUB_KEY_ASN1_PREFIX = "3059301306072a8648ce3d020106082a8648ce3d030107034200".decode('hex')
        publicKey = PUB_KEY_ASN1_PREFIX + publicKey

        # Check for OpenSSL version 1.0.0 or higher
        if not self._is_supported_openssl_version():
            log.error("This version of OpenSSL is not supported! OpenSSL version 1.0.0 or higher "
                      "is required for the U2F token.")
            raise Exception("This version of OpenSSL is not supported! OpenSSL version 1.0.0 or "
                            "higher is required for the U2F token.")

        try:
            # 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 curve (as of March 2015), this command will fail
            # with a NULL pointer exception on these systems
            ECPubKey = EC.pub_key_from_der(publicKey)
        except ValueError as ex:
            log.error(
                "Could not get ECPubKey. Possibly missing ECDSA support for the NIST P-256 "
                "curve in OpenSSL? %r", ex)
            raise Exception(
                "Could not get ECPubKey. Possibly missing ECDSA support for the NIST P-256 "
                "curve in OpenSSL? %r" % ex)

        # According to the FIDO U2F specification the signature is a ECDSA signature on the
        # NIST P-256 curve over the SHA256 hash of the following byte string
        toBeVerified = sha256(
            applicationParameter + userPresenceByte + counter + challengeParameter).digest()
        if ECPubKey.verify_dsa_asn1(toBeVerified, signature) != 1:
            log.debug("Signature verification failed!")
            return False
        return True
示例#16
0
    def _validateAuthenticationSignature(self,
                                         applicationParameter,
                                         userPresenceByte,
                                         counter,
                                         challengeParameter,
                                         publicKey,
                                         signature
                                         ):
        """
        Internal helper function to validate the authentication signature received after parsing
        the token authentication response according to the U2F specification

        :param applicationParameter: SHA-256 hash of the application identity.
        :param userPresenceByte:     The user presence byte as received in the authentication
                                     response
        :param challengeParameter:   SHA-256 hash of the Client Data, a stringified JSON data
                                     structure prepared by the FIDO Client.
        :param publicKey:            The user public key retrieved on parsing the registration data
        :param signature:            The signature to be verified as retrieved on parsing the
                                     authentication response
        """
        # add ASN1 prefix
        PUB_KEY_ASN1_PREFIX = "3059301306072a8648ce3d020106082a8648ce3d030107034200".decode('hex')
        publicKey = PUB_KEY_ASN1_PREFIX + publicKey

        # Check for OpenSSL version 1.0.0 or higher
        if not self._is_supported_openssl_version():
            log.error("This version of OpenSSL is not supported! OpenSSL version 1.0.0 or higher "
                      "is required for the U2F token.")
            raise Exception("This version of OpenSSL is not supported! OpenSSL version 1.0.0 or "
                            "higher is required for the U2F token.")

        try:
            # 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 curve (as of March 2015), this command will fail
            # with a NULL pointer exception on these systems
            ECPubKey = EC.pub_key_from_der(publicKey)
        except ValueError as ex:
            log.exception(
                "Could not get ECPubKey. Possibly missing ECDSA support for the NIST P-256 "
                "curve in OpenSSL? %r", ex)
            raise Exception(
                "Could not get ECPubKey. Possibly missing ECDSA support for the NIST P-256 "
                "curve in OpenSSL? %r" % ex)

        # According to the FIDO U2F specification the signature is a ECDSA signature on the
        # NIST P-256 curve over the SHA256 hash of the following byte string
        toBeVerified = sha256(
            applicationParameter + userPresenceByte + counter + challengeParameter).digest()
        if ECPubKey.verify_dsa_asn1(toBeVerified, signature) != 1:
            log.debug("Signature verification failed!")
            return False
        return True
示例#17
0
def do_verify_torrent_signature(digest,sigstr,permid):
    if permid is None:
        return False
    try:
        ecpub = EC.pub_key_from_der(permid)
        if ecpub is None:
            return False
        intret = ecpub.verify_dsa_asn1(digest,sigstr)
        return intret == 1
    except Exception, e:
        print >> sys.stderr,"permid: Exception in verify_torrent_signature:",str(e) 
        return False
示例#18
0
def do_verify_torrent_signature(digest,sigstr,permid):
    if permid is None:
        return False
    try:
        ecpub = EC.pub_key_from_der(permid)
        if ecpub is None:
            return False
        intret = ecpub.verify_dsa_asn1(digest,sigstr)
        return intret == 1
    except Exception, e:
        print >> sys.stderr,time.asctime(),'-', "permid: Exception in verify_torrent_signature:",str(e) 
        return False
示例#19
0
 def verify_csr_signature(self):
     data = chr(0x00) + self.app_param + self.chal_param + \
         self.key_handle + self.pub_key
     pubkey = self.certificate.get_pubkey()
     # TODO: Figure out how to do this using the EVP API.
     # pubkey.verify_init()
     # pubkey.verify_update(data)
     # if not pubkey.verify_final(self.signature) == 1:
     digest = H(data)
     pub_key = EC.pub_key_from_der(pubkey.as_der())
     if not pub_key.verify_dsa_asn1(digest, self.signature) == 1:
         raise Exception('Attestation signature verification failed!')
示例#20
0
 def verify_csr_signature(self):
     data = chr(0x00) + self.app_param + self.chal_param + \
         self.key_handle + self.pub_key
     pubkey = self.certificate.get_pubkey()
     # TODO: Figure out how to do this using the EVP API.
     # pubkey.verify_init()
     # pubkey.verify_update(data)
     # if not pubkey.verify_final(self.signature) == 1:
     digest = H(data)
     pub_key = EC.pub_key_from_der(pubkey.as_der())
     if not pub_key.verify_dsa_asn1(digest, self.signature) == 1:
         raise Exception('Attestation signature verification failed!')
示例#21
0
    def __init__(self, piecelen, npieces, keypair=None, pubkeypem=None):

        print >>sys.stderr, time.asctime(), "-", "ECDSAAuth: npieces", npieces

        Authenticator.__init__(self, piecelen, npieces)
        self.contentblocksize = piecelen - self.OUR_SIGSIZE
        self.keypair = keypair
        if pubkeypem is not None:
            # print >>sys.stderr,time.asctime(),'-', "ECDSAAuth: pubkeypem",`pubkeypem`
            self.pubkey = EC.pub_key_from_der(pubkeypem)
        else:
            self.pubkey = None
        self.seqnum = 0L
示例#22
0
def check_response2(rdata2,randomA,peeridA,randomB,peeridB):
    try:
        response2 = bdecode(rdata2)
    except:
        return None
    if response2['A'] != peeridA:
        return None
    pubB_der = response2['certB']
    pubB = EC.pub_key_from_der(pubB_der)
    sigB = response2['SB']
    if verify_response(randomB,randomA,peeridA,pubB,sigB):
        return pubB
    else:
        return None
示例#23
0
def check_response2(rdata2,randomA,peeridA,randomB,peeridB):
    try:
        response2 = bdecode(rdata2)
    except:
        return None
    if response2['A'] != peeridA:
        return None
    pubB_der = response2['certB']
    pubB = EC.pub_key_from_der(pubB_der)
    sigB = response2['SB']
    if verify_response(randomB,randomA,peeridA,pubB,sigB):
        return pubB
    else:
        return None
示例#24
0
def check_response1(rdata1,randomB,peeridB):
    try:
        response1 = bdecode(rdata1)
    except:
        return [None,None]
    if response1['B'] != peeridB:
        return [None,None]
    pubA_der = response1['certA']
    pubA = EC.pub_key_from_der(pubA_der)
    sigA = response1['SA']
    randomA = response1['rA']
    if verify_response(randomA,randomB,peeridB,pubA,sigA):
        return [randomA,pubA]
    else:
        return [None,None]
示例#25
0
def check_response1(rdata1,randomB,peeridB):
    try:
        response1 = bdecode(rdata1)
    except:
        return [None,None]
    if response1['B'] != peeridB:
        return [None,None]
    pubA_der = response1['certA']
    pubA = EC.pub_key_from_der(pubA_der)
    sigA = response1['SA']
    randomA = response1['rA']
    if verify_response(randomA,randomB,peeridB,pubA,sigA):
        return [randomA,pubA]
    else:
        return [None,None]
示例#26
0
 def check_response2(self,resp2_data,rA,rB,myid):
     resp2 = bdecode(resp2_data)
     self.testcase.assert_(type(resp2) == DictType)
     self.testcase.assert_(resp2.has_key('certB'))
     self.testcase.assert_(resp2.has_key('A'))
     self.testcase.assert_(resp2.has_key('SB'))
     # show throw exception when key no good
     pubB = EC.pub_key_from_der(resp2['certB'])
     A = resp2['A']
     self.testcase.assert_(type(A) == StringType)
     self.testcase.assert_(A,myid)
     SB = resp2['SB']
     self.testcase.assert_(type(SB) == StringType)
     # verify signature
     sig_list = [rB,rA,myid]
     sig_data = bencode(sig_list)
     sig_hash = sha(sig_data).digest()
     self.testcase.assert_(pubB.verify_dsa_asn1(sig_hash,SB))
示例#27
0
 def check_response2(self, resp2_data, rA, rB, myid):
     resp2 = bdecode(resp2_data)
     self.testcase.assert_(type(resp2) == DictType)
     self.testcase.assert_(resp2.has_key('certB'))
     self.testcase.assert_(resp2.has_key('A'))
     self.testcase.assert_(resp2.has_key('SB'))
     # show throw exception when key no good
     pubB = EC.pub_key_from_der(resp2['certB'])
     A = resp2['A']
     self.testcase.assert_(type(A) == StringType)
     self.testcase.assert_(A, myid)
     SB = resp2['SB']
     self.testcase.assert_(type(SB) == StringType)
     # verify signature
     sig_list = [rB, rA, myid]
     sig_data = bencode(sig_list)
     sig_hash = sha(sig_data).digest()
     self.testcase.assert_(pubB.verify_dsa_asn1(sig_hash, SB))
示例#28
0
文件: dcs.py 项目: sr-gi/paysense
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}
示例#29
0
文件: encrypt.py 项目: temp321/fwlite
 def save_pub_key(pubkey, dest):
     pubk = EC.pub_key_from_der(buffer(pubkey))
     pubk.save_pub_key(dest)
示例#30
0
def verify_data(plaintext,permid,blob):
    pubkey = EC.pub_key_from_der(permid)
    digest = sha(plaintext).digest()
    return pubkey.verify_dsa_asn1(digest,blob)
示例#31
0
 def save_pub_key(pubkey, dest):
     pubk = EC.pub_key_from_der(buffer(pubkey))
     pubk.save_pub_key(dest)
示例#32
0
 def get_dh_key(self, otherKey):
     pk = EC.pub_key_from_der(buffer(otherKey))
     return self.ec.compute_dh_key(pk)
def active_auth(dg15: bytes, sm_object: SMObject, security_infos: List[bytes]):
    """
    Do active authentication with DG15
    """
    # Generate 8 random bytes
    rnd_ifd = urandom(8)

    # exception caught in main program loop
    data = send(
        sm_object,
        APDU(b"\x00",
             b"\x88",
             b"\x00",
             b"\x00",
             Lc=b"\x08",
             cdata=rnd_ifd,
             Le=b"\x00"))

    if data == b"":
        raise ActiveAuthenticationError("[-] No reply from card.")

    i = asn1_node_root(dg15)
    i = asn1_node_first_child(dg15, i)
    pub_key = asn1_get_all(dg15, i)

    i = asn1_node_first_child(dg15, i)
    i = asn1_node_first_child(dg15, i)

    if asn1_get_all(dg15, i) == encode_oid_string("1.2.840.10045.2.1"):  # ECC
        r = data[:len(data) // 2]
        s = data[len(data) // 2:]
        signature = asn1_sequence(asn1_integer(r) + asn1_integer(s))
        ec_pub = EC.pub_key_from_der(pub_key)
        if ec_pub.check_key() != 1:
            raise ActiveAuthenticationError(
                "[-] Active Authentication (AA) failed! Problem in EC Public Key!"
            )

        try:
            hash_type = find_hash_name(security_infos)
        except ValueError as ex:
            raise ActiveAuthenticationError(
                "[-] Active Authentication (AA) failed! Problem in Security Infos hash type!"
            ) from ex
        # for hash_type in ["sha224", "sha256", "sha384", "sha512"]:
        try:
            result = ec_pub.verify_dsa_asn1(
                hashlib.new(hash_type, rnd_ifd).digest(), signature)
        except EC.ECError as ex:
            print("[-] Error in EC function " + ex)
            raise ActiveAuthenticationError(
                "[-] Error in verify_dsa_asn1 of M2Crypto.EC") from ex
        if result == 1:
            print("[+] Active Authentication (AA) completed successfully!")
        else:
            raise ActiveAuthenticationError(
                "[-] Active Authentication (AA) failed!")

    elif asn1_get_all(dg15,
                      i) == encode_oid_string("1.2.840.113549.1.1.1"):  # RSA
        j = asn1_node_root(pub_key)
        j = asn1_node_first_child(pub_key, j)
        j = asn1_node_next(pub_key, j)

        rsa_pub_key = asn1_get_value_of_type(pub_key, j, "BIT STRING")
        if rsa_pub_key[0] != 0x00:
            raise ActiveAuthenticationError(
                "[-] An issue with the RSA key! Padding 0x00 is expected")

        rsa_pub_key = rsa_pub_key[1:]
        j = asn1_node_root(rsa_pub_key)
        j = asn1_node_first_child(rsa_pub_key, j)
        n_der = asn1_get_value_of_type(rsa_pub_key, j, "INTEGER")
        j = asn1_node_next(rsa_pub_key, j)
        e_der = asn1_get_value_of_type(rsa_pub_key, j, "INTEGER")
        n = int.from_bytes(n_der, byteorder="big")
        e = int.from_bytes(e_der, byteorder="big")

        # rsa_key = RSA.import_key(pub_key)
        # https://stackoverflow.com/a/60132608/6077951

        msg = int.from_bytes(data, byteorder="big")
        dec = pow(msg, e, n).to_bytes(len(data), byteorder="big")

        if dec[-1] == 0xCC:
            if dec[-2] == 0x38:
                hash_alg = "sha224"
            elif dec[-2] == 0x34:
                hash_alg = "sha256"
            elif dec[-2] == 0x36:
                hash_alg = "sha384"
            elif dec[-2] == 0x35:
                hash_alg = "sha512"
            t = 2
        elif dec[-1] == 0xBC:
            hash_alg = "sha1"
            t = 1
        else:
            raise ActiveAuthenticationError(
                "[-] Error while Active Authentication!")

        def compare_aa(hash_object):
            # k = rsa_key.size_in_bits()
            # Lh = hash_object.digest_size * 8
            # Lm1 = (k - Lh - (8 * t) - 4 - 4) // 8
            D = dec[-hash_object.digest_size - t:-t]
            M1 = dec[1:-hash_object.digest_size - t]
            Mstar = M1 + rnd_ifd
            hash_object.update(Mstar)
            Dstar = hash_object.digest()
            return hmac.compare_digest(D, Dstar)

        hash_object = hashlib.new(hash_alg)
        if compare_aa(hash_object):
            print("[+] Active Authentication (AA) completed successfully!")
        else:
            raise ActiveAuthenticationError(
                "[-] Active Authentication (AA) failed!")
示例#34
0
def pub_key_from_der(der):
    return EC.pub_key_from_der(PUB_KEY_DER_PREFIX + der)
示例#35
0
def verify_data(plaintext, permid, blob):
    pubkey = EC.pub_key_from_der(permid)
    digest = sha(plaintext).digest()
    return pubkey.verify_dsa_asn1(digest, blob)
示例#36
0
from M2Crypto import EC, EVP, BIO
import binascii, sys, cryptimage
from pydmtx import DataMatrix
from PIL import Image
debug=0

#read in the data from the image
dm_read = DataMatrix(scheme=DataMatrix.DmtxSchemeBase256)
img = Image.open("dm.png")
data = dm_read.decode(img.size[0],img.size[1],img.tostring())

#extract public key and encrypted message
ephpub, ciphertext = cryptimage.parse_input(data)
ephemeral = EC.pub_key_from_der(cryptimage.build_asn1(ephpub))

if debug: sys.stderr.write("ct = %s\n" % binascii.b2a_hex(ciphertext))

ecpairpem = """-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIH8TNBOfV+JWVBr25KfjJ1007paZ/JnrvjxFzZThUgSToAoGCCqGSM49
AwEHoUQDQgAEtv1eCFuapm3ku1AdTt5eK1IVaAzH2MBQqreo3FBSE8EHxCsEGRvK
auFV+AgDEQotZbdqzAojRoCjuhZcYP73Pg==
-----END EC PRIVATE KEY-----
"""

#derive shared key
ecbio = BIO.MemoryBuffer()
ecbio.write(ecpairpem)
ecpair = EC.load_key_bio(ecbio)
ecder = ecpair.pub().get_der()
ecpub = cryptimage.compress_key(cryptimage.strip_asn1(ecder))
示例#37
0
from M2Crypto import EC, EVP
import binascii, sys, cryptimage
from pydmtx import DataMatrix
debug=0

ecpubkey = binascii.a2b_hex('02b6fd5e085b9aa66de4bb501d4ede5e2b5215680cc7d8c050aab7a8dc505213c1')
ecder = cryptimage.build_asn1(ecpubkey)
ecpub = EC.pub_key_from_der(ecder)

digest = EVP.MessageDigest("sha1")
digest.update(cryptimage.compress_key(ecpubkey))
fingerprint = digest.digest()

# NID_X9_62_prime256v1
ephemeral = EC.gen_params(EC.NID_X9_62_prime256v1)
ephemeral.gen_key()
ephpub=cryptimage.strip_asn1(ephemeral.pub().get_der())
ephpub=cryptimage.compress_key(ephpub)

shared = ephemeral.compute_dh_key(ecpub.pub())

#strip second half of key which is y cordinates and can be derived from first half
dk=cryptimage.KDF(shared[:len(shared)/2],128,fingerprint)

if debug: sys.stderr.write("dk = %s\n" % binascii.b2a_hex(dk))

account="2000111122223333"
amount="1500050"
pin="7654"

data=cryptimage.dataencode(account,amount,pin)
示例#38
0
文件: encrypt.py 项目: temp321/fwlite
 def get_dh_key(self, otherKey):
     pk = EC.pub_key_from_der(buffer(otherKey))
     return self.ec.compute_dh_key(pk)
示例#39
0
def pub_key_from_der(der):
    return EC.pub_key_from_der(PUB_KEY_DER_PREFIX + der)
示例#40
0
#!/usr/bin/env python
# coding=utf-8

from M2Crypto import EC
from hashlib import sha256

prefix = "3059301306072a8648ce3d020106082a8648ce3d030107034200".decode('hex')
tail_key = '04EC4FDC9FBDECFE8F21B178693703733C0E3A96BE41590CCF98DCFB2DA8A19BA8A3854E8B5E57D1E01AEDCA8F28B0B643BC890174A08018C34F91D0A79D064548'.decode('hex')

ec = EC.pub_key_from_der(prefix + tail_key)

msg = '002122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F400102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F200000000004EC4FDC9FBDECFE8F21B178693703733C0E3A96BE41590CCF98DCFB2DA8A19BA8A3854E8B5E57D1E01AEDCA8F28B0B643BC890174A08018C34F91D0A79D064548'.decode('hex')
sig = '304402206613ECA917F891ABADEAB63054CE7DFE3F32268FCE7D0AF4B37C6000C9D13B2B022067E717B413597268EF28EC72EE79135EB87026DB14E64776C15CD7335D95402A'.decode('hex')

h = sha256()
h.update(msg)
result = ec.verify_dsa_asn1(h.digest(), sig)
print result