代码拉取完成,页面将自动刷新
package fun
import "crypto/aes"
// =================== ECB(电码本模式) ======================
func AesEncryptECB(origData []byte, key []byte) (encrypted []byte, err error) {
cipherBlock, err := aes.NewCipher(generateKey(key))
if err != nil {
return nil, err
}
length := (len(origData) + aes.BlockSize) / aes.BlockSize
plain := make([]byte, length*aes.BlockSize)
copy(plain, origData)
pad := byte(len(plain) - len(origData))
for i := len(origData); i < len(plain); i++ {
plain[i] = pad
}
encrypted = make([]byte, len(plain))
// 分组分块加密
for bs, be := 0, cipherBlock.BlockSize(); bs <= len(origData); bs, be = bs+cipherBlock.BlockSize(), be+cipherBlock.BlockSize() {
cipherBlock.Encrypt(encrypted[bs:be], plain[bs:be])
}
return encrypted, nil
}
func AesDecryptECB(encrypted []byte, key []byte) (decrypted []byte, err error) {
cipherBlock, _ := aes.NewCipher(generateKey(key))
decrypted = make([]byte, len(encrypted))
//
for bs, be := 0, cipherBlock.BlockSize(); bs < len(encrypted); bs, be = bs+cipherBlock.BlockSize(), be+cipherBlock.BlockSize() {
cipherBlock.Decrypt(decrypted[bs:be], encrypted[bs:be])
}
bEnd := searchByteSliceIndex(decrypted, 0)
if bEnd == -1 {
// 如果找不到特定字节,使用切片的原始长度
bEnd = len(decrypted)
}
data := removePKCS7Padding(decrypted[:bEnd])
return data, nil
}
func generateKey(key []byte) (genKey []byte) {
genKey = make([]byte, 16)
copy(genKey, key)
for i := 16; i < len(key); {
for j := 0; j < 16 && i < len(key); j, i = j+1, i+1 {
genKey[j] ^= key[i]
}
}
return genKey
}
func removePKCS7Padding(ciphertext []byte) []byte {
padding := int(ciphertext[len(ciphertext)-1])
if padding < 1 || padding > aes.BlockSize {
padding = 0
}
for i := 0; i < padding; i++ {
if int(ciphertext[len(ciphertext)-1-i]) != padding {
padding = 0
break
}
}
if padding > 0 {
return ciphertext[:len(ciphertext)-padding]
}
return ciphertext
}
// []byte 字节切片 循环查找
func searchByteSliceIndex(bSrc []byte, b byte) int {
for i := 0; i < len(bSrc); i++ {
if bSrc[i] == b {
return i
}
}
return -1
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。