我有pkcs8_rsa_private_key文件,它由openssl从rsa_private_key.pem文件生成.
我需要通过python中的私钥进行签名,使用下面的java代码创建相同的签名.
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)来执行和验证数据上的数字签名.
你拥有的这段代码有三件事:
>它将Base64解码为PKCS#8
>它将PKCS#8解码为内存中的实际密钥(请注意,您可能需要在此处提供密码)
>它使用SHA-1使用所述密钥执行PKCS#1 v1.5签名
>它对Base64中的签名进行编码
标签:java,python,encryption,openssl,rsa
来源: https://codeday.me/bug/20191005/1856644.html