首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PowerShell非对称加密

PowerShell非对称加密
EN

Stack Overflow用户
提问于 2016-10-13 09:02:57
回答 1查看 1.9K关注 0票数 1

我试图使用从base64生成的公钥加密$key字符串。但是(据我所发现),我只能导入一个证书(在PowerShell中),然后使用从X509Certificate2对象提取的公钥对目标进行加密。

但是,在获得结果之后,当我尝试使用python脚本解密结果时,我将不会返回原始明文。但是,当我在python脚本中使用相同的密钥进行加密和解密时,我会得到原始明文。

所以,我猜我可能是错误地做了PowerShell公钥加密(如下图所示),或者我被绊倒了。

PowerShell:

代码语言:javascript
复制
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-解密:

代码语言:javascript
复制
#!/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-加密:

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-17 00:37:32

由于@PetSerAl,他说在PowerShell中有OAEP填充,但是在Python代码中没有任何填充(上面)。下面是使用PKCS1_OAEP模块编辑的python解密代码。

Python-解密:

代码语言:javascript
复制
#!/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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40016624

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档