我想用私钥(不是普通签名)进行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程序的结果:
我的Python脚本的结果:
您不使用私钥来加密数据。
如果你真正想要的是签署你的哈希,而不是使用encrypt
函数,你应该使用sign
函数。
所以,而不是
from Crypto.Cipher import PKCS1_v1_5
PKCS1_v1_5.new(privateKey).encrypt(hash)
你可能想试试
from Crypto.Signature import pkcs1_15
pkcs1_15.new(privateKey).sign(hash)
如果你想看一下,我写了一些关于使用pycryptodome进行签名/验证的blog post。