I am trying to encrypt a base64 string ($key), using a public key generated from OpenSSL. But (from what I found), I can only import a Certificate (in PowerShell), and then encrypt the target using the public key extract from the X509Certificate2 Object.
However after getting the result, when I try to decrypt the result using python script, I don't get back the original plaintext. But, when I encrypt and decrypt using the same keys in python script, I get back the original plaintext.
So, I am guessing that either I did the PowerShell public key encryption wrongly (shown below), or I am tripping.
PowerShell:
function encryptKey(){
Param(
[Parameter(Mandatory = $true,Position = 0,HelpMessage = 'key')]
[ValidateNotNullorEmpty()]
[String]$key
)
[byte[]] $certBytes = <byte array of public key, extracted from certificate from OpenSSL>
$cert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import($certBytes)
$byteval = [System.Text.Encoding]::UTF8.GetBytes($key)
$encKey = $cert.PublicKey.Key.Encrypt($byteval, $true)
$encKey = [System.Convert]::ToBase64String($encKey)
return $encKey
}
Python-Decrypt:
#!/usr/bin/python
from Crypto.PublicKey import RSA
from base64 import b64decode
from base64 import b64encode
privKey = "<Private key in String>"
encKey = "<encrypted String TO DECRYPT>"
privKey = b64decode(privKey)
r = RSA.importKey(privKey,passphrase=None)
encKey = b64decode(encKey)
decKey = r.decrypt(encKey)
print decKey
with open('sucks.txt','w') as f:
f.write(decKey)
Python-Encrypt:
from Crypto.PublicKey import RSA
from base64 import b64decode
from base64 import b64encode
key64 = b'<Public Key (extracted) >'
keyDER = b64decode(key64)
keyPub = RSA.importKey(keyDER)
key = "TPnrxxxxxxjT8JLXWMJrPQ==" #key is the target to be encrypted
enc = keyPub.encrypt(key,32)
enc = ''.join((enc))
print b64encode(enc)
Thanks to @PetSerAl, he said that there is OAEP padding in PowerShell but none in the Python code (above). So below is the edited python-decrypt code using the PKCS1_OAEP module.
Python-Decrypt:
#!/usr/bin/python
from Crypto.PublicKey import RSA
from base64 import b64decode
from base64 import b64encode
from Crypto.Cipher import PKCS1_OAEP
privKey = "<Private key in String>"
encKey = "<encrypted String TO DECRYPT>"
privKey = b64decode(privKey)
r = RSA.importKey(privKey,passphrase=None)
cipher = PKCS1_OAEP.new(r)
encKey = b64decode(encKey)
decKey = cipher.decrypt(encKey)
print decKey
with open('sucks.txt','w') as f:
f.write(decKey)