我正在尝试使用从OpenSSL生成的公钥来加密base64字符串($ key)。但是(从我发现的),我只能导入证书(在PowerShell中),然后使用X509Certificate2对象的公钥提取加密目标。
然而,在得到结果后,当我尝试使用python脚本解密结果时,我没有收回原始明文。但是,当我在python脚本中使用相同的密钥加密和解密时,我会收回原始明文。
所以,我猜我要么错误地进行PowerShell公钥加密(如下所示),要么就是绊倒。
的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的解密:
#!/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的加密:
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)
答案 0 :(得分:0)
感谢@PetSerAl,他说PowerShell中有OAEP填充,但Python代码中没有(上图)。以下是使用PKCS1_OAEP模块编辑的python-decrypt代码。
Python的解密:
#!/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)