Reputation: 2352
I'am trying to find RSASSA-PSS-2048-SHA256 digital signature algorithm in python2.7.
Currently my code like this:
def calc_rsassa_pss_2048_sha256(self, data):
private_key = RSA.importKey(self.private_key)
cipher = PKCS1_v1_5.new(private_key)
h = SHA.new(data)
signature = cipher.sign(h)
return base64.b64encode(signature)
But got the signature not match error when we try to verify the generated signature.
In Java the code like this:
public static PrivateKey decodePrivateKey(String privateKeyStr) throws NoSuchAlgorithmException, InvalidKeySpecException {
String privateKeyRaw = trimPrivateKey(privateKeyStr);
byte[] buffer = decodeBase64(privateKeyRaw);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
}
public static String sha256withRSAPSS(String privateKeyStr, String content) throws InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
PrivateKey privateKey = decodePrivateKey(privateKeyStr);
Signature signature = Signature.getInstance("SHA256withRSA/PSS", new BouncyCastleProvider());
signature.initSign(privateKey);
signature.update(content.getBytes(CHARSET));
return encodeBase64(signature.sign());
}
I don't know what's wrong with the python signature code above. Or how to use RSASSA-PSS-2048-SHA256
algorithm in python2.7 ?
Many thanks.
Upvotes: 4
Views: 2550
Reputation: 1342
On the Python piece you are using PKCS#1 v1.5 padding for signing. On the Java piece you are using PSS. As you are using different schemes it's only natural that these two won't produce the same output. Generally it is more recommended to use PSS scheme over v1.5.
I'm no Python expert, but after quick look in internet, maybe Hazmat crypto library could help you with that on Python (https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/):
>>> from cryptography.hazmat.primitives import hashes
>>> from cryptography.hazmat.primitives.asymmetric import padding
>>> message = b"A message I want to sign"
>>> signature = private_key.sign(
... message,
... padding.PSS(
... mgf=padding.MGF1(hashes.SHA256()),
... salt_length=padding.PSS.MAX_LENGTH
... ),
... hashes.SHA256()
... )
Edit: If Hazmat won't suit you, take a look at the approved answer here: PKCS1_PSS sign() method
Upvotes: 2