当前位置:网站首页>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
***********************************/边栏推荐
猜你喜欢
随机推荐
[ciscn2019 finals Day2 web1]easyweb
MYSQL中的行锁升级表锁的原因
MySQL8.0中的隐藏索引和降序索引(新特性)
[b01lers2020]Welcome to Earth
Detailed explanation of CSRF forged user request attack
10个Web API
Dataframe of sparksql
[CTF攻防世界] WEB区 关于Cookie的题目
当事务遇上分布式锁
JSCORE day_ 02(7.1)
DOM day_02(7.8)网页制作流程、图片src属性、轮播图、自定义属性、标签栏、输入框事件、勾选操作、访问器语法
Crop TIF image
[HITCON 2017]SSRFme
Export and import in ES6
MySQL common functions (summary)
Essay - I say you are so cute
JSCORE day_01(6.30) RegExp 、 Function
Use of postman
js检测屏幕的方法总结 2021-10-05
Application of encoding in XSS

![[b01lers2020]Welcome to Earth](/img/e7/c8c0427b95022fbdf7bf2128c469c0.png)

![[问题]yum资源被占用怎么办](/img/8d/50129fa1b1ef0aa0e968e6e6f20969.png)



![[HarekazeCTF2019]encode_and_encode](/img/f5/c06523a1764717bdf2d91f069c9d77.png)

