1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- package crypto
- import (
- "crypto/aes"
- "crypto/cipher"
- "crypto/rand"
- "encoding/hex"
- "errors"
- "io"
- )
- func MakeKey() []byte {
- key := [32]byte{}
- _, err := io.ReadFull(rand.Reader, key[:])
- if err != nil {
- panic(err)
- }
- return key[:]
- }
- func MakeID() (string, error) {
- id := [16]byte{}
- _, err := io.ReadFull(rand.Reader, id[:])
- if err != nil {
- return "", err
- }
- return hex.EncodeToString(id[:]), nil
- }
- func Encrypt(plaintext []byte, key []byte) ([]byte, error) {
- block, err := aes.NewCipher(key)
- if err != nil {
- return nil, err
- }
- gcm, err := cipher.NewGCM(block)
- if err != nil {
- return nil, err
- }
- nonce := make([]byte, gcm.NonceSize())
- _, err = io.ReadFull(rand.Reader, nonce)
- if err != nil {
- return nil, err
- }
- return gcm.Seal(nonce, nonce, plaintext, nil), nil
- }
- func Decrypt(ciphertext, key []byte) ([]byte, error) {
- block, err := aes.NewCipher(key)
- if err != nil {
- return nil, err
- }
- gcm, err := cipher.NewGCM(block)
- if err != nil {
- return nil, err
- }
- if len(ciphertext) < gcm.NonceSize() {
- return nil, errors.New("malformed ciphertext")
- }
- return gcm.Open(nil,
- ciphertext[:gcm.NonceSize()],
- ciphertext[gcm.NonceSize():],
- nil,
- )
- }
|