问题描述
我有pkcs8_rsa_private_key文件,通过openssl从rsa_private_key.pem文件生成。
I have pkcs8_rsa_private_key file which generate by openssl from a rsa_private_key.pem file.
我需要通过python中的私钥进行签名,使相同的签名与以下java代码。
I need make a signature by the private key in python, make the same signature with below java code.
public static final String SIGN_ALGORITHMS = "SHA1WithRSA";
public static String sign(String content, String privateKey) {
String charset = "utf-8";
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(SIGN_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(charset));
byte[] signed = signature.sign();
return Base64.encode(signed);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
推荐答案
PKCS#8定义了一种方式编码和传输密钥,它不是OpenSSL特有的; PKCS#1定义了一种使用RSA密钥的方法(无论如何加载到您的应用程序中,使用PKCS#8)来执行和验证数据上的数字签名。
PKCS#8 defines a way to encode and transport secret keys and it is not specific to OpenSSL; PKCS#1 defines a way to use an RSA key (no matter how it was loaded into your application, with PKCS#8 or not) to carry out and verify digital signature on data.
这段代码有三件事:
- 它将Base64解码成PKCS#8
- 它将PKCS#8解码成内存中的实际密钥(您可能需要在此处提供密码)
- 它使用SHA-1执行PKCS#1 v1.5签名使用所述密钥
- 它在Base64中编码签名
- It decodes Base64 into PKCS#8
- It decodes PKCS#8 into the actual key in memory (mind you may need to provide a passphrase here)
- It performs PKCS#1 v1.5 signature using SHA-1 using said key
- It encodes the signature in Base64
PKCS#1 v1.5的例子,用于签名PyCrypto的API 确实步骤#2和#3。
The example for PKCS#1 v1.5 signing in the API of PyCrypto does exactly steps #2 and #3.
这篇关于如何在python中创建PKCS8 RSA签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!