# очистка старого
Get-ChildItem Cert:\CurrentUser\My | Where-Object Subject -eq "CN=LabCert" | Remove-Item
Remove-Item C:\lab, C:\lab2 -Recurse -Force -ErrorAction SilentlyContinue
mkdir C:\lab, C:\lab2 | Out-Null
cd C:\lab
$pass = ConvertTo-SecureString "123456" -AsPlainText -Force
$pad = [System.Security.Cryptography.RSAEncryptionPadding]::OaepSHA256
$ext = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]
# 1. сертификат и ключи
$cert = New-SelfSignedCertificate -Subject "CN=LabCert" -Type DocumentEncryptionCert -KeyAlgorithm RSA -KeyLength 2048 -CertStoreLocation Cert:\CurrentUser\My
Export-Certificate -Cert $cert -FilePath C:\lab\cert.cer | Out-Null
Export-PfxCertificate -Cert $cert -FilePath C:\lab\cert.pfx -Password $pass | Out-Null
# 2. файлы с фамилией
$text = "Фелионидов Данил Сергеевич"
$text | Set-Content C:\lab\a.txt -Encoding UTF8
$text | Set-Content C:\lab\b.txt -Encoding UTF8
# 3. шифрование: a - сертификатом, b - открытым ключом
Protect-CmsMessage -To $cert -Path C:\lab\a.txt -OutFile C:\lab\a.enc
$pub = $ext::GetRSAPublicKey((New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\lab\cert.cer")))
[IO.File]::WriteAllBytes("C:\lab\b.enc", $pub.Encrypt([IO.File]::ReadAllBytes("C:\lab\b.txt"), $pad))
"=== ЗАШИФРОВАННЫЙ a.enc ==="; Get-Content C:\lab\a.enc | Select-Object -First 4
# 4. "другой компьютер": копируем файлы и удаляем сертификат из Windows
copy C:\lab\a.enc, C:\lab\b.enc, C:\lab\cert.pfx C:\lab2
Get-ChildItem Cert:\CurrentUser\My | Where-Object Subject -eq "CN=LabCert" | Remove-Item
"=== БЕЗ КЛЮЧА (ошибка - это нормально) ==="
Unprotect-CmsMessage -Path C:\lab2\a.enc
# 5. расшифровка закрытым ключом из pfx
Import-PfxCertificate -FilePath C:\lab2\cert.pfx -CertStoreLocation Cert:\CurrentUser\My -Password $pass | Out-Null
Unprotect-CmsMessage -Path C:\lab2\a.enc | Set-Content C:\lab2\a_dec.txt -Encoding UTF8
$c = Get-ChildItem Cert:\CurrentUser\My | Where-Object Subject -eq "CN=LabCert"
$priv = $ext::GetRSAPrivateKey($c)
[IO.File]::WriteAllBytes("C:\lab2\b_dec.txt", $priv.Decrypt([IO.File]::ReadAllBytes("C:\lab2\b.enc"), $pad))
# 6. результат
"=== ОРИГИНАЛЫ ==="; type C:\lab\a.txt; type C:\lab\b.txt
"=== РАСШИФРОВАНО ==="; type C:\lab2\a_dec.txt; type C:\lab2\b_dec.txt