Golang Go 中的密码学
在Go语言中,你可以使用crypto
和crypto/rand
标准库来进行密码学操作。以下是一些基本的密码学操作的示例代码:
- 生成随机数:
package main
import (
"crypto/rand"
"fmt"
"io"
)
func main() {
randomNumber := make([]byte, 8) // 创建一个8字节的切片来存储随机数
_, err := io.ReadFull(rand.Reader, randomNumber) // 从加密的随机数生成器读取足够的随机数
if err != nil {
fmt.Println("Error generating random number:", err)
return
}
fmt.Printf("Random number: %x\n", randomNumber)
}
- 使用SHA256进行哈希:
package main
import (
"crypto/sha256"
"fmt"
)
func main() {
data := []byte("hello world")
hash := sha256.Sum256(data)
fmt.Printf("SHA256 hash: %x\n", hash)
}
- 使用AES-256-GCM进行加密和认证:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"io"
"log"
)
func encrypt(plaintext string) (string, error) {
key := make([]byte, 32) // AES-256的密钥长度
if _, err := io.ReadFull(rand.Reader, key); err != nil {
return "", err
}
plaintextBytes := []byte(plaintext)
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonce := make([]byte, 12) // GCM非常安全,所以使用足够长的nonce
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
ciphertext := aesgcm.Seal(nil, nonce, plaintextBytes, nil)
return base64.StdEncoding.EncodeToString(append(nonce, ciphertext...)), nil
}
func decrypt(ciphertext string) (string, error) {
ciphertextBytes, err := base64.StdEncoding.DecodeString(ciphertext)
if err != nil {
return "", err
}
key := ciphertextBytes[:len(ciphertextBytes)-12]
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonce := ciphertextBytes[len(ciphertextBytes)-12:]
plaintext, err := aesgcm.Open(nil, nonce, ciphertextBytes[len(nonce):], nil)
if err != nil {
return "", err
}
return string(plaintext), nil
}
func main() {
encrypted, err := encrypt("hello world")
if err != nil {
log.Fatal(err)
}
fmt.Println("Encrypted:", encrypted)
decrypted, err := decrypt(encrypted)
if err != nil {
log.Fatal(err)
}
fmt.Println("Decrypted:", decrypted)
}
这些例子展示了如何在Go中生成随机数、进行哈希、创建
评论已关闭