pkcs: update gcm parameters

This commit is contained in:
Sun Yimin 2023-03-28 11:09:58 +08:00 committed by GitHub
parent af86ca7b7b
commit f66d37654c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 4 deletions

View File

@ -169,10 +169,13 @@ type gcmBlockCipher struct {
nonceSize int 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 { type gcmParameters struct {
Nonce []byte `asn1:"tag:4"` Nonce []byte
ICVLen int ICVLen int `asn1:"default:12,optional"`
} }
func (c *gcmBlockCipher) Encrypt(key, plaintext []byte) (*pkix.AlgorithmIdentifier, []byte, error) { 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 return nil, err
} }
if params.ICVLen != aead.Overhead() { 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) return aead.Open(nil, params.Nonce, encryptedKey, nil)

View File

@ -1,9 +1,13 @@
package pkcs package pkcs
import ( import (
"bytes"
"crypto/x509/pkix" "crypto/x509/pkix"
"encoding/asn1" "encoding/asn1"
"testing" "testing"
"golang.org/x/crypto/cryptobyte"
cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
) )
func TestGetCipher(t *testing.T) { func TestGetCipher(t *testing.T) {
@ -57,3 +61,27 @@ func TestInvalidKeyLen(t *testing.T) {
t.Errorf("should be error") 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, &params)
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")
}
}