// Package encrypt // @Link https://github.com/bufanyun/hotgo // @Copyright Copyright (c) 2023 HotGo CLI // @Author Ms <133814250@qq.com> // @License https://github.com/bufanyun/hotgo/blob/master/LICENSE package encrypt import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "fmt" "github.com/forgoer/openssl" "io" ) const AESGCMKeySize = 32 // AESGCMEncrypt encrypts plaintext with AES-256-GCM and a fresh random nonce. func AESGCMEncrypt(plaintext, key, additionalData []byte) (ciphertext, nonce []byte, err error) { if len(key) != AESGCMKeySize { return nil, nil, fmt.Errorf("AES-256-GCM key must be %d bytes", AESGCMKeySize) } block, err := aes.NewCipher(key) if err != nil { return nil, nil, err } gcm, err := cipher.NewGCM(block) if err != nil { return nil, nil, err } nonce = make([]byte, gcm.NonceSize()) if _, err = io.ReadFull(rand.Reader, nonce); err != nil { return nil, nil, err } return gcm.Seal(nil, nonce, plaintext, additionalData), nonce, nil } // AESGCMDecrypt authenticates and decrypts ciphertext encrypted by AESGCMEncrypt. func AESGCMDecrypt(ciphertext, nonce, key, additionalData []byte) ([]byte, error) { if len(key) != AESGCMKeySize { return nil, fmt.Errorf("AES-256-GCM key must be %d bytes", AESGCMKeySize) } block, err := aes.NewCipher(key) if err != nil { return nil, err } gcm, err := cipher.NewGCM(block) if err != nil { return nil, err } if len(nonce) != gcm.NonceSize() { return nil, fmt.Errorf("AES-GCM nonce must be %d bytes", gcm.NonceSize()) } return gcm.Open(nil, nonce, ciphertext, additionalData) } // AesECBEncrypt 加密 func AesECBEncrypt(src, key []byte) (dst []byte, err error) { return openssl.AesECBEncrypt(src, key, openssl.PKCS7_PADDING) } // AesECBDecrypt 解密 func AesECBDecrypt(src, key []byte) (dst []byte, err error) { return openssl.AesECBDecrypt(src, key, openssl.PKCS7_PADDING) } // MustAesECBEncryptToString // Return the encryption result directly. Panic error func MustAesECBEncryptToString(bytCipher, key string) string { dst, err := AesECBEncrypt([]byte(bytCipher), []byte(key)) if err != nil { panic(err) } return base64.StdEncoding.EncodeToString(dst) } // MustAesECBDecryptToString // Directly return decryption result, panic error func MustAesECBDecryptToString(bytCipher, key string) string { dst, err := AesECBDecrypt([]byte(bytCipher), []byte(key)) if err != nil { panic(err) } return string(dst) }