Encrypt/decrypt text files using any file as a private key

Posted: October 28, 2011 in File Operations, Information Technology, Scripts

This script requires the PowerShell Community Extensions for the Get-Hash function. It will use the MD5 hash of any file as the key for encryption/decryption, take a plain text input and output the encrypted text, or vice versa.
This script has 4 inputs:

  • A switch to set which direction you are going. use “enc” to encrypt text, anything else to decrypt
  • The file you want to use as the key
  • The plain text file location, this will either be the plain text input or plain text output depending on which way you are going
  • The encrypted file location, again either input or output depending on which direction
  • Example usage:

    c:\scripts\SecureText.ps1 enc C:\Scripts\MyKeyFile.zip C:\Scripts\SensitiveData.txt C:\Scripts\SensitiveData.enc

    This will use the file MyKeyfile.zip as the key generator and take the data in the .txt file and output the encrypted version to the enc file.

    To reverse it on the other side, you will need the exact same copy of the MyKeyfile.zip. Just change the switch value.

    c:\scripts\SecureText.ps1 dec C:\Scripts\MyKeyFile.zip C:\Scripts\SensitiveData.txt C:\Scripts\SensitiveData.enc

    And here is the code:

    param ([string] $Switch, $HashFile, $PlainTextData, $EncryptedData)
    Import-Module Pscx

    $String = (Get-Hash $HashFile).HashString
    $Encoding = New-Object System.Text.ASCIIEncoding
    $Key = $Encoding.GetBytes($String)

    Function EncryptData{
    $SecureString = ConvertTo-SecureString -AsPlainText -Force (Get-Content $PlainTextData)
    $encryptedData = ConvertFrom-SecureString -SecureString $secureString -Key $key | Out-File $EncryptedData
    }

    Function DecryptData{
    $SecureString = ConvertTo-SecureString -Key $Key -String (Get-Content $EncryptedData | Out-String)
    [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString)) | Out-File $PlainTextData
    }

    If ($Switch -eq “enc”) { EncryptData} Else { DecryptData }

    Advertisements

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s