github.com/emmansun/gmsm@v0.29.1/pkcs/cipher_test.go (about) 1 package pkcs 2 3 import ( 4 "bytes" 5 "crypto/rand" 6 "crypto/x509/pkix" 7 "encoding/asn1" 8 "testing" 9 10 "golang.org/x/crypto/cryptobyte" 11 cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1" 12 ) 13 14 func TestGetCipher(t *testing.T) { 15 marshalledIV, err := asn1.Marshal([]byte("0123456789ABCDEF")) 16 if err != nil { 17 t.Fatal(err) 18 } 19 sm4Scheme := pkix.AlgorithmIdentifier{ 20 Algorithm: oidSM4, 21 Parameters: asn1.RawValue{FullBytes: marshalledIV}, 22 } 23 cipher, err := GetCipher(sm4Scheme) 24 if err != nil { 25 t.Fatal(err) 26 } 27 if !cipher.OID().Equal(oidSM4CBC) { 28 t.Errorf("not expected CBC") 29 } 30 31 _, err = GetCipher(pkix.AlgorithmIdentifier{Algorithm: asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 401, 2}}) 32 if err == nil || err.Error() != "pbes: unsupported cipher (OID: 1.2.156.10197.1.401.2)" { 33 t.Fatal(err) 34 } 35 } 36 37 func TestInvalidKeyLen(t *testing.T) { 38 plaintext := []byte("Hello World") 39 invalidKey := []byte("123456") 40 _, _, err := SM4ECB.Encrypt(rand.Reader, invalidKey, plaintext) 41 if err == nil { 42 t.Errorf("should be error") 43 } 44 _, err = SM4ECB.Decrypt(invalidKey, nil, nil) 45 if err == nil { 46 t.Errorf("should be error") 47 } 48 _, _, err = SM4CBC.Encrypt(rand.Reader, invalidKey, plaintext) 49 if err == nil { 50 t.Errorf("should be error") 51 } 52 _, err = SM4CBC.Decrypt(invalidKey, nil, nil) 53 if err == nil { 54 t.Errorf("should be error") 55 } 56 _, _, err = SM4GCM.Encrypt(rand.Reader, invalidKey, plaintext) 57 if err == nil { 58 t.Errorf("should be error") 59 } 60 _, err = SM4GCM.Decrypt(invalidKey, nil, nil) 61 if err == nil { 62 t.Errorf("should be error") 63 } 64 } 65 66 func TestGcmParameters(t *testing.T) { 67 var b cryptobyte.Builder 68 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) { 69 b.AddASN1OctetString([]byte("123456789012")) 70 }) 71 pb1, _ := b.Bytes() 72 params := gcmParameters{} 73 _, err := asn1.Unmarshal(pb1, ¶ms) 74 if err != nil { 75 t.Fatal(err) 76 } 77 if params.ICVLen != 12 { 78 t.Errorf("should be 12, but got %v", params.ICVLen) 79 } 80 if !bytes.Equal([]byte("123456789012"), params.Nonce) { 81 t.Errorf("not expected nonce") 82 } 83 84 pb2, _ := asn1.Marshal(params) 85 if !bytes.Equal(pb1, pb2) { 86 t.Errorf("not consistent result") 87 } 88 }