diff --git a/pkcs/cipher.go b/pkcs/cipher.go index 6f8ce33..5f5e665 100644 --- a/pkcs/cipher.go +++ b/pkcs/cipher.go @@ -169,10 +169,13 @@ type gcmBlockCipher struct { nonceSize int } -// http://javadoc.iaik.tugraz.at/iaik_jce/current/index.html?iaik/security/cipher/GCMParameters.html +// https://datatracker.ietf.org/doc/rfc5084/ +// GCMParameters ::= SEQUENCE { +// aes-nonce OCTET STRING, -- recommended size is 12 octets +// aes-ICVlen AES-GCM-ICVlen DEFAULT 12 } type gcmParameters struct { - Nonce []byte `asn1:"tag:4"` - ICVLen int + Nonce []byte + ICVLen int `asn1:"default:12,optional"` } func (c *gcmBlockCipher) Encrypt(key, plaintext []byte) (*pkix.AlgorithmIdentifier, []byte, error) { @@ -222,7 +225,7 @@ func (c *gcmBlockCipher) Decrypt(key []byte, parameters *asn1.RawValue, encrypte return nil, err } if params.ICVLen != aead.Overhead() { - return nil, errors.New("pkcs: invalid tag size") + return nil, errors.New("pkcs: we do not support non-standard tag size") } return aead.Open(nil, params.Nonce, encryptedKey, nil) diff --git a/pkcs/cipher_test.go b/pkcs/cipher_test.go index 01de947..c1c9746 100644 --- a/pkcs/cipher_test.go +++ b/pkcs/cipher_test.go @@ -1,9 +1,13 @@ package pkcs import ( + "bytes" "crypto/x509/pkix" "encoding/asn1" "testing" + + "golang.org/x/crypto/cryptobyte" + cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1" ) func TestGetCipher(t *testing.T) { @@ -57,3 +61,27 @@ func TestInvalidKeyLen(t *testing.T) { t.Errorf("should be error") } } + +func TestGcmParameters(t *testing.T) { + var b cryptobyte.Builder + b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) { + b.AddASN1OctetString([]byte("123456789012")) + }) + pb1, _ := b.Bytes() + params := gcmParameters{} + _, err := asn1.Unmarshal(pb1, ¶ms) + if err != nil { + t.Fatal(err) + } + if params.ICVLen != 12 { + t.Errorf("should be 12, but got %v", params.ICVLen) + } + if !bytes.Equal([]byte("123456789012"), params.Nonce) { + t.Errorf("not expected nonce") + } + + pb2, _ := asn1.Marshal(params) + if !bytes.Equal(pb1, pb2) { + t.Errorf("not consistent result") + } +}