我想用私钥(不是普通签名)进行 RSA 加密,但 PyCryptodome 似乎无法做到。
我需要使用私钥执行此操作的原因是,我需要获得与不是我编写的 Java 程序相同的结果,该程序错误地使用 javax.crypto.Cipher 和私钥来签署消息......
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import javax.crypto.Cipher;
...
String deviceKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASC...";
PKCS8EncodedKeySpec localPKCS8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decode(deviceKey).getBytes("UTF-8"));
PrivateKey localPrivateKey = KeyFactory.getInstance("RSA").generatePrivate(localPKCS8EncodedKeySpec);
byte[] hash = MessageDigest.getInstance("SHA-256").digest("test".getBytes());
Cipher localCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
localCipher.init(Cipher.ENCRYPT_MODE, localPrivateKey);
String sign = new String(Base64.encode(localCipher.doFinal(hash)));
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from Crypto.Hash import SHA256
...
deviceKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASC...'
privateKey = RSA.importKey(deviceKey)
hash = SHA256.new('test'.encode()).digest()
signer = PKCS1_v1_5.new(privateKey)
sign = b64encode(signer.encrypt(hash))
Java程序的结果:
哈希:9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
符号:k8y6zMfl0KVuQWWOmRxieXF1aH0dpVUX......(总是一样)
我的 Python 脚本的结果:
哈希:9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
符号:GfLVqZDnu5aLHHbi0tM5OtCBEVKKRcjW......(每次都改变)