go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/server/encryptedcookies/internal/crypto_test.go (about) 1 // Copyright 2021 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package internal 16 17 import ( 18 "bytes" 19 "testing" 20 21 "github.com/google/tink/go/aead" 22 "github.com/google/tink/go/keyset" 23 24 "go.chromium.org/luci/server/encryptedcookies/internal/encryptedcookiespb" 25 "go.chromium.org/luci/server/encryptedcookies/session/sessionpb" 26 27 . "github.com/smartystreets/goconvey/convey" 28 . "go.chromium.org/luci/common/testing/assertions" 29 ) 30 31 func TestGenerateNonce(t *testing.T) { 32 t.Parallel() 33 34 Convey("Works", t, func() { 35 nonce1 := GenerateNonce() 36 nonce2 := GenerateNonce() 37 So(nonce1, ShouldHaveLength, 16) 38 So(bytes.Equal(nonce1, nonce2), ShouldBeFalse) 39 }) 40 } 41 42 func TestCrypto(t *testing.T) { 43 t.Parallel() 44 45 Convey("With keyset", t, func() { 46 kh, err := keyset.NewHandle(aead.AES256GCMKeyTemplate()) 47 So(err, ShouldBeNil) 48 ae, err := aead.New(kh) 49 So(err, ShouldBeNil) 50 51 Convey("State enc/dec", func() { 52 state := &encryptedcookiespb.OpenIDState{DestHost: "blah"} 53 54 enc, err := EncryptStateB64(ae, state) 55 So(err, ShouldBeNil) 56 57 dec, err := DecryptStateB64(ae, enc) 58 So(err, ShouldBeNil) 59 So(dec, ShouldResembleProto, state) 60 61 _, err = DecryptStateB64(ae, "aaaaaaaa"+enc[8:]) 62 So(err, ShouldNotBeNil) 63 }) 64 65 Convey("Private enc/dec", func() { 66 priv := &sessionpb.Private{AccessToken: "blah"} 67 68 enc, err := EncryptPrivate(ae, priv) 69 So(err, ShouldBeNil) 70 71 dec, err := DecryptPrivate(ae, enc) 72 So(err, ShouldBeNil) 73 So(dec, ShouldResembleProto, priv) 74 75 for i := 0; i < 8; i++ { 76 enc[i] = 0 77 } 78 _, err = DecryptPrivate(ae, enc) 79 So(err, ShouldNotBeNil) 80 }) 81 }) 82 }