Decrypt using BCPGP private key in python - python

How do I read BouncingCastle PGP key and decrypt message using Python.?
This private key is generated using GoAnywhere OpenPGP Studio, password is Test#123
Below is the key blob and the error I'm getting. I'm getting same error when I read from file(.asc) as well
test_key_pvt = """-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: BCPG v1.48
lQO0BGJpFmIBCACDfQVAmS1pIH0Noiy3vBDPHvrTmIZseGzRwzJ1hs7jx4Mh3r3f
WFrYKyfeF9niJQCBBfQjukx+f9BxbhZNyZb3PMH36gzI3yLNCVQcv8IMSsa1nvmV
wBtwzVu65RZ9M6Uc20mUHuHtB5tr8h4VRwTfZoUolp8KnvQqLz1QsDiCulHV70QO
gXs6JA3YtXUQAkf3+6HqTxF7PdfX9M7loKwJyglw0R+TQ6QWJzMh7HGhW08y77aV
fbGGJWkpT50ubM8sFOyIijp/IKNW+n9PO5XpcJq26Yo2Q37wVsoOQtw01UdK2Ld5
VRhb/tQINLj4CzPVTbzSr0bczlyUP1n9pp4dABEBAAH/CQMCEZNEmlxewwJg5RN0
osxAk8hgjgar7Qlxgb3WVsz1lY0+DDEX1m//D70YVYoU3zdfNVn5/VPbxElTEm5l
Zo+ZQu6ZRGYo1f3IaovWQzJDEgSIEZupcRB/YF5cWwYRQZdsfEzobcbMhsggqv7H
QJyOY7AW7WzLr03QVFpk9k+hYWaSAYM5oO+k0WKAS6U5n7E5TS7SJ99W/o4oWHm/
QIgj/0tA7AKicEZcQtLR7BqsjZhwr75jKXhnEsi0EhsaWtOrqpUYdmv8H9b2Z/pa
1b2H/2/ESk3Q0nPb8oOCxijMInbCRTb+/9+fI1r09X2Gbo6ojblXpv+ECS+f04L/
I+2mpluCkwutvfDRtpxFOKm23yJWR8GwZYjF4jFBxNvW+hRdgS9NqeRcZELM3tet
RHGYTyTTyAZmS+ZqSIy8BY7O4VjgieR64SEynIleTG05tvgwQ/GnkUYDSf5xVwbY
TvU57+Lr6QngkZuANDmwp67iR1OU0rDNYuhCz9R04VY/veqLyhtrcyfXS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RIVATE KEY BLOCK-----
"""
pvt_key, _ = pgpy.PGPKey.from_blob(test_key_pvt)
Error: pgpy.errors.PGPError: 6 is not a valid SymmetricKeyAlgorithm
Another error for different key: pgpy.errors.PGPError: 112 is not a valid CompressionAlgorithm
Not able to arrive at any solution, I'm trying to automate a very small transfer and its really annoying that I'm not able to find anything for this in python. PGPY library doesn't have a lot of documentation.
TIA

Related

Decrypting and encrypting java JWEObject with algorithm RSA-OAEP-256 on python

I have a kafka message that was encrypted on java with the following code:
private String decryptedMessage(String key, String encryptedMessage) throws NoSuchAlgorithmException, InvalidKeySpecException, ParseException, JOSEException {
PrivateKey privateKey = <some way to generate a private key from key>;
JWEDecrypter decrypter = new RSADecrypter(privateKey);
JWEObject decryptedJweObj = JWEObject.parse(encryptedMessage);
decryptedJweObj.decrypt(decrypter);
return decryptedJweObj.getPayload().toJSONObject().toJSONString();
}
Now I'm trying to decode it using python on a decoded message where I already know the private key.
I tried using jwcrypto (since I'm using python3 and jeso is only for 2.x) using this code like in their documents, but it didn't work:
enc = '<encrypted message>'
private = '<private key>'
jwetoken = jwe.JWE()
jwetoken.deserialize(enc, key=private_key)
payload = jwetoken.payload
And I get this error code: jwcrypto.jwe.InvalidJWEData: No recipient matched the provided key["Failed: [ValueError('key is not a JWK object',)]"] I tried looking for a way to make the private key a JWK object but couldn't find one.
I know my message is JWE since it's split by 4 dots and when I base64 decode the first part I get this json: b'{"alg":"RSA-OAEP-256","enc":"A256GCM","kid":"<some key id>"}'
So I'm kind of stuck on how to decode my message.
Decrypted string: {"value":"Object Encryption"}
Encrypted string:
eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIiwia2lkIjoiYjFhOWVmNzAtYjQ4Yy00YzdiLWI0ZTQtODU2YzQyNGIyYzZlIn0.XzLgQTzESD7mg-DtiwFaOQQIfJjQOox5Efbq3Cn8n4H0OZUNvNFWuLr2gPH4WqhWZFYvYh6Mx3--bKiYA_kGplPaJUdPfuYx3OgOug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sNHLl+QKBgQDTORonO1FrIAo2VnsQS0Lq6EdxRzzP9q9mHttJNJK5eEXP7sNSdTDrudk4tpr3zvXtK4b+4SiCDriA5VTJHhdGF3wwqhR76XT3gLoXZLGYlx+4RvMbuIFDGkUee+39T2//MztEZgt3TM3LcBFEjTRV8gzpFJsj8wea3E4B8lOEZQKBgQDEFkfdgIBNu/3wH+z2uq40kYlkMRb4wQq8CjmwXYxGu1WR3SYn2zNQTsZR6BtiHFzx/37W279dO87u9rAbNuY5V9VYQKjxZD2lidYQ/0w07kO1PhNuISLpqn2AbiLczlLluX8dHpLpb5UG+JWlqih5VBCDFktmVUlMVteHPa21VwKBgCkpEHqiqYwJk1PhaFvVfrXOC9X8PtJ7zNRGoQ7T6t+vm1MYwQE5iw30imrt0qcFspDEEatrbvxhJ/0eM3Z5oalr/CxziEhZRwzQDfNvENieYnUDhm5Zdv7/iIaXOdpJ95YwgpUimYtm8Rd6wDKunYs9/twQwuavfkTkN2NTuIitAoGBAJu0NYylpTwUsyghscCZrAsCJd7xPBR69VMrq3NoVSM1TlVtDgdIAA8c/k27yUK20vc2sjladTJLc549NMnnZhjSrg5OCdjkiC8SrHECyDifmhQpHrSsi1SQlOeOjRBYpWrVSSKOTIogmG3YprvNyiXNou70nRq9Tl7X9nzldTIxAoGBAJ3qo/epO7xAs6Vhp+8na0Tv93Ji2kCvA14iOE+P08saldspB4NEVitGahuvrTx8CKDyL1PDH5X1MTabvI/LYw6k/gnzOhSX3MTP3qMepNEq1A5chvMJHhMS72/tAPKIXux+AgDkSvq8+G02DFWDpF9bcBoINL/89wOUcEfOQty0
The posted encrypted token can be decrypted with the posted RSA key and the Python library JWCrypto. Maybe it doesn't work for you because of a key import bug.
The posted RSA key is a DER encoded PKCS#8 key (Base64 encoded). JWCrypto does not support this encoding directly, but only the PEM encoding, which is not too bad, because the conversion from DER to PEM is trivial: The Base64 string must be formatted (line break after every 64 characters) and the header (-----BEGIN PRIVATE KEY-----) and footer (-----END PRIVATE KEY-----) must be added each in a separate line.
Alternatively, the key can be converted to a JWK and imported in this format.
The following Python code shows these two variants based on the posted data. For this the JWK was derived with online tools from the posted PKCS#8 key:
pkcs8pem = b'''-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQChyho54VxOGYDx
rN2pjM8/pA94kcqlMNZ0NSIoSHhasAm72X66XN9GI2IapQETy7+gNBKBWszWn4Js
NuAbLLNp5zeTlmzHp09ee4L+g8s/NIKMwA5Mgx9wGu2Hi0foh0pErAMKQV6CLBJU
fB5JUu9PX2MED7Z2XGG0RYClSMEO8L7iHXm1ooCr83rU/U5xXwpuTrp4L9nYD9eB
6EptCgOWEi98lq5oeQXNyWfti3/gckathUi8WINlI+5/fPv7ZWd9Z60VXAVfb5u8
61/erIhEIJRkqbDXc/ULAQsAeEKVYzHpStM9In30mQdp6EdY48imZiHj1GNgPvY+
MD3wPmdTAgMBAAECggEAE3IcJtrMYmK0WdfiKI/RFSAd7+ruBV7SV9NPELJtLNE9
ykNA9RtWhrKYBwXQFFYH6TR5CO0l86HmZiVOWFXOFquAxY9t8a1NX9jOjNLAag9g
pZQr48xayfmilQkLkoo4Rfq6vs/OkSzE4zyr0zpRoyOe3g0ZbC58W9OCu9r7wVTD
V+KKE8ChU39Ae8HLfMEQXWSIUqxbrpw+mLeFX1qh5ILNBDA9M6vD+JuoiuIZltW4
djnlU4hxYPVwTyuPBCQ3AwJsRGcddfxWTI+kIm2/6k8HzhdpB1ajBrZX/XVeXAp7
VlvyHzBZ5ri1NDpr/Cyh6o2ysdB8qGCnlDcsNHLl+QKBgQDTORonO1FrIAo2VnsQ
S0Lq6EdxRzzP9q9mHttJNJK5eEXP7sNSdTDrudk4tpr3zvXtK4b+4SiCDriA5VTJ
HhdGF3wwqhR76XT3gLoXZLGYlx+4RvMbuIFDGkUee+39T2//MztEZgt3TM3LcBFE
jTRV8gzpFJsj8wea3E4B8lOEZQKBgQDEFkfdgIBNu/3wH+z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vC-4h15taKAq_N61P1OcV8Kbk66eC_Z2A_XgehKbQoDlhIvfJauaHkFzcln7Yt_4HJGrYVIvFiDZSPuf3z7-2VnfWetFVwFX2-bvOtf3qyIRCCUZKmw13P1CwELAHhClWMx6UrTPSJ99JkHaehHWOPIpmYh49RjYD72PjA98D5nUw"}
enc = 'eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIiwia2lkIjoiYjFhOWVmNzAtYjQ4Yy00YzdiLWI0ZTQtODU2YzQyNGIyYzZlIn0.XzLgQTzESD7mg-DtiwFaOQQIfJjQOox5Efbq3Cn8n4H0OZUNvNFWuLr2gPH4WqhWZFYvYh6Mx3--bKiYA_kGplPaJUdPfuYx3OgOug9fuYMrZesE-9stJFd4TnQOJcrTfehJkI_QKPqfWgbEgh1Zn8r7DuIBbABmNK4OHa0edwUA0Lu4mUxzRW6UPaNdWtfEGL9ZVR4lzUx6QX6nweKdbi8tkDnQrSNcQ4eZKIn8mVl5rL3s-qa2VC1Zvo4R-eA4jTKs6WQrkPChJkfoECcYcLx7SIHdxP6VB9DAhW-TwRizr5OZUVLLLH3UEOF77Rtc6MLL4Al5mo29sE-E1faywQ.R1QE-zY29Ed7yfqX.-soXsfltkJL0AXk_q5tPn9hagCBG_1c03VKdh2A.-oteTYv0SHzE4yBmZlterg'
from jwcrypto import jwk, jwe
# Import of a PEM encoded PKCS#8 key
private_key = jwk.JWK.from_pem(pkcs8pem)
jwetoken = jwe.JWE()
jwetoken.deserialize(enc, key=private_key)
payload = jwetoken.payload
print(payload.decode('utf-8'))
# Import of a JWK
private_key = jwk.JWK(**jwkey)
jwetoken = jwe.JWE()
jwetoken.deserialize(enc, key=private_key)
payload = jwetoken.payload
print(payload.decode('utf-8'))
with the output:
{"value":"Object Encryption"}
{"value":"Object Encryption"}

ValueError("Expected: ASCII-armored PGP data") when using pgp_key.from_blob(key_string)

I am getting ValueError("Expected: ASCII-armored PGP data") when using pgp_key.from_blob(key_string) when trying to parse the key.
pgp_key = pgpy.PGPKey()
key = pgp_key.from_blob(key_string);
I tried using parse method as well but getting the same error.
I fixed this error by:
With your key as a file, run base64 /path/to/file_name new_encoded_file_name
Put your encoded key in your desired place (AWS Secrets Manager in my case)
Within your program, add the following line BEFORE getting your pgp key:
key_string = base64.decode(key_string)
Now key = pgp_key.from_blob(key_string) will no longer throw an error as the decoded string will be an ASCII-armored bytearray.

How to encrypt data with RSA private key (not normal signing) in Python?

I want to make RSA encryption with private key (not normal signing), but PyCryptodome seems not be able to do it.
The reason I need to do it with private key is, I need to get the same results as from a Java program not written by me, which wrongly uses javax.crypto.Cipher and private key to sign messages...
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))
Result of the Java program:
Hash: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
Sign: k8y6zMfl0KVuQWWOmRxieXF1aH0dpVUX......(always the same)
Result of my Python script:
Hash: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
Sign: GfLVqZDnu5aLHHbi0tM5OtCBEVKKRcjW......(it changes every time)
You don't use private keys to encrypt data.
A private key can sign data, which can be verified by the matching public key.
A public key can encrypt data, which can be decrypted by the matching private key.
If what you really want is to sign your hash, instead of using the encrypt function, you should use the sign function.
So, instead of
from Crypto.Cipher import PKCS1_v1_5
PKCS1_v1_5.new(privateKey).encrypt(hash)
you might want to try
from Crypto.Signature import pkcs1_15
pkcs1_15.new(privateKey).sign(hash)
I wrote a little blog post about signing/verifying using pycryptodome, if you want to take a look.

Python Openssl generate rsa key pair and write to a file

I want to generate a private , public key pair and put them into private.key and public.key files respectively.
I have the following code.
from OpenSSL import crypto, SSL
def gen_rsa_key_pair():
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 1024)
open("Priv.key", "wt").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))
crypto.dump_publickey() is not available.
How do I dump public key to a file?
The OpenSSL functions to print the public RSA key do not seem to be exported by the Python OpenSSL wrapper. By accessing the internals of the crypto module, you could still do it yourself (assuming that you have this package installed locally), as this code snippet shows:
>>> bio = crypto._new_mem_buf()
>>> rsa = crypto._lib.EVP_PKEY_get1_RSA(k._pkey)
>>> crypto._lib.PEM_write_bio_RSAPublicKey(bio, rsa)
1
>>> s = crypto._bio_to_string(bio)
>>> print(s)
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBANF1gYh10F8HTQdM6+bkwAwJ0Md6bMciKbP3qS6KTki3v3m+cM17Szqq
Mp4xxWbvnS2oeotYfn8eaZg0QUTOVDd1F7tuOxVEdvQ9ZEp1aeOCRU3b9QZSmVfg
wJrqDG3f149mNdexI12plwaxyt6odonv6+fEQJrbhrV/nIA8N/EFAgMBAAE=
-----END RSA PUBLIC KEY-----
This is just for illustration purposes. A proper solution should be added to the crypto module itself, via a new method dump_publickey() or the like.

Decrypting PGP using gnupg in Python

I am trying to decrypt a PGP file using this module:
http://packages.python.org/python-gnupg/
Here is my code snippet:
#!/usr/bin/python
import gnupg
gpg = gnupg.GPG(gnupghome='C:\\Users\\GSquire\\Desktop\\GnuPG',
gpgbinary='C:\\Users\\GSquire\\Desktop\\GnuPG\\pub\\gpg.exe',
keyring='C:\\Users\\GSquire\\Desktop\\GnuPG\\secring.skr')
with open('.\\tranx08022012.txt.pgp', 'rb') as f:
status = gpg.decrypt_file(f, passphrase='passphrase', output='out.txt')
I am using the latest version of the module, and Python 2.6.6. I thought I could just use the secure ring file to decrypt it because that is obviously needed by the file. It outputs this when I run the script:
ok: False
status:
stderr:
gpg: expected public key but found secret key - must stop
Isn't it true that the secure key is what decrypts the file? Thanks for the help!
The error you're getting is because you're passing the secret keyring's filename in the keyring parameter. That parameter is only for the public keyring. Unfortunately, there doesn't seem to be an alternative parameter to specify a secret keyring file.
By default, GnuPG will look for secret keys in secring.gpg in the gnupghome folder you specify, so you can probably rename your secret key file and get it to work.

Categories