Decrypt decrypts data encrypted with Encrypt.
(encrypted string)
| 98 | |
| 99 | // Decrypt decrypts data encrypted with Encrypt. |
| 100 | func (e *Encryption) Decrypt(encrypted string) (string, error) { |
| 101 | if encrypted == "" { |
| 102 | return "", nil |
| 103 | } |
| 104 | parts := strings.Split(encrypted, ":") |
| 105 | if len(parts) != 3 { |
| 106 | return "", fmt.Errorf("encryption: invalid format") |
| 107 | } |
| 108 | iv, err := hex.DecodeString(parts[0]) |
| 109 | if err != nil || len(iv) != ivLength { |
| 110 | return "", fmt.Errorf("encryption: invalid iv") |
| 111 | } |
| 112 | authTag, err := hex.DecodeString(parts[1]) |
| 113 | if err != nil || len(authTag) != authTagLength { |
| 114 | return "", fmt.Errorf("encryption: invalid auth tag") |
| 115 | } |
| 116 | ciphertext, err := hex.DecodeString(parts[2]) |
| 117 | if err != nil { |
| 118 | return "", err |
| 119 | } |
| 120 | block, err := aes.NewCipher(e.key) |
| 121 | if err != nil { |
| 122 | return "", err |
| 123 | } |
| 124 | aead, err := cipher.NewGCM(block) |
| 125 | if err != nil { |
| 126 | return "", err |
| 127 | } |
| 128 | combined := append(ciphertext, authTag...) |
| 129 | plaintext, err := aead.Open(nil, iv, combined, nil) |
| 130 | if err != nil { |
| 131 | return "", err |
| 132 | } |
| 133 | return string(plaintext), nil |
| 134 | } |
no outgoing calls
no test coverage detected