Go语言常用加密算法和加密技术全面解析!
在现代计算机领域,安全性非常重要,而加密技术是保证计算机信息系统安全性的重要措施之一。为了满足这个需求,Go语言提供了丰富的加密算法和加密技术,本文将为大家详细解析Go语言中常用的加密算法和加密技术。
一、对称加密算法
对称加密算法是加密和解密使用相同的密钥的一种加密方式。常用的对称加密算法有DES、3DES、AES等。Go语言中的crypto包中提供了多种对称加密算法。
以下是一个示例,使用AES加密算法加密字符串,然后再进行解密:
```go
package main
import (
"crypto/aes"
"crypto/cipher"
"fmt"
)
func AesEncrypt(plainText, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
iv := []byte("1234567890123456")
plainText = pkcs5Padding(plainText, block.BlockSize())
blockMode := cipher.NewCBCEncrypter(block, iv)
cipherText := make([]byte, len(plainText))
blockMode.CryptBlocks(cipherText, plainText)
return cipherText, nil
}
func AesDecrypt(cipherText, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
iv := []byte("1234567890123456")
blockMode := cipher.NewCBCDecrypter(block, iv)
plainText := make([]byte, len(cipherText))
blockMode.CryptBlocks(plainText, cipherText)
plainText = pkcs5UnPadding(plainText)
return plainText, nil
}
func pkcs5Padding(cipherText []byte, blockSize int) []byte {
padding := blockSize - len(cipherText)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(cipherText, padText...)
}
func pkcs5UnPadding(plainText []byte) []byte {
length := len(plainText)
unPadding := int(plainText[length-1])
return plainText[:(length - unPadding)]
}
func main() {
plainText := []byte("Hello World")
key := []byte("12345678901234567890123456789012")
cipherText, err := AesEncrypt(plainText, key)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Cipher Text: %x\n", cipherText)
plainTextResult, err := AesDecrypt(cipherText, key)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Plain Text: %s\n", plainTextResult)
}
```
二、非对称加密算法
非对称加密算法也称为公钥加密算法,加密和解密使用不同的密钥。常用的非对称加密算法有RSA、ECC等。Go语言中的crypto包中也提供了多种非对称加密算法。
以下是一个示例,使用RSA加密算法加密字符串,然后再进行解密:
```go
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
)
func RsaEncrypt(plainText []byte, publicKey []byte) ([]byte, error) {
block, _ := pem.Decode(publicKey)
if block == nil {
return nil, fmt.Errorf("public key pem decode failed")
}
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
pub := pubInterface.(*rsa.PublicKey)
cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, pub, plainText)
if err != nil {
return nil, err
}
return cipherText, nil
}
func RsaDecrypt(cipherText []byte, privateKey []byte) ([]byte, error) {
block, _ := pem.Decode(privateKey)
if block == nil {
return nil, fmt.Errorf("private key pem decode failed")
}
pri, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
priKey := pri.(*rsa.PrivateKey)
plainText, err := rsa.DecryptPKCS1v15(rand.Reader, priKey, cipherText)
if err != nil {
return nil, err
}
return plainText, nil
}
func main() {
plainText := []byte("Hello World")
publicKey, privateKey := GenerateRsaKeyPair(2048)
cipherText, err := RsaEncrypt(plainText, publicKey)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Cipher Text: %x\n", cipherText)
plainTextResult, err := RsaDecrypt(cipherText, privateKey)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Plain Text: %s\n", plainTextResult)
}
func GenerateRsaKeyPair(bitsize int) ([]byte, []byte) {
priKey, err := rsa.GenerateKey(rand.Reader, bitsize)
if err != nil {
return nil, nil
}
priDER := x509.MarshalPKCS1PrivateKey(priKey)
priPEM := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: priDER,
})
publicKey := priKey.PublicKey
pubDER, err := x509.MarshalPKIXPublicKey(&publicKey)
if err != nil {
return nil, nil
}
pubPEM := pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
Bytes: pubDER,
})
return pubPEM, priPEM
}
```
三、哈希算法
哈希算法将任意长度的消息压缩到固定长度的摘要中。常用的哈希算法有SHA-1、SHA-256、MD5等。Go语言中的crypto包中也提供了多种哈希算法。
以下是一个示例,使用SHA-256算法计算字符串的哈希值:
```go
package main
import (
"crypto/sha256"
"fmt"
)
func ComputeSha256Hash(data []byte) []byte {
h := sha256.New()
h.Write(data)
return h.Sum(nil)
}
func main() {
data := []byte("Hello World")
hash := ComputeSha256Hash(data)
fmt.Printf("SHA-256 Hash: %x\n", hash)
}
```
四、数字签名
数字签名是一种基于公钥密码学的技术,用来保证消息的完整性、真实性和不可否认性。常用的数字签名算法有RSA、ECC等。Go语言中的crypto包中也提供了多种数字签名算法。
以下是一个示例,使用RSA算法对数据进行数字签名,然后再进行验证:
```go
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/pem"
"fmt"
)
func RsaSign(data []byte, privateKey []byte) ([]byte, error) {
block, _ := pem.Decode(privateKey)
if block == nil {
return nil, fmt.Errorf("private key pem decode failed")
}
pri, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
priKey := pri.(*rsa.PrivateKey)
h := sha256.New()
h.Write(data)
hash := h.Sum(nil)
signature, err := rsa.SignPKCS1v15(rand.Reader, priKey, crypto.SHA256, hash)
if err != nil {
return nil, err
}
return signature, nil
}
func RsaVerify(data, signature, publicKey []byte) (bool, error) {
block, _ := pem.Decode(publicKey)
if block == nil {
return false, fmt.Errorf("public key pem decode failed")
}
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return false, err
}
pub := pubInterface.(*rsa.PublicKey)
h := sha256.New()
h.Write(data)
hash := h.Sum(nil)
err = rsa.VerifyPKCS1v15(pub, crypto.SHA256, hash, signature)
if err != nil {
return false, err
}
return true, nil
}
func main() {
data := []byte("Hello World")
publicKey, privateKey := GenerateRsaKeyPair(2048)
signature, err := RsaSign(data, privateKey)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Signature: %x\n", signature)
ok, err := RsaVerify(data, signature, publicKey)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Verify Result: %t\n", ok)
}
```
总结:
上述代码示例了Go语言中常用的加密算法和加密技术,包括对称加密算法、非对称加密算法、哈希算法和数字签名。这些技术在实际应用中非常有用,能够帮助开发人员保证系统的安全性。