Translate Java to Python - sign strings with PEM certificate files
I am trying to translate the following Java into my Python equivalent.
// certificate is contents of https://fps.sandbox.amazonaws.com/certs/090909/PKICert.pem
// signature is a string that I need to verify.
CertificateFactory factory = CertificateFactory.getInstance("X.509");
X509Certificate x509Certificate =
(X509Certificate) factory.generateCertificate(new ByteArrayInputStream(certificate.getBytes()));
Signature signatureInstance = Signature.getInstance(signatureAlgorithm);
signatureInstance.initVerify(x509Certificate.getPublicKey());
signatureInstance.update(stringToSign.getBytes(UTF_8_Encoding));
return signatureInstance.verify(Base64.decodeBase64(signature.getBytes()));
This is for verifying the PKI signature used by AWS FPS. http://docs.amazonwebservices.com/AmazonFPS/latest/FPSAccountManagementGuide/VerifyingSignature.html
Thanks for your help!
a source to share
I researched this with pyCrypto and keyczar, but the problem is not being able to parse X509 certificates (keyczar has keyczar.util.ParseX509 (), but it's limited and doesn't work for AWS-cert or I'm guessing which one or a real certificate).
I believe M2Crypto works. See the following code snippet, which requires a real signature and plaintext to really test.
from M2Crypto import X509
cert = X509.load_cert("PKICert.pem")
pub_key = cert.get_pubkey()
plaintext = "YYY" # Put plaintext message here
signature = "XXX" # Put signature of plaintext here
pub_key.verify_init()
pub_key.verify_update(plaintext)
if not pub_key.verify_final(signature):
print "Signature failed"
a source to share
After all was said and done, I decided not to use my own library to verify the signature (because M2Crypto is not easily portable to 64-bit Windows). I found that later versions of the Amazon FPS APIs include a REST / SOAP call to verify the signature, so if the round trip to their server isn't too expensive, you can just call VerifySignature . I added support for this in the next version of boto as boto.fps.connection.verify_signature.
a source to share