PowerShell 非对称加密

PowerShell Asymmetric Encryption

我正在尝试使用从 OpenSSL 生成的 public 密钥加密 base64 字符串($key)。但是(根据我的发现),我只能导入证书(在 PowerShell 中),然后使用从 X509Certificate2 对象中提取的 public 密钥加密目标。

但是在得到结果后,当我尝试使用 python 脚本解密结果时,我没有取回原始明文。但是,当我在 python 脚本中使用相同的密钥进行加密和解密时,我得到了原始明文。

所以,我猜测要么我错误地执行了 PowerShell public 密钥加密(如下所示),要么我被绊倒了。

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)

感谢@PetSerAl,他说 PowerShell 中有 OAEP 填充,但 Python 代码中有 none(上文)。所以下面是使用 PKCS1_OAEP 模块编辑的 python-解密代码。

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)