This Script identifies the current master key GUID of the blob being encrypted by the system.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
Remove-Variable * -ErrorAction SilentlyContinue; Remove-Module *; $error.Clear(); Clear-Host #This will Break the Webcall scripts Add-Type -AssemblyName System.Security; $Password = "Password123" $PasswordBytes = [System.Text.Encoding]::ASCII.GetBytes($Password) $SecurePassword = [Security.Cryptography.ProtectedData]::Protect($PasswordBytes, $null, [Security.Cryptography.DataProtectionScope]::LocalMachine) $SecurePasswordStr = [System.Convert]::ToBase64String($SecurePassword) Write-Host $SecurePasswordStr $PlainText = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($SecurePasswordStr)) $SecurePassword | foreach { Write-Host -NoNewline $_.ToString("X").PadLeft(2,"0")""; } Write-Host #$SecurePassword | Format-Hex #$dapiblob = New-Object DPAPI_BLOB #[System.Runtime.InteropServices.Marshal]::Copy($dapiblob,0,$PlainText,$PlainText.Length) [byte[]](0,1,2,3) | foreach { $dwVersion = $dwVersion + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "dwVersion: " + $dwVersion [byte[]](7,6,5,4,9,8,11,10,13,12,14,15,16,17,18,19) | foreach { $guidProvider = $guidProvider + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "guidProvider: " + $guidProvider [byte[]](20,21,22,23) | foreach { $dwMasterKeyVersion = $dwMasterKeyVersion + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "dwMasterKeyVersion: " + $dwMasterKeyVersion [byte[]](27,26,25,24,29,28,31,30,32,33,34,35,36,37,38,39) | foreach { $guidMasterKey = $guidMasterKey + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "guidMasterKey: " + $guidMasterKey [byte[]](40,41,42,43) | foreach { $dwFlags = $dwFlags + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "dwFlags: " + $dwFlags [byte[]](44,45,46,47) | foreach { $dwDescriptionLen = $dwDescriptionLen + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "dwDescriptionLen: " + $dwDescriptionLen [byte[]](48,49) | foreach { $szDescription = $szDescription + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "szDescription: " + $szDescription [byte[]](50,51,52,53) | foreach { $algCrypt = $algCrypt + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "algCrypt: " + $algCrypt [byte[]](54,55,56,57) | foreach { $dwAlgCryptLen = $dwAlgCryptLen + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "dwAlgCryptLen: " + $dwAlgCryptLen [byte[]](58,59,60,61) | foreach { $dwSaltLen = $dwSaltLen + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "dwSaltLen: " + $dwSaltLen [byte[]](62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77) | foreach { $pbSalt = $pbSalt + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "pbSalt: " + $pbSalt [byte[]](78,79,80,81) | foreach { $dwHmacKeyLen = $dwHmacKeyLen + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "dwHmacKeyLen: " + $dwHmacKeyLen [byte[]](78,79,80,81) | foreach { $pbHmackKey = $pbHmackKey + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "pbHmackKey: " + $pbHmackKey [byte[]](82,83,84,85) | foreach { $algHash = $algHash + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "algHash: " + $algHash [byte[]](86,87,88,89) | foreach { $dwAlgHashLen = $dwAlgHashLen + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "dwAlgHashLen: " + $dwAlgHashLen [byte[]](90,91,92,93) | foreach { $dwHmac2KeyLen = $dwHmac2KeyLen + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "dwHmac2KeyLen: " + $dwHmac2KeyLen [byte[]](94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109) | foreach { $pbHmack2Key = $pbHmack2Key + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "pbHmack2Key: " + $pbHmack2Key [byte[]](110,111,112,113) | foreach { $dwDataLen = $dwDataLen + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "dwDataLen: " + $dwDataLen [byte[]](114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137) | foreach { $pbData = $pbData + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "pbData: " + $pbData [byte[]](138,139,140,141) | foreach { $dwSignLen = $dwSignLen + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "dwSignLen: " + $dwSignLen [byte[]](151,152,153,154,155,156,157,158,159,160,161) | foreach { $pbSign = $pbSign + " " + $SecurePassword[$_].ToString("X").PadLeft(2,"0"); } "pbSign: " + $pbSign; $SecureStr = [System.Convert]::FromBase64String($SecurePasswordStr) $StringBytes = [Security.Cryptography.ProtectedData]::Unprotect($SecureStr, $null, [Security.Cryptography.DataProtectionScope]::LocalMachine) $PasswordStr = [System.Text.Encoding]::ASCII.GetString($StringBytes) Write-Host $PasswordStr |
AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAVHV+3dV0XEGGpdeIwr/L2wQAAAACAAAAAAADZgAAwAAAABAAAAC3Acu0kGl1ShI7AcSSNulJAAAAAASAAACgAAAAEAAAAAa0kmV05zGLZugZc0g+nKsQAAAAkkkbinmUcBiew391AqPh7hQAAAAfMziHP5hXYfx
OmmTywtVTS9cJGA== 01 00 00 00 D0 8C 9D DF 01 15 D1 11 8C 7A 00 C0 4F
C2 97 EB 01 00 00 00 54 75 7E DD D5 74 5C 41 86 A5 D7 88 C2 BF CB DB
04 00 00 00 02 00 00 00 00 00 03 66 00 00 C0 00 00 00 10 00 00 00 B7
01 CB B4 90 69 75 4A 12 3B 01 C4 92 36 E9 49 00 00 00 00 04 80 00 00
A0 00 00 00 10 00 00 00 06 B4 92 65 74 E7 31 8B 66 E8 19 73 48 3E 9C
AB 10 00 00 00 92 49 1B 8A 79 94 70 18 9E C3 7F 75 02 A3 E1 EE 14 00
00 00 1F 33 38 87 3F 98 57 61 FC 4E 9A 64 F2 C2 D5 53 4B D7 09 18
dwVersion: 01 00 00 00 guidProvider: DF 9D 8C D0 15 01 11 D1 7A 8C
00 C0 4F C2 97 EB dwMasterKeyVersion: 01 00 00 00 guidMasterKey: DD
7E 75 54 74 D5 41 5C 86 A5 D7 88 C2 BF CB DB dwFlags: 04 00 00 00
dwDescriptionLen: 02 00 00 00 szDescription: 00 00 algCrypt: 03 66
00 00 dwAlgCryptLen: C0 00 00 00 dwSaltLen: 10 00 00 00 pbSalt: B7
01 CB B4 90 69 75 4A 12 3B 01 C4 92 36 E9 49 dwHmacKeyLen: 00 00 00
00 pbHmackKey: 00 00 00 00 algHash: 04 80 00 00 dwAlgHashLen: A0 00
00 00 dwHmac2KeyLen: 10 00 00 00 pbHmack2Key: 06 B4 92 65 74 E7 31
8B 66 E8 19 73 48 3E 9C AB dwDataLen: 10 00 00 00 pbData: 92 49 1B
8A 79 94 70 18 9E C3 7F 75 02 A3 E1 EE 14 00 00 00 1F 33 38 87
dwSignLen: 3F 98 57 61 You cannot call a method on a null-valued
expression. At C:\mstsc\DPAPI.ps1:126 char:1
+ $pbSign = $pbSign + ” ” + $SecurePassword[$].ToString(“X”).PadLeft(2 …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At C:\mstsc\DPAPI.ps1:126 char:1
+ $pbSign = $pbSign + ” ” + $SecurePassword[$].ToString(“X”).PadLeft(2 …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At C:\mstsc\DPAPI.ps1:126 char:1
+ $pbSign = $pbSign + ” ” + $SecurePassword[$].ToString(“X”).PadLeft(2 …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At C:\mstsc\DPAPI.ps1:126 char:1
+ $pbSign = $pbSign + ” ” + $SecurePassword[$].ToString(“X”).PadLeft(2 …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At C:\mstsc\DPAPI.ps1:126 char:1
+ $pbSign = $pbSign + ” ” + $SecurePassword[$].ToString(“X”).PadLeft(2 …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At C:\mstsc\DPAPI.ps1:126 char:1
+ $pbSign = $pbSign + ” ” + $SecurePassword[$].ToString(“X”).PadLeft(2 …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At C:\mstsc\DPAPI.ps1:126 char:1
+ $pbSign = $pbSign + ” ” + $SecurePassword[$].ToString(“X”).PadLeft(2 …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At C:\mstsc\DPAPI.ps1:126 char:1
+ $pbSign = $pbSign + ” ” + $SecurePassword[$].ToString(“X”).PadLeft(2 …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull pbSign: D7 09 18 Password123PS Z:>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 |
Imports System Imports System.Text Imports System.Runtime.InteropServices Imports System.ComponentModel Imports Microsoft.VisualBasic Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Try Dim text As String = "Password123" Dim entropy As String = Nothing Dim description As String Dim encrypted As String Dim decrypted As String Console.WriteLine("Plaintext: {0}" & Chr(13) & Chr(10), text) ' Call DPAPI to encrypt data with user-specific key. encrypted = DPAPI.Encrypt(DPAPI.KeyType.MachineKey, text, entropy, "") Console.WriteLine("Encrypted: {0}" & Chr(13) & Chr(10), encrypted) ' Call DPAPI to decrypt data. decrypted = DPAPI.Decrypt(encrypted, entropy, description) Console.WriteLine("Decrypted: {0} <<<{1}>>>" & Chr(13) & Chr(10), decrypted, description) Catch ex As Exception While Not (ex Is Nothing) Console.WriteLine(ex.Message) ex = ex.InnerException End While End Try End Sub End Class Public Class DPAPI ' Wrapper for DPAPI CryptProtectData function. <DllImport("crypt32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> Private Shared Function CryptProtectData _ ( ByRef pPlainText As DATA_BLOB, ByVal szDescription As String, ByRef pEntropy As DATA_BLOB, ByVal pReserved As IntPtr, ByRef pPrompt As CRYPTPROTECT_PROMPTSTRUCT, ByVal dwFlags As Integer, ByRef pCipherText As DATA_BLOB ) As Boolean End Function ' Wrapper for DPAPI CryptUnprotectData function. <DllImport("crypt32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> Private Shared Function CryptUnprotectData _ ( ByRef pCipherText As DATA_BLOB, ByRef pszDescription As String, ByRef pEntropy As DATA_BLOB, ByVal pReserved As IntPtr, ByRef pPrompt As CRYPTPROTECT_PROMPTSTRUCT, ByVal dwFlags As Integer, ByRef pPlainText As DATA_BLOB ) As Boolean End Function ' BLOB structure used to pass data to DPAPI functions. <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> Friend Structure DATA_BLOB Public cbData As Integer Public pbData As IntPtr End Structure ' Prompt structure to be used for required parameters. <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> Friend Structure CRYPTPROTECT_PROMPTSTRUCT Public cbSize As Integer Public dwPromptFlags As Integer Public hwndApp As IntPtr Public szPrompt As String End Structure ' DPAPI key initialization flags. Private Const CRYPTPROTECT_UI_FORBIDDEN As Integer = 1 Private Const CRYPTPROTECT_LOCAL_MACHINE As Integer = 4 ' <summary> ' Initializes empty prompt structure. ' </summary> ' <param name="ps"> ' Prompt parameter (which we do not actually need). ' </param> Private Shared Sub InitPrompt _ ( ByRef ps As CRYPTPROTECT_PROMPTSTRUCT ) ps.cbSize = Marshal.SizeOf(GetType(CRYPTPROTECT_PROMPTSTRUCT)) ps.dwPromptFlags = 0 ps.hwndApp = IntPtr.Zero ps.szPrompt = Nothing End Sub ' <summary> ' Initializes a BLOB structure from a byte array. ' </summary> ' <param name="data"> ' Original data in a byte array format. ' </param> ' <param name="blob"> ' Returned blob structure. ' </param> Private Shared Sub InitBLOB _ ( ByVal data As Byte(), ByRef blob As DATA_BLOB ) ' Use empty array for null parameter. If data Is Nothing Then data = New Byte(0) {} End If ' Allocate memory for the BLOB data. blob.pbData = Marshal.AllocHGlobal(data.Length) ' Make sure that memory allocation was successful. If blob.pbData.Equals(IntPtr.Zero) Then Throw New Exception( "Unable to allocate data buffer for BLOB structure.") End If ' Specify number of bytes in the BLOB. blob.cbData = data.Length Marshal.Copy(data, 0, blob.pbData, data.Length) End Sub ' Flag indicating the type of key. DPAPI terminology refers to ' key types as user store or machine store. Public Enum KeyType UserKey = 1 MachineKey End Enum ' It is reasonable to set default key type to user key. Private Shared defaultKeyType As KeyType = KeyType.UserKey ' <summary> ' Calls DPAPI CryptProtectData function to encrypt a plaintext ' string value with a user-specific key. This function does not ' specify data description and additional entropy. ' </summary> ' <param name="plainText"> ' Plaintext data to be encrypted. ' </param> ' <returns> ' Encrypted value in a base64-encoded format. ' </returns> Public Shared Function Encrypt _ ( ByVal plainText As String ) As String Return Encrypt(defaultKeyType, plainText, String.Empty, String.Empty) End Function ' <summary> ' Calls DPAPI CryptProtectData function to encrypt a plaintext ' string value. This function does not specify data description ' and additional entropy. ' </summary> ' <param name="keyType"> ' Defines type of encryption key to use. When user key is ' specified, any application running under the same user account ' as the one making this call, will be able to decrypt data. ' Machine key will allow any application running on the same ' computer where data were encrypted to perform decryption. ' Note: If optional entropy is specifed, it will be required ' for decryption. ' </param> ' <param name="plainText"> ' Plaintext data to be encrypted. ' </param> ' <returns> ' Encrypted value in a base64-encoded format. ' </returns> Public Shared Function Encrypt _ ( ByVal keyType As KeyType, ByVal plainText As String ) As String Return Encrypt(keyType, plainText, String.Empty, String.Empty) End Function Public Shared Function Encrypt _ ( ByVal keyType As KeyType, ByVal plainText As String, ByVal entropy As String ) As String Return Encrypt(keyType, plainText, entropy, String.Empty) End Function ' <summary> ' Calls DPAPI CryptProtectData function to encrypt a plaintext ' string value. This function does not specify data description. ' </summary> ' <param name="keyType"> ' Defines type of encryption key to use. When user key is ' specified, any application running under the same user account ' as the one making this call, will be able to decrypt data. ' Machine key will allow any application running on the same ' computer where data were encrypted to perform decryption. ' Note: If optional entropy is specifed, it will be required ' for decryption. ' </param> ' <param name="plainText"> ' Plaintext data to be encrypted. ' </param> ' <param name="entropy"> ' Optional entropy which - if specified - will be required to ' perform decryption. ' </param> ' <returns> ' Encrypted value in a base64-encoded format. ' </returns> Public Shared Function Encrypt _ ( ByVal keyType As KeyType, ByVal plainText As String, ByVal entropy As String, ByVal description As String ) As String If plainText Is Nothing Then plainText = String.Empty End If If entropy Is Nothing Then entropy = String.Empty End If Dim ReturnedData() As Byte ReturnedData = Encrypt(keyType, Encoding.UTF8.GetBytes(plainText), Encoding.UTF8.GetBytes(entropy), description) Debug.Write(BytesToString(ReturnedData)) Debug.WriteLine(vbCrLf) Return Convert.ToBase64String(ReturnedData) End Function Private Shared Function BytesToString(ByVal Input As Byte()) As String Dim Result As New System.Text.StringBuilder(Input.Length * 2) Dim Part As String For Each b As Byte In Input Part = Conversion.Hex(b) If Part.Length = 1 Then Part = "0" & Part Result.Append(Part & " ") Next Return Result.ToString() End Function ' <summary> ' Calls DPAPI CryptProtectData function to encrypt an array of ' plaintext bytes. ' </summary> ' <param name="keyType"> ' Defines type of encryption key to use. When user key is ' specified, any application running under the same user account ' as the one making this call, will be able to decrypt data. ' Machine key will allow any application running on the same ' computer where data were encrypted to perform decryption. ' Note: If optional entropy is specifed, it will be required ' for decryption. ' </param> ' <param name="plainTextBytes"> ' Plaintext data to be encrypted. ' </param> ' <param name="entropyBytes"> ' Optional entropy which - if specified - will be required to ' perform decryption. ' </param> ' <param name="description"> ' Optional description of data to be encrypted. If this value is ' specified, it will be stored along with encrypted data and ' returned as a separate value during decryption. ' </param> ' <returns> ' Encrypted value. ' </returns> Public Shared Function Encrypt _ ( ByVal keyType As KeyType, ByVal plainTextBytes As Byte(), ByVal entropyBytes As Byte(), ByVal description As String ) As Byte() ' Make sure that parameters are valid. If plainTextBytes Is Nothing Then plainTextBytes = New Byte(0) {} End If If entropyBytes Is Nothing Then entropyBytes = New Byte(0) {} End If If description Is Nothing Then description = String.Empty End If ' Create BLOBs to hold data. Dim plainTextBlob As DATA_BLOB = New DATA_BLOB Dim cipherTextBlob As DATA_BLOB = New DATA_BLOB Dim entropyBlob As DATA_BLOB = New DATA_BLOB ' We only need prompt structure because it is a required ' parameter. Dim prompt As _ CRYPTPROTECT_PROMPTSTRUCT = New CRYPTPROTECT_PROMPTSTRUCT InitPrompt(prompt) Try ' Convert plaintext bytes into a BLOB structure. Try InitBLOB(plainTextBytes, plainTextBlob) Catch ex As Exception Throw New Exception("Cannot initialize plaintext BLOB.", ex) End Try ' Convert entropy bytes into a BLOB structure. Try InitBLOB(entropyBytes, entropyBlob) Catch ex As Exception Throw New Exception("Cannot initialize entropy BLOB.", ex) End Try ' Disable any types of UI. Dim flags As Integer = CRYPTPROTECT_UI_FORBIDDEN ' When using machine-specific key, set up machine flag. If keyType = KeyType.MachineKey Then flags = flags Or (CRYPTPROTECT_LOCAL_MACHINE) End If ' Call DPAPI to encrypt data. Dim success As Boolean = CryptProtectData( plainTextBlob, description, entropyBlob, IntPtr.Zero, prompt, flags, cipherTextBlob) ' Check the result. If Not success Then ' If operation failed, retrieve last Win32 error. Dim errCode As Integer = Marshal.GetLastWin32Error() ' Win32Exception will contain error message corresponding ' to the Windows error code. Throw New Exception("CryptProtectData failed.", New Win32Exception(errCode)) End If ' Allocate memory to hold ciphertext. Dim cipherTextBytes(cipherTextBlob.cbData - 1) As Byte ' Copy ciphertext from the BLOB to a byte array. Marshal.Copy(cipherTextBlob.pbData, cipherTextBytes, 0, cipherTextBlob.cbData) ' Return the result. Return cipherTextBytes Catch ex As Exception Throw New Exception("DPAPI was unable to encrypt data.", ex) Finally If Not (plainTextBlob.pbData.Equals(IntPtr.Zero)) Then Marshal.FreeHGlobal(plainTextBlob.pbData) End If If Not (cipherTextBlob.pbData.Equals(IntPtr.Zero)) Then Marshal.FreeHGlobal(cipherTextBlob.pbData) End If If Not (entropyBlob.pbData.Equals(IntPtr.Zero)) Then Marshal.FreeHGlobal(entropyBlob.pbData) End If End Try End Function ' <summary> ' Calls DPAPI CryptUnprotectData to decrypt ciphertext bytes. ' This function does not use additional entropy and does not ' return data description. ' </summary> ' <param name="cipherText"> ' Encrypted data formatted as a base64-encoded string. ' </param> ' <returns> ' Decrypted data returned as a UTF-8 string. ' </returns> ' <remarks> ' When decrypting data, it is not necessary to specify which ' type of encryption key to use: user-specific or ' machine-specific; DPAPI will figure it out by looking at ' the signature of encrypted data. ' </remarks> Public Shared Function Decrypt _ ( ByVal cipherText As String ) As String Dim description As String Return Decrypt(cipherText, String.Empty, description) End Function ' <summary> ' Calls DPAPI CryptUnprotectData to decrypt ciphertext bytes. ' This function does not use additional entropy. ' </summary> ' <param name="cipherText"> ' Encrypted data formatted as a base64-encoded string. ' </param> ' <param name="description"> ' Returned description of data specified during encryption. ' </param> ' <returns> ' Decrypted data returned as a UTF-8 string. ' </returns> ' <remarks> ' When decrypting data, it is not necessary to specify which ' type of encryption key to use: user-specific or ' machine-specific; DPAPI will figure it out by looking at ' the signature of encrypted data. ' </remarks> Public Shared Function Decrypt _ ( ByVal cipherText As String, ByRef description As String ) As String Return Decrypt(cipherText, String.Empty, description) End Function ' <summary> ' Calls DPAPI CryptUnprotectData to decrypt ciphertext bytes. ' </summary> ' <param name="cipherText"> ' Encrypted data formatted as a base64-encoded string. ' </param> ' <param name="entropy"> ' Optional entropy, which is required if it was specified during ' encryption. ' </param> ' <param name="description"> ' Returned description of data specified during encryption. ' </param> ' <returns> ' Decrypted data returned as a UTF-8 string. ' </returns> ' <remarks> ' When decrypting data, it is not necessary to specify which ' type of encryption key to use: user-specific or ' machine-specific; DPAPI will figure it out by looking at ' the signature of encrypted data. ' </remarks> Public Shared Function Decrypt _ ( ByVal cipherText As String, ByVal entropy As String, ByRef description As String ) As String ' Make sure that parameters are valid. If entropy Is Nothing Then entropy = String.Empty End If Return Encoding.UTF8.GetString( Decrypt(Convert.FromBase64String(cipherText), Encoding.UTF8.GetBytes(entropy), description)) End Function ' <summary> ' Calls DPAPI CryptUnprotectData to decrypt ciphertext bytes. ' </summary> ' <param name="cipherTextBytes"> ' Encrypted data. ' </param> ' <param name="entropyBytes"> ' Optional entropy, which is required if it was specified during ' encryption. ' </param> ' <param name="description"> ' Returned description of data specified during encryption. ' </param> ' <returns> ' Decrypted data bytes. ' </returns> ' <remarks> ' When decrypting data, it is not necessary to specify which ' type of encryption key to use: user-specific or ' machine-specific; DPAPI will figure it out by looking at ' the signature of encrypted data. ' </remarks> Public Shared Function Decrypt _ ( ByVal cipherTextBytes As Byte(), ByVal entropyBytes As Byte(), ByRef description As String ) As Byte() ' Create BLOBs to hold data. Dim plainTextBlob As DATA_BLOB = New DATA_BLOB Dim cipherTextBlob As DATA_BLOB = New DATA_BLOB Dim entropyBlob As DATA_BLOB = New DATA_BLOB ' We only need prompt structure because it is a required ' parameter. Dim prompt As _ CRYPTPROTECT_PROMPTSTRUCT = New CRYPTPROTECT_PROMPTSTRUCT InitPrompt(prompt) ' Initialize description string. description = String.Empty Try ' Convert ciphertext bytes into a BLOB structure. Try InitBLOB(cipherTextBytes, cipherTextBlob) Catch ex As Exception Throw New Exception("Cannot initialize ciphertext BLOB.", ex) End Try ' Convert entropy bytes into a BLOB structure. Try InitBLOB(entropyBytes, entropyBlob) Catch ex As Exception Throw New Exception("Cannot initialize entropy BLOB.", ex) End Try ' Disable any types of UI. CryptUnprotectData does not ' mention CRYPTPROTECT_LOCAL_MACHINE flag in the list of ' supported flags so we will not set it up. Dim flags As Integer = CRYPTPROTECT_UI_FORBIDDEN ' Call DPAPI to decrypt data. Dim success As Boolean = CryptUnprotectData( cipherTextBlob, description, entropyBlob, IntPtr.Zero, prompt, flags, plainTextBlob) ' Check the result. If Not success Then ' If operation failed, retrieve last Win32 error. Dim errCode As Integer = Marshal.GetLastWin32Error() ' Win32Exception will contain error message corresponding ' to the Windows error code. Throw New Exception("CryptUnprotectData failed.", New Win32Exception(errCode)) End If ' Allocate memory to hold plaintext. Dim plainTextBytes(plainTextBlob.cbData - 1) As Byte ' Copy ciphertext from the BLOB to a byte array. Marshal.Copy(plainTextBlob.pbData, plainTextBytes, 0, plainTextBlob.cbData) ' Return the result. Return plainTextBytes Catch ex As Exception Throw New Exception("DPAPI was unable to decrypt data.", ex) ' Free all memory allocated for BLOBs. Finally If Not (plainTextBlob.pbData.Equals(IntPtr.Zero)) Then Marshal.FreeHGlobal(plainTextBlob.pbData) End If If Not (cipherTextBlob.pbData.Equals(IntPtr.Zero)) Then Marshal.FreeHGlobal(cipherTextBlob.pbData) End If If Not (entropyBlob.pbData.Equals(IntPtr.Zero)) Then Marshal.FreeHGlobal(entropyBlob.pbData) End If End Try End Function End Class |
01 00 00 00 D0 8C 9D DF 01 15 D1 11 8C 7A 00 C0 4F C2 97 EB 01 00 00
00 54 75 7E DD D5 74 5C 41 86 A5 D7 88 C2 BF CB DB 04 00 00 00 02 00
00 00 00 00 03 66 00 00 C0 00 00 00 10 00 00 00 04 7B E6 E4 0C C0 38
D3 30 AE CC 09 7B 6F 4F 40 00 00 00 00 04 80 00 00 A0 00 00 00 10 00
00 00 CC DC 76 DA 56 55 94 22 E0 76 C8 B1 1D AC 9A B7 10 00 00 00 81
8A D4 42 39 14 2C 18 42 66 AC D1 AB FC 44 7A 14 00 00 00 50 E0 F0 2B
7D EC 99 47 B8 0E CD 5A 0A 25 AD A7 57 15 6E 9DPlaintext: Password123
Encrypted:
AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAVHV+3dV0XEGGpdeIwr/L2wQAAAACAAAAAAADZgAAwAAAABAAAAAEe+bkDMA40zCuzAl7b09AAAAAAASAAACgAAAAEAAAAMzcdtpWVZQi4HbIsR2smrcQAAAAgYrUQjkULBhCZqzRq/xEehQAAABQ4PArfeyZR7gOzVoKJa2nVxVunQ==Decrypted: Password123 <<<>>>