golang字符串加密

发布时间:2024-07-02 20:52:31

在现如今信息安全越来越受到重视的时代,数据加密成为了保护用户隐私的重要手段之一。而在Golang开发领域,字符串加密是一个常见的需求。本文将介绍Golang中常用的字符串加密方式,并通过实例演示其使用。

MD5加密

MD5是一种广泛使用的散列函数,可以将任意长度的数据映射成固定长度的32位字符串。在Golang中,我们可以使用crypto/md5包进行MD5加密。

import (
    "crypto/md5"
    "encoding/hex"
    "fmt"
)

func MD5Encrypt(input string) string {
    hash := md5.Sum([]byte(input))
    return hex.EncodeToString(hash[:])
}

func main() {
    input := "Hello, World!"
    encrypted := MD5Encrypt(input)
    fmt.Println("MD5 encrypted:", encrypted)
}

上述代码中,我们首先导入了crypto/md5和encoding/hex两个包,前者提供了MD5加密的功能,后者用于将加密结果转换成可读的十六进制字符串。在MD5Encrypt函数中,我们将待加密的字符串转换成字节数组,然后调用md5.Sum对其进行加密,并使用hex.EncodeToString将加密结果转换成字符串,最后返回加密后的结果。

AES加密

AES(Advanced Encryption Standard)是一种对称加密算法,可用于加密和解密数据。在Golang中,我们可以使用crypto/aes包进行AES加密。

import (
    "crypto/aes"
    "crypto/cipher"
    "encoding/base64"
    "fmt"
)

func AESEncrypt(input, key string) (string, error) {
    block, err := aes.NewCipher([]byte(key))
    if err != nil {
        return "", err
    }

    data := []byte(input)
    ciphertext := make([]byte, aes.BlockSize+len(data))
    iv := ciphertext[:aes.BlockSize]
    if _, err := rand.Read(iv); err != nil {
        return "", err
    }

    mode := cipher.NewCBCEncrypter(block, iv)
    mode.CryptBlocks(ciphertext[aes.BlockSize:], data)

    return base64.StdEncoding.EncodeToString(ciphertext), nil
}

func main() {
    input := "Hello, World!"
    key := "password12345"
    encrypted, err := AESEncrypt(input, key)
    if err != nil {
        fmt.Println("AES encryption error:", err)
        return
    }
    fmt.Println("AES encrypted:", encrypted)
}

上述代码中,我们首先导入了crypto/aes、crypto/cipher和encoding/base64三个包。在AESEncrypt函数中,我们首先通过调用aes.NewCipher创建一个AES加密块,并使用[]byte(key)将密钥转换为字节数组。接下来,我们将待加密的字符串转换成字节数组,并创建一个长度为aes.BlockSize+len(data)的字节数组ciphertext来存储加密结果。然后,我们从ciphertext中取出前aes.BlockSize个字节作为初始向量(IV),并使用rand.Read生成随机数填充其余部分。通过调用cipher.NewCBCEncrypter创建一个加密模式,并将其作用在ciphertext[aes.BlockSize:]上,最后使用base64.StdEncoding.EncodeToString将加密结果转换成可读的字符串。

RSA加密

RSA是一种非对称加密算法,可以实现数据加密和数字签名等功能。在Golang中,我们可以使用crypto/rsa包进行RSA加密。

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "encoding/base64"
    "encoding/pem"
    "fmt"
)

func RSAEncrypt(input, publicKey string) (string, error) {
    block, _ := pem.Decode([]byte(publicKey))
    if block == nil {
        return "", fmt.Errorf("failed to decode public key")
    }

    pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
    if err != nil {
        return "", err
    }
    pubKey, ok := pubInterface.(*rsa.PublicKey)
    if !ok {
        return "", fmt.Errorf("failed to parse public key")
    }

    ciphertext, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey, []byte(input))
    if err != nil {
        return "", err
    }

    return base64.StdEncoding.EncodeToString(ciphertext), nil
}

func main() {
    input := "Hello, World!"
    publicKey := `-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAwP5zvJx0MhpCM/amgoQM
uhQa1dapMpkb97yQSre579FFyF3nLBcBpv8fmB7+j7ExTo6oI+352qwZm0FMbL2J
...
zIrUyynG9qIn/A4oDBoKEqOKtxpia5fzqqLOgfhtf9BKS9u4izY=
-----END PUBLIC KEY-----`
    encrypted, err := RSAEncrypt(input, publicKey)
    if err != nil {
        fmt.Println("RSA encryption error:", err)
        return
    }
    fmt.Println("RSA encrypted:", encrypted)
}

上述代码中,我们首先导入了crypto/rand、crypto/rsa、crypto/x509、encoding/base64和encoding/pem五个包。在RSAEncrypt函数中,我们通过调用pem.Decode将公钥编码解析为PEM块。然后,我们使用x509.ParsePKIXPublicKey将PEM块的Bytes字段解析为PKIXPublicKey结构,并将其转换为*rsa.PublicKey类型。接下来,我们使用rsa.EncryptPKCS1v15对输入数据进行RSA加密,传入的参数包括随机数源、RSA公钥和待加密的数据。最后,我们使用base64.StdEncoding.EncodeToString将加密结果转换成可读的字符串。

到目前为止,我们已经介绍了在Golang中常用的字符串加密方式,包括MD5、AES和RSA加密。这些加密方式都具有不同的特点和用途,开发者应根据实际需求选择适合的加密方式。在使用加密算法时,还需要注意密钥的安全性和加密过程的性能等问题,以保证数据的安全性和系统的可靠性。

相关推荐