Encrypt encrypts plaintext and returns a prefixed base64 string.
(plaintext string, key []byte)
| 121 | |
| 122 | // Encrypt encrypts plaintext and returns a prefixed base64 string. |
| 123 | func Encrypt(plaintext string, key []byte) (string, error) { |
| 124 | if plaintext == "" { |
| 125 | return "", nil |
| 126 | } |
| 127 | |
| 128 | block, err := aes.NewCipher(key) |
| 129 | if err != nil { |
| 130 | return "", err |
| 131 | } |
| 132 | |
| 133 | aesGCM, err := cipher.NewGCM(block) |
| 134 | if err != nil { |
| 135 | return "", err |
| 136 | } |
| 137 | |
| 138 | nonce := make([]byte, aesGCM.NonceSize()) |
| 139 | if _, err := io.ReadFull(rand.Reader, nonce); err != nil { |
| 140 | return "", err |
| 141 | } |
| 142 | |
| 143 | ciphertext := aesGCM.Seal(nonce, nonce, []byte(plaintext), nil) |
| 144 | return encryptedPrefix + base64.StdEncoding.EncodeToString(ciphertext), nil |
| 145 | } |
| 146 | |
| 147 | // Decrypt decrypts a prefixed base64 string back to plaintext. |
| 148 | func Decrypt(encrypted string, key []byte) (string, error) { |
no outgoing calls