f
This commit is contained in:
parent
4f7804a635
commit
63446e91f1
3 changed files with 67 additions and 1 deletions
2
go.work
2
go.work
|
|
@ -2,5 +2,5 @@ go 1.23.0
|
|||
|
||||
use (
|
||||
./
|
||||
|
||||
./pkg/crypto
|
||||
)
|
||||
|
|
|
|||
3
pkg/crypto/go.mod
Normal file
3
pkg/crypto/go.mod
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
module github.com/zeevdiukman/z/crypto
|
||||
|
||||
go 1.23.0
|
||||
63
pkg/crypto/sketch.go
Normal file
63
pkg/crypto/sketch.go
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
package sketch
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
)
|
||||
|
||||
func Encrypt(plaintext string, key []byte) (string, error) {
|
||||
// Create a new AES cipher
|
||||
c, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Generate a random nonce
|
||||
nonce := make([]byte, 12)
|
||||
if _, err := rand.Read(nonce); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Create a GCM cipher
|
||||
gcm, err := cipher.NewGCM(c)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Encrypt the plaintext
|
||||
ciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
|
||||
|
||||
// Encode the ciphertext to base64
|
||||
return base64.StdEncoding.EncodeToString(ciphertext), nil
|
||||
}
|
||||
|
||||
func Decrypt(ciphertext string, key []byte) (string, error) {
|
||||
// Decode the ciphertext from base64
|
||||
ciphertextBytes, err := base64.StdEncoding.DecodeString(ciphertext)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Create a new AES cipher
|
||||
c, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Create a GCM cipher
|
||||
gcm, err := cipher.NewGCM(c)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Decrypt the ciphertext
|
||||
nonce := ciphertextBytes[:12]
|
||||
plaintext, err := gcm.Open(nil, nonce, ciphertextBytes[12:], nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(plaintext), nil
|
||||
}
|
||||
Loading…
Reference in a new issue