当前位置:网站首页>How does go use symmetric encryption?
How does go use symmetric encryption?
2022-07-01 16:21:00 【frank.】
Hello everyone , I am a frank.
01
Introduce
In project development , We often encounter scenarios that require symmetric key encryption , For example, when the client calls the interface , The parameter contains the mobile number 、 ID number or bank card number, etc .
Symmetric key encryption is an encryption method , There is only one key for encrypting and decrypting data . Entities communicating through symmetric encryption must share this key , So that it can be used during decryption . This encryption method is different from asymmetric encryption , Asymmetric encryption uses a pair of keys ( A public key and a private key ) To encrypt and decrypt data .
02
AES Algorithm
Common symmetric key encryption algorithms are AES (Advanced Encryption Standard),DES (Data Encryption Standard) etc. , They all belong to block cipher .
Because based on the processing power of the current computer , Can be quickly cracked DES Algorithm , therefore DES It is rarely used nowadays .
AES Is the most commonly used symmetric key encryption algorithm , Originally known as Rijndael.AES The size of each password packet is 128 bits, But it has three key lengths , Namely AES-128、AES-192 and AES-256. It should be noted that , stay Golang The interface provided by the standard library , Support only AES-128(16 byte), actually AES-128 The encryption strength of is secure enough .
In this paper, we mainly introduce Golang How to use AES Symmetric key encryption algorithm .
03
practice
AES The grouping mode of the algorithm includes ECB、CBC、CFB、OFB and CTR, among ECB and CBC Use more , although ECB Than CBC Simple , Efficient , But its ciphertext is regular , Easy to crack , therefore , It is recommended that you use CBC, In this article, we mainly introduce the most used CBC Group mode .
It should be noted that ,ECB and CBC The last grouping in the grouping mode , Need to fill up 16 byte, About fill mode , Limited to space , This article does not introduce , But it will provide code for populating data and de populating data .
Golang Realization AES Symmetric encryption algorithm is mainly divided into the following steps :
Encryption steps :
- Create a new encrypted block .
- Get the size of the encrypted block .
- Fill in the data .
- Initialization vector .
- Specifies the grouping mode of the encrypted block .
- Encrypts multiple blocks .
Sample code :
func AESCbcEncrypt(secretKey, src string) string {
key := []byte(secretKey)
if len(key) > 16 {
key = key[:16]
}
plaintext := []byte(src)
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
blockSize := block.BlockSize()
plaintext = Padding(plaintext, blockSize)
if len(plaintext)%aes.BlockSize != 0 {
panic("plaintext is not a multiple of the block size")
}
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
panic(err)
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
return base64.StdEncoding.EncodeToString(ciphertext)
}
Decryption steps :
- Create a new encrypted block .
- Initialization vector .
- Specifies the grouping mode of the decrypted block .
- Decrypt multiple blocks .
- Unpin data .
Sample code :
func AESCbcDecrypt(secretKey, src string) string {
key := []byte(secretKey)
ciphertext, _ := base64.StdEncoding.DecodeString(src)
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
if len(ciphertext) < aes.BlockSize {
panic("ciphertext too short")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
if len(ciphertext)%aes.BlockSize != 0 {
panic("ciphertext is not a multiple of the block size")
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
ciphertext = UnPadding(ciphertext)
return string(ciphertext)
}
Fill in the sample code :
func Padding(plainText []byte, blockSize int) []byte {
padding := blockSize - len(plainText)%blockSize
char := []byte{byte(padding)}
newPlain := bytes.Repeat(char, padding)
return append(plainText, newPlain...)
}
Unfill sample code :
func UnPadding(plainText []byte) []byte {
length := len(plainText)
lastChar := plainText[length-1]
padding := int(lastChar)
return plainText[:length-padding]
}
It should be noted that , Initialization vector (IV) Is random , Careful readers may have found , Use random IV , The same document , The ciphertext obtained by each encryption is also different . however , Used for encryption and decryption IV It has to be the same .
04
summary
In this paper, we introduce the concept of symmetric key encryption , And briefly introduced AES Algorithm , Finally, we also provided Golang How do you use it? AES Algorithm CBC Group mode to achieve symmetric key encryption example code , Interested readers and friends , You can write your own code for other grouping modes .
This article focuses on how to use Go Language to achieve symmetric key encryption , The code takes up a lot of space , About AES The grouping mode and filling mode of the algorithm are introduced in detail , Interested readers can read the link address given in the reference .
Reference material :
- https://en.wikipedia.org/wiki/Symmetric-key_algorithm
- https://pkg.go.dev/crypto/[email protected]#NewCipher
- https://pkg.go.dev/crypto/cipher#NewCBCEncrypter
- https://pkg.go.dev/crypto/cipher#NewCBCDecrypter
- https://datatracker.ietf.org/doc/html/rfc5246#section-6.2.3.2
- https://en.wikipedia.org/wiki/Padding_(cryptography)
- https://www.cryptomathic.com/news-events/blog/the-use-of-encryption-modes-with-symmetric-block-ciphers
边栏推荐
- 数据库系统原理与应用教程(006)—— 编译安装 MySQL5.7(Linux 环境)
- Smart Party Building: faith through time and space | 7.1 dedication
- Apple's self-developed baseband chip failed again, which shows Huawei Hisilicon's technological leadership
- Stonedb is building blocks for domestic databases, and the integrated real-time HTAP database based on MySQL is officially open source!
- 超视频时代,什么样的技术会成为底座?
- UML旅游管理系统「建议收藏」
- Comprehensively view the value of enterprise digital transformation
- Where should older test / development programmers go? Will it be abandoned by the times?
- Problems encountered in IM instant messaging development to maintain heartbeat
- Go language learning notes - Gorm use - table addition, deletion, modification and query | web framework gin (VIII)
猜你喜欢
2023 spring recruitment Internship - personal interview process and face-to-face experience sharing
Principle of motion capture system
Summer Challenge harmonyos canvas realize clock
【Hot100】20. 有效的括号
搜索框和按钮缩放时会有缝隙的bug
Tutorial on principles and applications of database system (004) -- MySQL installation and configuration: resetting MySQL login password (Windows Environment)
电脑照片尺寸如何调整成自己想要的
2023届春招实习-个人面试过程和面经分享
Analysis of PostgreSQL storage structure
[observation] where is the consulting going in the digital age? Thoughts and actions of softcom consulting
随机推荐
Nuxt.js数据预取
Stonedb is building blocks for domestic databases, and the integrated real-time HTAP database based on MySQL is officially open source!
如何使用phpIPAM来管理IP地址和子网
【Hot100】20. Valid parentheses
周少剑,很少见
虚拟串口模拟器和串口调试助手使用教程「建议收藏」
瑞典公布决定排除华为5G设备,但是华为已成功找到新出路
数据库系统原理与应用教程(006)—— 编译安装 MySQL5.7(Linux 环境)
Win11如何設置用戶權限?Win11設置用戶權限的方法
There is a difference between u-standard contract and currency standard contract. Will u-standard contract explode
接口测试框架中的鉴权处理
Huawei issued hcsp-solution-5g security talent certification to help build 5g security talent ecosystem
程序员职业生涯真的很短吗?
Principle of motion capture system
动作捕捉系统用于苹果采摘机器人
部门来了个拿25k出来的00后测试卷王,老油条表示真干不过,已被...
运动捕捉系统原理
laravel的模型删除后动作
Introduction to RT thread env tool (learning notes)
【IDM】IDM下载器安装