github.com/emmansun/gmsm@v0.29.1/pkcs/pkcs5_pbes2_test.go (about) 1 package pkcs 2 3 import ( 4 "crypto/rand" 5 "encoding/asn1" 6 "testing" 7 ) 8 9 func TestPBES2(t *testing.T) { 10 testCases := []struct { 11 name string 12 opts PBESEncrypter 13 }{ 14 { 15 name: "PBKDF2-AES128-CBC", 16 opts: NewPBESEncrypter(AES128CBC, NewPBKDF2Opts(SHA1, 16, 1000)), 17 }, 18 { 19 name: "PBKDF2-AES192-CBC", 20 opts: NewPBESEncrypter(AES192CBC, NewPBKDF2Opts(SHA1, 16, 1000)), 21 }, 22 { 23 name: "PBKDF2-AES256-CBC", 24 opts: NewPBESEncrypter(AES256CBC, NewPBKDF2Opts(SHA1, 16, 1000)), 25 }, 26 { 27 name: "PBKDF2(SHA256)-AES128-CBC", 28 opts: NewPBESEncrypter(AES128CBC, NewPBKDF2Opts(SHA256, 16, 1000)), 29 }, 30 { 31 name: "PBKDF2(SHA256)-AES192-CBC", 32 opts: NewPBESEncrypter(AES192CBC, NewPBKDF2Opts(SHA256, 16, 1000)), 33 }, 34 { 35 name: "PBKDF2(SHA256)-AES256-CBC", 36 opts: NewPBESEncrypter(AES256CBC, NewPBKDF2Opts(SHA256, 16, 1000)), 37 }, 38 { 39 name: "PBKDF2(SM3)-SM4-CBC", 40 opts: NewPBESEncrypter(SM4CBC, NewPBKDF2Opts(SM3, 16, 1000)), 41 }, 42 { 43 name: "SMPBES", 44 opts: NewSMPBESEncrypter(16, 1000), 45 }, 46 } 47 for _, tc := range testCases { 48 t.Run(tc.name, func(t *testing.T) { 49 alg, ciphertext, err := tc.opts.Encrypt(rand.Reader, []byte("password"), []byte("pbes2")) 50 if err != nil { 51 t.Errorf("unexpected error: %v", err) 52 } 53 pbes2Opts := tc.opts.(*PBES2Opts) 54 if !alg.Algorithm.Equal(pbes2Opts.pbesOID) { 55 t.Errorf("unexpected algorithm: got %v, want %v", alg.Algorithm, tc.opts.(*PBES2Opts).pbesOID) 56 } 57 var param PBES2Params 58 if _, err := asn1.Unmarshal(alg.Parameters.FullBytes, ¶m); err != nil { 59 t.Errorf("unexpected error: %v", err) 60 } 61 plaintext, _, err := param.Decrypt([]byte("password"), ciphertext) 62 if err != nil { 63 t.Errorf("unexpected error: %v", err) 64 } 65 if string(plaintext) != "pbes2" { 66 t.Errorf("unexpected plaintext: got %s, want pbes2", plaintext) 67 } 68 }) 69 } 70 }