code.vegaprotocol.io/vega@v0.79.0/libs/crypto/encryption.go (about) 1 // Copyright (C) 2023 Gobalsky Labs Limited 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Affero General Public License as 5 // published by the Free Software Foundation, either version 3 of the 6 // License, or (at your option) any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Affero General Public License for more details. 12 // 13 // You should have received a copy of the GNU Affero General Public License 14 // along with this program. If not, see <http://www.gnu.org/licenses/>. 15 16 package crypto 17 18 import ( 19 "crypto/aes" 20 "crypto/cipher" 21 "crypto/rand" 22 "io" 23 ) 24 25 func Encrypt(data []byte, passphrase string) ([]byte, error) { 26 block, _ := aes.NewCipher(Hash([]byte(passphrase))) 27 gcm, err := cipher.NewGCM(block) 28 if err != nil { 29 return nil, err 30 } 31 nonce := make([]byte, gcm.NonceSize()) 32 if _, err = io.ReadFull(rand.Reader, nonce); err != nil { 33 return nil, err 34 } 35 ciphertext := gcm.Seal(nonce, nonce, data, nil) 36 return ciphertext, nil 37 } 38 39 func Decrypt(data []byte, passphrase string) ([]byte, error) { 40 key := Hash([]byte(passphrase)) 41 block, err := aes.NewCipher(key) 42 if err != nil { 43 return nil, err 44 } 45 gcm, err := cipher.NewGCM(block) 46 if err != nil { 47 return nil, err 48 } 49 nonceSize := gcm.NonceSize() 50 nonce, ciphertext := data[:nonceSize], data[nonceSize:] 51 plaintext, err := gcm.Open(nil, nonce, ciphertext, nil) 52 if err != nil { 53 return nil, err 54 } 55 return plaintext, nil 56 }