当前位置:网站首页>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
边栏推荐
- Is the programmer's career really short?
- Telecommuting experience? Let's introduce ourselves ~ | community essay solicitation
- 超视频时代,什么样的技术会成为底座?
- 开机时小键盘灯不亮的解决方案
- Guide for high-end programmers to fish at work
- StoneDB 为国产数据库添砖加瓦,基于 MySQL 的一体化实时 HTAP 数据库正式开源!
- Authentication processing in interface testing framework
- Crypto Daily: Sun Yuchen proposed to solve global problems with digital technology on MC12
- 广东用电量大跌,说明高新技术产业替代高能耗产业已取得初步成果
- Where should older test / development programmers go? Will it be abandoned by the times?
猜你喜欢
2022 Moonriver global hacker song winning project list
DO280管理应用部署--pod调度控制
Programming examples of stm32f1 and stm32subeide - production melody of PWM driven buzzer
Uncover the "intelligence tax" of mousse: spend 4billion on marketing, and only 7 invention patents
Go language learning notes - Gorm use - table addition, deletion, modification and query | web framework gin (VIII)
复杂度相关OJ题(LeetCode、C语言、复杂度、消失的数字、旋转数组)
圈铁发音,动感与无噪强强出彩,魔浪HIFIair蓝牙耳机测评
There will be a gap bug when the search box and button are zoomed
【Hot100】20. 有效的括号
高端程序员上班摸鱼指南
随机推荐
【Hot100】17. 电话号码的字母组合
picgo快捷键 绝了这人和我的想法 一模一样
从大湾区“1小时生活圈”看我国智慧交通建设
圈铁发音,动感与无噪强强出彩,魔浪HIFIair蓝牙耳机测评
电脑照片尺寸如何调整成自己想要的
广东用电量大跌,说明高新技术产业替代高能耗产业已取得初步成果
数据库系统原理与应用教程(006)—— 编译安装 MySQL5.7(Linux 环境)
Is the programmer's career really short?
学会了selenium 模拟鼠标操作,你就可以偷懒点点点了
Submission lottery - light application server essay solicitation activity (may) award announcement
[daily question] 1175 Prime permutation
The picgo shortcut is amazing. This person thinks exactly the same as me
PostgreSQL 存储结构浅析
基于PHP的轻量企业销售管理系统
Summer Challenge harmonyos canvas realize clock
实现数字永生还有多久?元宇宙全息真人分身#8i
Seata中1.5.1 是否支持mysql8?
[每日一氵]Latex 的通讯作者怎么搞
idea启动Command line is too long问题处理
Thinkphp内核工单系统源码商业开源版 多用户+多客服+短信+邮件通知