且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Powershell中生成RSA密钥对

更新时间:2023-01-31 20:30:02

如果您只想使用powershell实施公钥加密/解密,则可以使用内置工具。要生成密钥对,只需使用New-SelfSignedCertificate cmdlet,然后就可以使用Protect / Unprotect-CmsMessage使用生成的证书来加密/解密数据(这是类似PGP的cmdlet,这意味着您不必自己处理对称密钥部分) 。然后,要将密钥共享或移动到其他计算机,可以使用Import / Export-Certificate cmdlet。参见下面的示例

If you just want to implement Public Key encryption/decryption with powershell, there are built-in tools for that. To generate key pair just use New-SelfSignedCertificate cmdlet, then you can use generated certificate to encrypt/decrypt data using Protect/Unprotect-CmsMessage (this is PGP-like cmdlets, meaning you don't have to deal with symmetric key part yourself). Then to share or move keys to other machines you can use Import/Export-Certificate cmdlets. See the example below

$store = "cert:\CurrentUser\My"

$params = @{
 CertStoreLocation = $store
 Subject = "CN=Test1"
 KeyLength = 2048
 KeyAlgorithm = "RSA" 
 KeyUsage = "DataEncipherment"
 Type = "DocumentEncryptionCert"
}

# generate new certificate and add it to certificate store
$cert = New-SelfSignedCertificate @params


# list all certs 
# Get-ChildItem -path $store

# Encryption / Decryption

$message = "My secret message"

$cipher = $message  | Protect-CmsMessage -To "CN=Test1" 
Write-Host "Cipher:" -ForegroundColor Green
$cipher

Write-Host "Decrypted message:" -ForegroundColor Green
$cipher | Unprotect-CmsMessage


# Exporting/Importing certificate

$pwd = ("P@ssword" | ConvertTo-SecureString -AsPlainText -Force)
$privateKey = "$home\Documents\Test1.pfx"
$publicKey = "$home\Documents\Test1.cer"

# Export private key as PFX certificate, to use those Keys on different machine/user
Export-PfxCertificate -FilePath $privateKey -Cert $cert -Password $pwd

# Export Public key, to share with other users
Export-Certificate -FilePath $publicKey -Cert $cert

#Remove certificate from store
$cert | Remove-Item

# Add them back:
# Add private key on your machine
Import-PfxCertificate -FilePath $privateKey -CertStoreLocation $store -Password $pwd

# This is for other users (so they can send you encrypted messages)
Import-Certificate -FilePath $publicKey -CertStoreLocation $store