Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function Invoke-DecryptWithCert{
- param(
- [parameter(mandatory=$True,Position=0)]
- $CipherText,
- [System.Security.Cryptography.X509Certificates.X509Certificate]$Certificate
- )
- if(!$Certificate){
- $Certificate = Get-ChildItem Cert:\CurrentUser\My
- if($Certificate.Count -gt 1){ Write-Error -Message "Multiple Certificates detected. Please pass one as a parameter"}
- }elseif($Certificate.GetType().BaseType.Name -ne "X509Certificate"){
- Write-Error -Category InvalidArgument -Message "Certificate not valid"
- Return $Null
- }
- $type = $CipherText.GetType().Name
- if($type -ne "String"){
- Write-Error -Category InvalidArgument -Message "Input must be a string"
- }
- $EncryptedBytes = [System.Convert]::FromBase64String($CipherText)
- $DecryptedBytes = $Certificate.PrivateKey.Decrypt($EncryptedBytes, $true)
- $DecryptedTXT = [system.text.encoding]::UTF8.GetString($DecryptedBytes)
- Return $DecryptedTXT
- }
- function Invoke-EncryptWithCert{
- param(
- [parameter(mandatory=$True,Position=0)]
- $Input,
- [System.Security.Cryptography.X509Certificates.X509Certificate]$Certificate
- )
- if(!$Certificate){
- $Certificate = Get-ChildItem Cert:\CurrentUser\My
- if($Certificate.Count -gt 1){ Write-Error -Message "Multiple Certificates detected. Please pass one as a parameter"}
- }elseif($Certificate.GetType().BaseType.Name -ne "X509Certificate"){
- Write-Error -Category InvalidArgument -Message "Certificate not valid"
- Return $Null
- }
- if($Input.GetType().Name -eq "PSCredential"){
- $EncodedTXT = [System.Text.Encoding]::UTF8.GetBytes($Input.GetNetworkCredential().Password)
- }elseif($Input.GetType().Name -eq "String"){
- $EncodedTXT = [System.Text.Encoding]::UTF8.GetBytes($Input)
- }else{
- Write-Error -Category InvalidArgument -Message "Input must be either credential or a String type"
- Return $Null
- }
- $EncryptedBytes = $Certificate.PublicKey.Key.Encrypt($EncodedTXT, $true)
- $EncryptedTXT = [System.Convert]::ToBase64String($EncryptedBytes)
- Return $EncryptedTXT
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement