发布时间:2019-09-10 08:48:45编辑:auto阅读(2473)
今天对接业务接口,传递的参数需要用RSA签名,三方只给了java的RSA签名Demo;但我们这边后端采用python开发,因此需要用Python来实现RSA签名。
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
public class Sign {
public static String sign(String content, String privateKey) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64
.decode(privateKey));
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey priKey = keyf.generatePrivate(priPKCS8);
java.security.Signature signature = java.security.Signature
.getInstance("SHA1WithRSA");//签名算法SHA1WithRSA
signature.initSign(priKey);
signature.update(content.getBytes("UTF-8"));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Python相关RSA加密库: rsa, Crypto, M2Crypto;下面分别调研了使用rsa和Crypto实现RSA签名(代码中,pem就是RSA签名需要的私钥)。
import base64
import rsa
def sign(self, data):
pri_key = rsa.PrivateKey.load_pkcs1(self.pem)
signature = rsa.sign(str(data), priv_key=pri_key, hash='SHA-1')
return base64.b64encode(signature)
import base64
from Crypto.Signature import PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA
def sign(self, data):
private_key = RSA.importKey(self.pem)
cipher = PKCS1_v1_5.new(private_key)
h = SHA.new(data)
signature = cipher.sign(h)
return base64.b64encode(signature)
openssl genrsa -out rsa_private_key.pem 1024
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt
import rsa
(pubkey, privkey) = rsa.newkeys(1024)
privkey.save_pkcs1('PEM')
pubkey.save_pkcs1('PEM')
上一篇: python将回车作为输入内容
下一篇: Python打包与发布的概念总结
47849
46410
37292
34741
29322
25979
24924
19959
19550
18037
5800°
6422°
5937°
5966°
7074°
5921°
5952°
6447°
6409°
7788°