当前位置:网站首页>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
边栏推荐
- 【Hot100】17. Letter combination of telephone number
- I'm a senior test engineer who has been outsourced by Alibaba and now has an annual salary of 40w+. My two-year career changing experience is sad
- 普通二本,去过阿里外包,到现在年薪40W+的高级测试工程师,我的两年转行心酸经历...
- 分享在大疆DJI(深圳总部)工作的日常和福利
- 投稿开奖丨轻量应用服务器征文活动(5月)奖励公布
- 數據庫系統原理與應用教程(006)—— 編譯安裝 MySQL5.7(Linux 環境)
- [daily news]what happened to the corresponding author of latex
- When ABAP screen switching, refresh the previous screen
- 【Hot100】17. 电话号码的字母组合
- Origin2018安装与使用(整理中)
猜你喜欢
AVL balanced binary search tree
从大湾区“1小时生活圈”看我国智慧交通建设
制造业数字化转型究竟是什么
[SQL statement] Why do you select two Shanghai and query different counts here? I want it to become a Shanghai, and count only displays a sum
数据库系统原理与应用教程(006)—— 编译安装 MySQL5.7(Linux 环境)
Im instant messaging develops a message delivery scheme for 10000 people
嵌入式开发:5个修订控制最佳实践
Is the programmer's career really short?
揭秘慕思“智商税”:狂砸40亿搞营销,发明专利仅7项
PostgreSQL 存储结构浅析
随机推荐
Nuxt.js数据预取
Win11如何設置用戶權限?Win11設置用戶權限的方法
运动捕捉系统原理
嵌入式开发:5个修订控制最佳实践
开机时小键盘灯不亮的解决方案
【Hot100】20. Valid parentheses
數據庫系統原理與應用教程(006)—— 編譯安裝 MySQL5.7(Linux 環境)
The sharp drop in electricity consumption in Guangdong shows that the substitution of high-tech industries for high-energy consumption industries has achieved preliminary results
picgo快捷键 绝了这人和我的想法 一模一样
Go language learning notes - Gorm use - table addition, deletion, modification and query | web framework gin (VIII)
Do280 management application deployment - pod scheduling control
复杂度相关OJ题(LeetCode、C语言、复杂度、消失的数字、旋转数组)
分享在大疆DJI(深圳总部)工作的日常和福利
Comment utiliser le langage MySQL pour les appareils de ligne et de ligne?
DO280管理应用部署--pod调度控制
Korean AI team plagiarizes shock academia! One tutor with 51 students, or plagiarism recidivist
Im instant messaging develops a message delivery scheme for 10000 people
PostgreSQL 存储结构浅析
Crypto Daily: Sun Yuchen proposed to solve global problems with digital technology on MC12
Pico, do you want to save or bring consumer VR?