Golang的crypto
包提供了加密算法的功能,包括散列、加密、签名等。以下是一些常用功能的示例代码:
- 使用
crypto/md5
进行MD5散列:
import (
"crypto/md5"
"fmt"
)
func main() {
data := []byte("hello world")
hasher := md5.New()
hasher.Write(data)
md5Sum := hasher.Sum(nil)
fmt.Println(md5Sum)
}
- 使用
crypto/sha256
进行SHA256散列:
import (
"crypto/sha256"
"fmt"
)
func main() {
data := []byte("hello world")
hash := sha256.Sum256(data)
fmt.Println(hash)
}
- 使用
crypto/rand
生成随机数:
import (
"crypto/rand"
"fmt"
"io"
)
func main() {
b := make([]byte, 16)
_, err := io.ReadFull(rand.Reader, b)
if err != nil {
fmt.Println("Error generating random bytes:", err)
return
}
fmt.Printf("%x\n", b)
}
- 使用
crypto/aes
进行AES加密和解密:
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"io"
"log"
)
func encrypt(plaintext []byte) ([]byte, error) {
key := make([]byte, 32) // AES-256 key
_, err := io.ReadFull(rand.Reader, key)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
_, err = io.ReadFull(rand.Reader, nonce)
if err != nil {
return nil, err
}
ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
return ciphertext, nil
}
func decrypt(ciphertext []byte) ([]byte, error) {
key := []byte(/* AES-256 key */)
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
if len(ciphertext) < gcm.NonceSize() {
return nil, "ciphertext too short"
}
nonce, ciphertext := ciphertext[:gcm.NonceSize()], ciphertext[gcm.NonceSize():]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}
func main() {
data := []byte("hello world")
encrypted, err := encrypt(data)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Encrypted: %x\n", encrypted)
decrypted, err := decrypt(encrypted)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Decrypted: %s\n", decrypt