|
| 1 | +package symmetric |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/aes" |
| 5 | + "crypto/cipher" |
| 6 | + "errors" |
| 7 | +) |
| 8 | + |
| 9 | +var ( |
| 10 | + ErrInvalidKeyLength = errors.New("invalid key length") |
| 11 | + ErrInvalidMode = errors.New("invalid mode") |
| 12 | +) |
| 13 | + |
| 14 | +type AESMode uint8 |
| 15 | + |
| 16 | +const ( |
| 17 | + GCM AESMode = iota |
| 18 | +) |
| 19 | + |
| 20 | +type AESEncrypterDecrypter struct { |
| 21 | + keyID string |
| 22 | + keyBytes []byte |
| 23 | + mode AESMode |
| 24 | +} |
| 25 | + |
| 26 | +// NewAESEncrypterDecrypterFromSSLibSymmetricKey creates an |
| 27 | +// AESEncrypterDecrypter from an SSLibSymmetricKey. |
| 28 | +func NewAESEncrypterDecrypterFromSSLibSymmetricKey(key *SSLibSymmetricKey, mode AESMode) (*AESEncrypterDecrypter, error) { |
| 29 | + switch mode { |
| 30 | + case GCM: |
| 31 | + break |
| 32 | + default: |
| 33 | + return nil, ErrInvalidMode |
| 34 | + } |
| 35 | + |
| 36 | + return &AESEncrypterDecrypter{ |
| 37 | + keyID: key.KeyID, |
| 38 | + keyBytes: key.KeyVal, |
| 39 | + mode: mode, |
| 40 | + }, nil |
| 41 | +} |
| 42 | + |
| 43 | +func (ed *AESEncrypterDecrypter) Encrypt(data []byte) ([]byte, error) { |
| 44 | + block, err := aes.NewCipher(ed.keyBytes) |
| 45 | + if err != nil { |
| 46 | + return nil, err |
| 47 | + } |
| 48 | + |
| 49 | + var ciphertext []byte |
| 50 | + |
| 51 | + switch ed.mode { |
| 52 | + case GCM: |
| 53 | + gcm, err := cipher.NewGCMWithRandomNonce(block) |
| 54 | + if err != nil { |
| 55 | + return nil, err |
| 56 | + } |
| 57 | + |
| 58 | + ciphertext = gcm.Seal(nil, nil, data, nil) |
| 59 | + } |
| 60 | + return ciphertext, nil |
| 61 | +} |
| 62 | + |
| 63 | +func (ed *AESEncrypterDecrypter) Decrypt(data []byte) ([]byte, error) { |
| 64 | + block, err := aes.NewCipher(ed.keyBytes) |
| 65 | + if err != nil { |
| 66 | + return nil, err |
| 67 | + } |
| 68 | + |
| 69 | + var plaintext []byte |
| 70 | + switch ed.mode { |
| 71 | + case GCM: |
| 72 | + gcm, err := cipher.NewGCMWithRandomNonce(block) |
| 73 | + if err != nil { |
| 74 | + return nil, err |
| 75 | + } |
| 76 | + |
| 77 | + plaintext, err = gcm.Open(nil, nil, data, nil) |
| 78 | + if err != nil { |
| 79 | + return nil, err |
| 80 | + } |
| 81 | + } |
| 82 | + return plaintext, nil |
| 83 | +} |
| 84 | + |
| 85 | +func (ed *AESEncrypterDecrypter) KeyID() (string, error) { |
| 86 | + return ed.keyID, nil |
| 87 | +} |
| 88 | + |
| 89 | +func validateAESKeySize(key []byte) (int, error) { |
| 90 | + switch len(key) { |
| 91 | + // AES-128, AES-192, AES-256 |
| 92 | + case 16, 24, 32: |
| 93 | + return len(key) / 8, nil |
| 94 | + default: |
| 95 | + return 0, ErrInvalidKeyLength |
| 96 | + } |
| 97 | +} |
0 commit comments