github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/encrypt/aesgcm_test.go (about) 1 // Copyright 2023 The GitBundle Inc. All rights reserved. 2 // Copyright 2017 The Gitea Authors. All rights reserved. 3 // Use of this source code is governed by a MIT-style 4 // license that can be found in the LICENSE file. 5 6 // Copyright 2019 Drone.IO Inc. All rights reserved. 7 // Use of this source code is governed by the Drone Non-Commercial License 8 // that can be found in the LICENSE file. 9 10 package encrypt 11 12 import ( 13 "crypto/aes" 14 "crypto/rand" 15 "testing" 16 17 "github.com/stretchr/testify/assert" 18 ) 19 20 func TestAesgcm(t *testing.T) { 21 s := "correct-horse-batter-staple" 22 n, _ := New("fb4b4d6267c8a5ce8231f8b186dbca92") 23 ciphertext, err := n.Encrypt(s) 24 if err != nil { 25 t.Error(err) 26 } 27 plaintext, err := n.Decrypt(ciphertext) 28 if err != nil { 29 t.Error(err) 30 } 31 if want, got := plaintext, s; got != want { 32 t.Errorf("Want plaintext %q, got %q", want, got) 33 } 34 } 35 36 func TestAesgcmFail(t *testing.T) { 37 s := "correct-horse-batter-staple" 38 n, _ := New("ea1c5a9145c8a5ce8231f8b186dbcabc") 39 ciphertext, err := n.Encrypt(s) 40 if err != nil { 41 t.Error(err) 42 } 43 n, _ = New("fb4b4d6267c8a5ce8231f8b186dbca92") 44 _, err = n.Decrypt(ciphertext) 45 if err == nil { 46 t.Error("Expect error when encryption and decryption keys mismatch") 47 } 48 } 49 50 func TestAesgcmCompat(t *testing.T) { 51 s := "correct-horse-batter-staple" 52 n := Encrypter(&None{}) 53 ciphertext, err := n.Encrypt(s) 54 if err != nil { 55 t.Error(err) 56 } 57 n, _ = New("ea1c5a9145c8a5ce8231f8b186dbcabc") 58 n.(*Aesgcm).Compat = true 59 plaintext, err := n.Decrypt(ciphertext) 60 if err != nil { 61 t.Error(err) 62 } 63 if want, got := plaintext, s; got != want { 64 t.Errorf("Want plaintext %q, got %q", want, got) 65 } 66 } 67 68 func TestAESGCM(t *testing.T) { 69 t.Parallel() 70 71 key := make([]byte, 2*aes.BlockSize) 72 _, err := rand.Read(key) 73 assert.NoError(t, err) 74 75 plaintext := []byte("this will be encrypted") 76 77 ciphertext, err := AesGcmEncrypt(key, plaintext) 78 assert.NoError(t, err) 79 80 decrypted, err := AesGcmDecrypt(key, ciphertext) 81 assert.NoError(t, err) 82 83 assert.Equal(t, plaintext, decrypted) 84 }