golang.zx2c4.com/wireguard/windows@v0.5.4-0.20230123132234-dcc0eb72a04b/conf/dpapi/dpapi_windows_test.go (about) 1 /* SPDX-License-Identifier: MIT 2 * 3 * Copyright (C) 2019-2022 WireGuard LLC. All Rights Reserved. 4 */ 5 6 package dpapi 7 8 import ( 9 "bytes" 10 "testing" 11 "unsafe" 12 13 "golang.org/x/sys/windows" 14 ) 15 16 func TestRoundTrip(t *testing.T) { 17 name := "golang test" 18 original := []byte("The quick brown fox jumped over the lazy dog") 19 20 e, err := Encrypt(original, name) 21 if err != nil { 22 t.Errorf("Error encrypting: %s", err.Error()) 23 } 24 25 if len(e) < len(original) { 26 t.Error("Encrypted data is smaller than original data.") 27 } 28 29 d, err := Decrypt(e, name) 30 if err != nil { 31 t.Errorf("Error decrypting: %s", err.Error()) 32 } 33 34 if !bytes.Equal(d, original) { 35 t.Error("Decrypted content does not match original") 36 } 37 38 _, err = Decrypt(e, "bad name") 39 if err == nil { 40 t.Error("Decryption failed to notice ad mismatch") 41 } 42 43 eCorrupt := make([]byte, len(e)) 44 copy(eCorrupt, e) 45 eCorrupt[len(original)-1] = 7 46 _, err = Decrypt(eCorrupt, name) 47 if err == nil { 48 t.Error("Decryption failed to notice ciphertext corruption") 49 } 50 51 copy(eCorrupt, e) 52 nameUtf16, err := windows.UTF16FromString(name) 53 if err != nil { 54 t.Errorf("Unable to get utf16 chars for name: %s", err) 55 } 56 nameUtf16Bytes := unsafe.Slice((*byte)(unsafe.Pointer(&nameUtf16[0])), len(nameUtf16)*2) 57 i := bytes.Index(eCorrupt, nameUtf16Bytes) 58 if i == -1 { 59 t.Error("Unable to find ad in blob") 60 } else { 61 eCorrupt[i] = 7 62 _, err = Decrypt(eCorrupt, name) 63 if err == nil { 64 t.Error("Decryption failed to notice ad corruption") 65 } 66 } 67 68 // BUG: Actually, Windows doesn't report length extension of the buffer, unfortunately. 69 // 70 // eCorrupt = make([]byte, len(e)+1) 71 // copy(eCorrupt, e) 72 // _, err = Decrypt(eCorrupt, name) 73 // if err == nil { 74 // t.Error("Decryption failed to notice length extension") 75 // } 76 }