python 处理java生成的证书流程

python 处理java生成的证书流程,以及公钥私钥加密,加签验签,aes加解密(这里用的是M2Crypto库里面的RSA X509 EVP)

java生成的jks证书python不能直接使用需要转换成pem格式可用以下命令(需要先安装keytool(网上很多例子))
 keytool -importkeystore -srckeystore xxxx.jks -destkeystore xxxx.p12 -srcstoretype jks -deststoretype pkcs12
 上一命令只是生成p12文件再由p12文件生成pem文件(关于p12格式自己可以网上查一下证书格式)
 openssl pkcs12 -in xxxx.p12 -out xxxx.pem(生成加密的pem文件)
 
 openssl pkcs12 -nodes -in xxxx.p12 -out xxxx.pem(生成非加密的pem文件)
 
 至此证书格式转换完成
 
 先说公钥加解密(这里用的是RSA源码地址https://gitlab.com/m2crypto/m2crypto/blob/master/M2Crypto/RSA.py)
 
 获取密钥对我用的是RSA.load_key(file, callback=util.passphrase_callback)
 file既是pem证书文件的地址,callback为回调函数,即自己写一个pem证书密码返回的函数
 例如def pass():
        return '111111'
公钥加密RSA.public_encrypt(self, data, padding)data是待加密的数据 pading(个人理解是一种补全格式)    
公钥解密RSA.public_decrypt(self, data, padding)data是待解密的数据 pading(个人理解是一种补全格式)
私钥加密RSA.private_encrypt(self, data, padding)data是待加密的数据 pading(个人理解是一种补全格式)    
私钥解密RSA.private_decrypt(self, data, padding)data是待解密的数据 pading(个人理解是一种补全格式)
补充如果单独从类似'''xxxx'''这样的字符串中获取公钥加密
可用kkk = X509.load_cert_der_string(data)如果data是经过base64加密的需要先进行解密,在调用 kkk.get_pubkey()获取公钥对象
即可进行加密
aes加解密直接上码
加密:
def AES_build_cipher(key, iv, op):
    return EVP.Cipher(alg='aes_128_cbc', key=key, iv=iv, op=op)
 
    def AES_encrypt(key, msg, iv): # key, iv -> bytes, msg -> text
       if iv is None:
          raise ValueError("IV must be defined!")
 
       def encrypt(data):
           cipher = AES_build_cipher(key, iv, data)
           v = cipher.update(data)
           v = v + cipher.final()
           del cipher
           v = base64.b64encode(v)
           return v

解密:
def AES_decrypt(key,msg, iv=None):
    # Return the decryption function
     print iv
     def decrypt(data):
         data = base64.b64decode(data)
         cipher = AES_build_cipher(key, iv, 1)
         v = cipher.update(data)
         v = v + cipher.final()
         del cipher
         return v
     return decrypt(msg)
    
加签 验签这里用的是EVP模块(源码地址https://gitlab.com/m2crypto/m2crypto/blob/master/M2Crypto/EVP.py)

加签(私钥)
key = EVP.load_key(file,callback = passwd)
key.reset_context(md='sha1')
key.sign_init()
key.sign_update(data)
sign = base64.b64encode(key.sign_final())
return sign

解签
#datas是加签数据
#rsa_key是公钥对象
VerifyEVP = EVP.PKey()
VerifyEVP.assign_rsa(rsa_key)
VerifyEVP.verify_init()
VerifyEVP.verify_update(dat) #验证内容
verift = VerifyEVP.verify_final(datas)
#json.dumps(dats,sort_keys = True, separators=(',',':')).decode('unicode-escape').encode('utf8') 此方法是对数据进行格式处理(去空格 排顺序)

以上 只是本人个人见解,如有错误希望大家指出

posted @ 2016-08-04 13:31  菜鸟笔记go  阅读(3552)  评论(0编辑  收藏  举报