ecc生成key (python版本)

from OpenSSL import crypto
import struct
import os
import binascii




class Ecdh(object):
    
    def __init__(self):
        self.ssl_lib = crypto._lib
        self.ssl_ffi = crypto._ffi
        
            
    
    def gen_ecdh_key_ex(self,new_pubkey,old_pubkey,old_privitekey):
        
        ecdh2 = self.ssl_lib.EC_KEY_new_by_curve_name(711)
        if not ecdh2:
            print("ERROR:EC_KEY_new_by_curve_name failed.")
            return
        
        #释放使用 self.ssl_lib.BN_free(ctx)
        bn_private_key = self.ssl_lib.BN_bin2bn(old_privitekey,len(old_privitekey),self.ssl_ffi.NULL)
        if self.ssl_lib.EC_KEY_set_private_key(ecdh2,bn_private_key) != 1:
            print("EC_KEY_set_private_key failed")
            self.ssl_lib.BN_free(bn_private_key)
            return 
        self.ssl_lib.BN_free(bn_private_key)
        
        #
        group = self.ssl_lib.EC_KEY_get0_group(ecdh2)
        if not group:
            print("EC_KEY_get0_group failed")
            return
        #释放使用 self.ssl_lib.EC_POINT_free(pub_key)
        new_point = self.ssl_lib.EC_POINT_new(group)
        if not new_point:
            print("EC_POINT_new failed")
            return
            
           
        
        if len(old_pubkey) != 0:
            self.ssl_lib.EC_POINT_oct2point(group,new_point,old_pubkey,len(old_pubkey),self.ssl_ffi.NULL)
        else:
            self.ssl_lib.EC_POINT_mul(group,new_point,0,0,0,0)
        self.ssl_lib.EC_KEY_set_public_key(ecdh2,new_point)
        
        #释放
        self.ssl_lib.EC_POINT_free(new_point)
        
          
        #释放使用 self.ssl_lib.EC_POINT_free()
        new_point_2 = self.ssl_lib.EC_POINT_new(group)
        self.ssl_lib.EC_POINT_oct2point(group,new_point_2,new_pubkey,len(new_pubkey),self.ssl_ffi.NULL)
        
        #
        
        #
        new_share_key = bytes(512)
        compute_key = self.ssl_lib.ECDH_compute_key(new_share_key,512,new_point_2,ecdh2,self.ssl_ffi.NULL)
        #新的密钥
        new_share_key = new_share_key[:compute_key]
        
        
        #释放使用的内存
        self.ssl_lib.EC_POINT_free(new_point_2)
        self.ssl_lib.EC_KEY_free(ecdh2)

你可能感兴趣的:(ecc生成key (python版本))