ZBLOG

golang 如何给任意长度的字符串进行加解密操作

Go语言提供了多种加解密算法,可以对任意长度的字符串进行加解密操作。

  1. 对称加密

对称加密算法使用同一个密钥进行加解密,常见的对称加密算法有AES、DES、RC4等。Go语言中提供了crypto包来实现对称加密操作。

下面是一个使用AES对称加密的例子:

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

func AESEncrypt(origData, key string) (string, error) {
    // 转换为字节数组
    keyBytes := []byte(key)
    plaintext := []byte(origData)
    // 创建AES加密算法块
    block, err := aes.NewCipher(keyBytes)
    if err != nil {
        return "", err
    }
    // 补全明文数据
    plaintext = PKCS5Padding(plaintext, block.BlockSize())
    // 创建CBC加密模式,iv需要与明文长度相同
    iv := []byte("1234567890123456")
    cipherText := make([]byte, len(plaintext))
    mode := cipher.NewCBCEncrypter(block, iv)
    mode.CryptBlocks(cipherText, plaintext)
    // 返回Base64编码的密文
    return base64.StdEncoding.EncodeToString(cipherText), nil
}

func AESDecrypt(cipherText, key string) (string, error) {
    // 转换为字节数组
    keyBytes := []byte(key)
    ciphertext, _ := base64.StdEncoding.DecodeString(cipherText)
    // 创建AES解密算法块
    block, err := aes.NewCipher(keyBytes)
    if err != nil {
        return "", err
    }
    // 创建CBC解密模式,iv需要与明文长度相同
    iv := []byte("1234567890123456")
    plaintext := make([]byte, len(ciphertext))
    mode := cipher.NewCBCDecrypter(block, iv)
    mode.CryptBlocks(plaintext, ciphertext)
    // 去除填充的数据
    plaintext = PKCS5UnPadding(plaintext)
    return string(plaintext), nil
}

func PKCS5Padding(src []byte, blockSize int) []byte {
    padding := blockSize - len(src)%blockSize
    padText := bytes.Repeat([]byte{byte(padding)}, padding)
    return append(src, padText...)
}

func PKCS5UnPadding(src []byte) []byte {
    length := len(src)
    unpadding := int(src[length-1])
    return src[:(length - unpadding)]
}
  1. 非对称加密

非对称加密算法使用公钥和私钥进行加解密,常见的非对称加密算法有RSA、ECC等。Go语言中提供了crypto/rsa包来实现非对称加密操作。

下面是一个使用RSA非对称加密的例子:

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

func RSAEncrypt(origData, publicKey string) (string, error) {
    // 解析Base64编码的公钥
    publicKeyBytes, _ := base64.StdEncoding.DecodeString(publicKey)
    block, _ := pem.Decode(publicKeyBytes)
    if block == nil {
        return "", errors.New("public key error")
    }
    pub, err := x509.ParsePKIXPublicKey(block.Bytes)
    if err != nil {
        return "", err
    }
    // 转换为RSA公钥类型
    pubKey := pub.(*rsa.PublicKey)
    // 加密明文数据
    cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey, []byte(origData))
    if err != nil {
        return "", err
    }
    // 返回Base64编码的密文
    return base64.StdEncoding.EncodeToString(cipherText), nil
}

func RSADecrypt(cipherText, privateKey string) (string, error) {
    // 解析Base64编码的私钥
    privateKeyBytes, _ := base64.StdEncoding.DecodeString(privateKey)
    block, _ := pem.Decode(privateKeyBytes)
    if block == nil {
        return "", errors.New("private key error")
    }
    pri, err := x509.ParsePKCS1PrivateKey(block.Bytes)
    if err != nil {
        return "", err
    }
    // 解密密文数据
    cipherBytes, _ := base64.StdEncoding.DecodeString(cipherText)
    plainText, err := rsa.DecryptPKCS1v15(rand.Reader, pri, cipherBytes)
    if err != nil {
        return "", err
    }
    return string(plainText), nil
}

参考文献:

https://www.liwenzhou.com/posts/Go/go_crypto/

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=1204

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?