当前位置:网站首页>Golang implements AES with five encryption mode functions, encrypt encryption and decryption string output
Golang implements AES with five encryption mode functions, encrypt encryption and decryption string output
2022-07-27 00:55:00 【One day long -- xuanbin】
/*
AES There are five encryption modes
Codebook mode (Electronic Codebook Book (ECB))、
Password group link mode (Cipher Block Chaining (CBC))、
Calculator mode (Counter (CTR))、
Password feedback mode (Cipher FeedBack (CFB))
Output feedback mode (Output FeedBack (OFB))
*/
package libs
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"encoding/hex"
"strings"
"errors"
)
/***************CBC encryption ***************************
func main() {
orig := "hello world"
key := "0123456789012345"
fmt.Println(" original text :", orig)
encryptCode := AesEncryptCBC(orig, key)
fmt.Println(" Ciphertext :" , encryptCode)
decryptCode := AesDecryptCBC(encryptCode, key)
fmt.Println(" Decryption result :", decryptCode)
}
**************************************************/
func AesEncryptCBC(orig string, key string) string {
// Convert to byte array
origData := []byte(orig)
k := []byte(key)
// Group key
// NewCipher This function limits the input k The length of must be 16, 24 perhaps 32
block, _ := aes.NewCipher(k)
// Get the length of the secret key block
blockSize := block.BlockSize()
// Complete the code
origData = PKCS7Padding(origData, blockSize)
// Encryption mode
blockMode := cipher.NewCBCEncrypter(block, k[:blockSize])
// Create array
cryted := make([]byte, len(origData))
// encryption
blockMode.CryptBlocks(cryted, origData)
return base64.StdEncoding.EncodeToString(cryted)
}
func AesDecryptCBC(cryted string, key string) string {
// Convert to byte array
crytedByte, _ := base64.StdEncoding.DecodeString(cryted)
k := []byte(key)
// Group key
block, _ := aes.NewCipher(k)
// Get the length of the secret key block
blockSize := block.BlockSize()
// Encryption mode
blockMode := cipher.NewCBCDecrypter(block, k[:blockSize])
// Create array
orig := make([]byte, len(crytedByte))
// Decrypt
blockMode.CryptBlocks(orig, crytedByte)
// To complete the code
orig = PKCS7UnPadding(orig)
return string(orig)
}
// Complement code
//AES Encrypted data block packet length must be 128bit(byte[16]), The key length can be 128bit(byte[16])、192bit(byte[24])、256bit(byte[32]) Any one of .
func PKCS7Padding(ciphertext []byte, blocksize int) []byte {
padding := blocksize - len(ciphertext)%blocksize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
// De coding
func PKCS7UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
/***************AESEncryptECBStr Encryption and decryption cases *********
func main() {
source:="asdasadgsdhfasf"
fmt.Println(" Original character :",source)
//16byte secret key
key:="sdddd"
encryptCode:=AESEncryptECBStr(source,key)
fmt.Println(" Ciphertext :",encryptCode)
decryptCode:=AESDecryptECBStr(encryptCode,key)
fmt.Println(" Decrypt :",decryptCode)
}
**************************************************/
func AESEncryptECBStr(source string, keys string) string {
// String to slice
src := []byte(source)
key := []byte(keys)
cipher, _ := aes.NewCipher(generateKeys(key))
length := (len(src) + aes.BlockSize) / aes.BlockSize
plain := make([]byte, length*aes.BlockSize)
copy(plain, src)
pad := byte(len(plain) - len(src))
for i := len(src); i < len(plain); i++ {
plain[i] = pad
}
encrypted := make([]byte, len(plain))
// Block and block encryption
for bs, be := 0, cipher.BlockSize(); bs <= len(src); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
cipher.Encrypt(encrypted[bs:be], plain[bs:be])
}
//return encrypted
encryptstr :=strings.ToUpper(hex.EncodeToString(encrypted))
return encryptstr
}
func AESDecryptECBStr(encrypteds string, keys string) string {
// String to slice
//encrypted := []byte(encrypteds)
encrypted, _ := hex.DecodeString(encrypteds)
key := []byte(keys)
cipher, _ := aes.NewCipher(generateKeys(key))
decrypted := make([]byte, len(encrypted))
//
for bs, be := 0, cipher.BlockSize(); bs < len(encrypted); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
cipher.Decrypt(decrypted[bs:be], encrypted[bs:be])
}
trim := 0
if len(decrypted) > 0 {
trim = len(decrypted) - int(decrypted[len(decrypted)-1])
}
return string(decrypted[:trim])
}
func generateKeys(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
}
// For convenience , Declare the function , Omit error handling
// Test decoding
//const testStr = "R2/or63oqIDnvJbnqIs="
//str :=mustDecode(base64.StdEncoding,testStr) // Print :R2/or63oqIDnvJbnqIs=
//fmt.Println(str)
func Base64DecodeStr(enc *base64.Encoding, str string) string {
data, err := enc.DecodeString(str)
if err != nil {
panic(err)
}
return string(data)
}
// This function tests encoding and decoding
// enc For the test Encoding object ,str For the string to be tested
//const testStr = "Go Language programming "
// test StdEncoding, Pay attention to the / by URL Special character in , Finally, there is one padding,mysql Of base64 encryption
//testEncoding(base64.StdEncoding, testStr) // Print :R2/or63oqIDnvJbnqIs=
test URLEncoding, You can see / Be replaced by _
//testEncoding(base64.URLEncoding, testStr) // Print :R2_or63oqIDnvJbnqIs=
//
test RawStdEncoding, You can see that padding
//testEncoding(base64.RawStdEncoding, testStr) // Print :R2/or63oqIDnvJbnqIs
//
test RawURLEncoding, You can see / Be replaced Wie_, And it fell padding
//testEncoding(base64.RawURLEncoding, testStr) // Print :R2_or63oqIDnvJbnqIs
func Base64EncodeStr(enc *base64.Encoding, str string) string {
// code
encStr := enc.EncodeToString([]byte(str))
// decode
decStr := Base64DecodeStr(enc, encStr)
if decStr != str { // The encoding and decoding should be the same as the original string
// If the judgment here is different , be panic
panic(errors.New("unequal!"))
}
return encStr
}
/************************** Encryption Introduction
mysql Of AES_DECRYPT Method , To use golang Implement the method , But the research found that golang Current default support CBC The way , however mysql Currently using ECB Pattern ,
SELECT HEX(AES_ENCRYPT('hello world', '1443flfsaWfdas'));
SELECT AES_DECRYPT(UNHEX('ef845a0501a6f76da2de6fba84546f8b'),'1443flfsaWfdas')
Go Linguistic string The module contains ToLower and ToUpper function , Used to convert strings to lowercase and uppercase ,mysql All return uppercase
Symmetric encryption , Encryption and decryption all use the same key , The representative is AES
Non encryption and decryption , Encryption and decryption use different keys , The representative is RSA
Signature algorithm , Such as MD5、SHA1、HMAC etc. , Mainly used to verify , Prevent information from being modified , Such as : File check 、 digital signature 、 Authentication agreement
AES: Advanced encryption standard (Advanced Encryption Standard), also called Rijndael Encryption , This standard is used to replace the original DES.
AES Encrypted data block packet length must be 128bit(byte[16]), The key length can be 128bit(byte[16])、192bit(byte[24])、256bit(byte[32]) Any one of .
block : When encrypting plaintext , First, the plaintext should be in accordance with 128bit division .
fill style : Because the length of plaintext is not always 128 Integer multiple , So we need to fill the vacancy , What we use here is PKCS7 fill style
AES There are various ways to realize , These include ECB、CBC、CFB、OFB etc.
1. Codebook mode (Electronic Codebook Book (ECB))
The result of encrypting plaintext packets is directly called ciphertext packets .
2. Password group link mode (Cipher Block Chaining (CBC))
Group plaintext with the previous ciphertext XOR operation , And then encryption . The encryption and decryption of each packet depends on the previous packet . The first group has no previous group ,
So we need an initialization vector
3. Calculator mode (Counter (CTR))
4. Password feedback mode (Cipher FeedBack (CFB))
The previous ciphertext packet will be sent back to the input of the cryptographic algorithm .
stay CBC and EBC In the pattern , Plaintext packets are encrypted by cryptographic algorithms . And in the CFB In the pattern , Plaintext packets are not encrypted directly by encryption algorithm ,
There is only one between plaintext group and ciphertext group XOR.
Encryption mode Corresponding encryption and decryption methods
CBC NewCBCDecrypter, NewCBCEncrypter
CTR NewCTR
CFB NewCFBDecrypter, NewCFBEncrypter
OFB NewOFB
***********************************/边栏推荐
- DOM day_02(7.8)网页制作流程、图片src属性、轮播图、自定义属性、标签栏、输入框事件、勾选操作、访问器语法
- Designer mode
- DOM day_04(7.12)BOM、打开新页面(延迟打开)、地址栏操作、浏览器信息读取、历史操作
- 2022.7.10DAY602
- [leetcode] no duplicate longest string
- The company gave how to use the IP address (detailed version)
- FlinkSql多表(三表) join/interval join
- Two methods of automated testing XSS vulnerabilities using burpsuite
- [watevrCTF-2019]Cookie Store
- el-checkbox中的checked勾选状态问题 2021-08-02
猜你喜欢

Neo4j基础指南(安装,节点和关系数据导入,数据查询)

Solve the problem that there is no ado.net entity data model in vs

Install redis-7.0.4 in Linux system

Golang切片make与new的区别

JSCORE day_05(7.6)
![[By Pass] 文件上传的绕过方式](/img/72/d3e46a820796a48b458cd2d0a18f8f.png)
[By Pass] 文件上传的绕过方式

DOM day_ 04 (7.12) BOM, open new page (delayed opening), address bar operation, browser information reading, historical operation

14 web vulnerability: types of SQL injection and submission injection

JSCORE day_ 04(7.5)
![[HFCTF2020]EasyLogin](/img/23/91912865a01180ee191a513be22c03.png)
[HFCTF2020]EasyLogin
随机推荐
Yolo of Darknet_ Forward of layer_ yolo_ Layer comments
MySQL8.0中的隐藏索引和降序索引(新特性)
[hongminggu CTF 2021] write_ shell
10个Web API
MySQL common functions (summary)
[RootersCTF2019]I_<3_Flask
[4.7 Gauss elimination details]
[qt] meta object system
[leetcode] no duplicate longest string
[HarekazeCTF2019]encode_ and_ encode
MYSQL 使用及实现排名函数RANK、DENSE_RANK和ROW_NUMBER
Doris或StarRocks Jmeter压测
[By Pass] 文件上传的绕过方式
flink1.11 sql本地运行demo & 本地webUI可视解决
Search engine realizes keyword highlighting
Vector size performance problems
Ah ah ah ah ah a
MySql - 如何确定一个字段适合构建索引?
14 web vulnerability: types of SQL injection and submission injection
[HITCON 2017]SSRFme