Encrypt/Decrypt Files with SecureString

Posted Saturday, January 14, 2012 in Old JamesCMS Posts

Here's two simple functions done in powershell that will take a text file and perform encryption or decryption on it.

{{Powershell}}
function encrypt([string]$filepath){            
    [string]$plaintext = [string]::join([environment]::newline, (get-content $filepath))  #retains newlines            
    $filename = get-childitem $filepath            
    $filename = "Encrypted-" + $filename.Name            
    $ciphertext = ConvertTo-SecureString $plaintext -force -asPlainText            
    $bytes = ConvertFrom-SecureString $ciphertext            
    $bytes | Out-File $filename            
}           
             
            
function decrypt([string]$filepath){            
    $ciphertext = get-content $filepath            
    $filename = get-childitem $filepath            
    $filename = $filename.Name.Replace("Encrypted-", "")            
    $ciphertext = ConvertTo-SecureString -string $ciphertext            
    $plaintext = [System.Runtime.InteropServices.marshal]::PtrToStringAuto(
        [System.Runtime.InteropServices.marshal]::SecureStringToBSTR($ciphertext))            
    $plaintext | Out-File $filename            
}