Go语言常见加密与解密【Base编码与解码、哈希、对称与非对称、数字签名】
package main
import (
"crypto/md5"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"fmt"
)
func main() {
// Base64编码与解码
originalString := "Hello, Base64!"
encodedString := base64.StdEncoding.EncodeToString([]byte(originalString))
decodedBytes, _ := base64.StdEncoding.DecodeString(encodedString)
decodedString := string(decodedBytes)
fmt.Printf("Original: %s\nEncoded: %s\nDecoded: %s\n", originalString, encodedString, decodedString)
// 哈希函数MD5
hasher := md5.New()
hasher.Write([]byte(originalString))
md5Bytes := hasher.Sum(nil)
md5String := hex.EncodeToString(md5Bytes)
fmt.Printf("MD5: %s\n", md5String)
// 哈希函数SHA256
hasher = sha256.New()
hasher.Write([]byte(originalString))
sha256Bytes := hasher.Sum(nil)
sha256String := hex.EncodeToString(sha256Bytes)
fmt.Printf("SHA256: %s\n", sha256String)
// 对称加密(RSA加密解密)
publicKey, privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
cipherText, _ := rsa.EncryptPKCS1v15(rand.Reader, publicKey, []byte(originalString))
decryptedText, _ := rsa.DecryptPKCS1v15(rand.Reader, privateKey, cipherText)
fmt.Printf("Original: %s\nEncrypted: %x\nDecrypted: %s\n", originalString, cipherText, decryptedText)
// 非对称加密(RSA签名验证)
h := sha256.New()
h.Write([]byte(originalString))
d := h.Sum(nil)
signature, _ := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, d)
ok := rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, d, signature)
fmt.Printf("Signature Verified: %t\n", ok)
}
这段代码展示了如何在Go语言中进行Base64编码与解码、哈希函数MD5与SHA256的使用,以及如何使用RSA算法进行对称加密、非对称加密和数字签名。代码简洁,注重实用性,并处理了可能出现的错误。
评论已关闭