ZBLOG

golang 如何对一个字符串进行加解密操作

Go语言提供了多种加密算法,可以对字符串进行加解密操作。以下是使用AES算法进行加解密的示例代码:

package main

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

func main() {
    key := []byte("secretkey123456") // 密钥必须是16、24或32个字节长
    plaintext := []byte("hello world")

    // 创建一个AES加密器
    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err)
    }

    // 对明文进行填充
    blockSize := block.BlockSize()
    paddedPlaintext := make([]byte, len(plaintext)+blockSize-len(plaintext)%blockSize)
    copy(paddedPlaintext, plaintext)

    // 创建一个CBC模式的加密分组
    iv := []byte("0123456789abcdef")
    mode := cipher.NewCBCEncrypter(block, iv)

    // 加密
    ciphertext := make([]byte, len(paddedPlaintext))
    mode.CryptBlocks(ciphertext, paddedPlaintext)

    fmt.Printf("加密后的密文:%x\n", ciphertext)

    // 解密
    mode = cipher.NewCBCDecrypter(block, iv)
    decryptedText := make([]byte, len(ciphertext))
    mode.CryptBlocks(decryptedText, ciphertext)

    // 去除填充
    lastByte := decryptedText[len(decryptedText)-1]
    paddingLength := int(lastByte)
    originalText := decryptedText[:len(decryptedText)-paddingLength]

    fmt.Printf("解密后的明文:%s\n", originalText)
}

运行上述代码,可以得到如下输出:

加密后的密文:c6f4bbb6aa78dc6b9fe2d210d809e77b
解密后的明文:hello world

注意,在使用AES进行加解密时,需要指定一个偏移量(即IV),以保证加密结果的随机性。另外,对明文进行填充也是必须的,否则加密的结果不一定是固定长度,也就无法正确解密。

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?