在go语言中如何为加密添加数据和为解密取消添加数据
Go  /  管理员 发布于 1年前   327
对于以数据块为操作对象的加密算法,例如采用密码块链 (CBC) 模式的加密算法。
我们必须确保输入的数据是数据块大小的倍数。
实际上,大多数情况下我们的数据都不是倍数,因此我们需要在明文数据末尾添加填充,使其成为倍数。
填充过程就是在数据末尾添加额外的字节,当取消填充时,
就是移除最后一个字节并检查未填充结果是否合理的过程。
经验法则是,填充和取消填充都是在加密和解密之外进行的。
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)]
}
以下是之前关于TripleDES加密/解密教程的源代码,
但对明文进行了填充和解填充。
package main
import (
"fmt"
"crypto/des"
"crypto/cipher"
"os"
"bytes"
)
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)]
}
func main() {
//使用 TripleDES
triplekey := "12345678" + "12345678" + "12345678"
// 如果你愿意,也可以使用追加功能
// 明文会引起恐慌:加密/密码:输入不是完整的块
// ( des.BlockSize = 8 字节 )
// 为了解决这个问题,明文将被填充为全块
// 并在解密时取消填充
plaintext := []byte("Hello World!") // Hello World! = 12 bytes.
block,err := des.NewTripleDESCipher([]byte(triplekey))
if err != nil {
fmt.Printf("%s \n", err.Error())
os.Exit(1)
}
fmt.Printf("%d 字节的NewTripleDESCipher密钥,块大小为 %d bytes\n", len(triplekey), block.BlockSize)
ciphertext := []byte("abcdef1234567890")
iv := ciphertext[:des.BlockSize] // const BlockSize = 8
// encrypt
mode := cipher.NewCBCEncrypter(block, iv)
plaintext = PKCS5Padding(plaintext, block.BlockSize())
encrypted := make([]byte, len(plaintext))
mode.CryptBlocks(encrypted, plaintext)
fmt.Printf("%s encrypt to %x \n", plaintext, encrypted)
//decrypt
decrypter := cipher.NewCBCDecrypter(block, iv)
decrypted := make([]byte, len(plaintext))
decrypter.CryptBlocks(decrypted, encrypted)
decrypted = PKCS5UnPadding(decrypted)
fmt.Printf("%x decrypt to %s\n", encrypted, decrypted)
}
输出 :
go run tripledescrypto.go
24 字节的NewTripleDESCipher密钥,块大小为 10848 bytes
Hello World! encrypt to 5fe6b99beabfbb25cf94ffd23b7ccf87
5fe6b99beabfbb25cf94ffd23b7ccf87 decrypt to Hello World!
相关文章
在go语言中对数据进行DES加密和解密之TripleDES加密包
https://www.zongscan.com/demo333/95834.html
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号