Advertisement
Guest User

UnsecureString

a guest
Nov 23rd, 2016
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class UnSecureString {
  2.    [string]$EncryptedString
  3.    [byte[]]$Key
  4.    UnSecureString() { }
  5.    UnSecureString([System.Security.SecureString]$SecureString) {
  6.       $vKey = New-Object Byte[](32)
  7.       $Rng = [System.Security.Cryptography.RNGCryptoServiceProvider]::Create()
  8.       $Rng.GetBytes($vKey)
  9.       $this.Key = $vKey
  10.       $this.EncryptedString = ConvertFrom-SecureString -SecureString $SecureString -Key $vKey
  11.    }
  12.    UnSecureString([string]$String) {
  13.       $SecureString = ConvertTo-SecureString -String $String -AsPlainText -Force
  14.       $vKey = New-Object Byte[](32)
  15.       $Rng = [System.Security.Cryptography.RNGCryptoServiceProvider]::Create()
  16.       $Rng.GetBytes($vKey)
  17.       $this.Key = $vKey
  18.       $this.EncryptedString = ConvertFrom-SecureString -SecureString $SecureString -Key $vKey
  19.    }
  20.    [System.Security.SecureString]ToSecureString() {
  21.       return (ConvertTo-SecureString -String $this.EncryptedString -Key $this.Key)
  22.    }
  23.    [string]ToString() { return $this.EncryptedString }
  24. }
  25. class UnCredential {
  26.    [string]$Username
  27.    [UnSecureString]$Password
  28.    UnCredential([string]$Username, [System.Security.SecureString]$Password) {
  29.       $this.Username = $Username
  30.       $this.Password = [UnsecureString]::new($Password)
  31.    }
  32.    UnCredential([string]$Username, [string]$Password) {
  33.       $this.Username = $Username
  34.       $this.Password = [UnsecureString]::new($Password)
  35.    }
  36.    [PSCustomObject]ToPSObject() {
  37.       $f = @{
  38.          Username = $this.Username
  39.          Password = $this.Password.EncryptedString
  40.          Key = $this.Password.Key
  41.       }
  42.       return (New-Object -TypeName PSCustomObject -Property $f)
  43.    }
  44.    UnCredential([string]$Path) {
  45.       $Data = Import-Clixml -Path $Path
  46.       'Username', 'Password', 'Key' | ? { $_ -notin $Data.PSObject.Properties.Name } | %  { throw "XML in $Path missing property $_" }
  47.       $this.Username = $Data.Username
  48.       $this.Password = [UnSecureString]::new()
  49.       $this.Password.EncryptedString = $Data.Password
  50.       $this.Password.Key = $Data.Key
  51.    }
  52.    [void]Save([string]$Path) {
  53.       $this.ToPSObject() | Export-Clixml $Path
  54.    }
  55.    [System.Management.Automation.PSCredential]ToPSCredential() {
  56.       return (New-Object System.Management.Automation.PSCredential($this.Username, $this.Password.ToSecureString()))
  57.    }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement