当前位置:网站首页>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
边栏推荐
- Submission lottery - light application server essay solicitation activity (may) award announcement
- Guide for high-end programmers to fish at work
- 毕业后5年,我成为了年薪30w+的测试开发工程师
- Idea start command line is too long problem handling
- StoneDB 为国产数据库添砖加瓦,基于 MySQL 的一体化实时 HTAP 数据库正式开源!
- 【LeetCode】43. 字符串相乘
- Motion capture system for apple picking robot
- Microservice tracking SQL (support Gorm query tracking under isto control)
- 红队第8篇:盲猜包体对上传漏洞的艰难利用过程
- 使用腾讯云搭建图床服务
猜你喜欢

数据库系统原理与应用教程(004)—— MySQL 安装与配置:重置 MySQL 登录密码(windows 环境)

China's intelligent transportation construction from the perspective of "one hour life circle" in Dawan District

Malaysia's Star: Sun Yuchen is still adhering to the dream of digital economy in WTO MC12

MLPerf Training v2.0 榜单发布,在同等GPU配置下百度飞桨性能世界第一

Authentication processing in interface testing framework

Go language learning notes - Gorm use - table addition, deletion, modification and query | web framework gin (VIII)

Learn selenium to simulate mouse operation, and you can be lazy a little bit

【LeetCode】43. 字符串相乘
![[observation] where is the consulting going in the digital age? Thoughts and actions of softcom consulting](/img/82/3bb382893682a30e8af130365ec4ef.jpg)
[observation] where is the consulting going in the digital age? Thoughts and actions of softcom consulting
![[nodemon] app crashed - waiting for file changes before starting...解决方法](/img/ee/9830afd86e092851a2a906cb994949.png)
[nodemon] app crashed - waiting for file changes before starting...解决方法
随机推荐
开机时小键盘灯不亮的解决方案
数据库系统原理与应用教程(006)—— 编译安装 MySQL5.7(Linux 环境)
Motion capture system for apple picking robot
Embedded development: five revision control best practices
【SQL语句】请问这边为什么select出了两个上海,查询出了不同的count我想让他变成一个上海,count只显示一个总和
AVL balanced binary search tree
July 1, 2022 Daily: Google's new research: Minerva, using language models to solve quantitative reasoning problems
Pico, do you want to save or bring consumer VR?
Golang爬虫框架初探
ThinkPHP kernel work order system source code commercial open source version multi user + multi customer service + SMS + email notification
[IDM] IDM downloader installation
Is the programmer's career really short?
Origin2018安装与使用(整理中)
Five years after graduation, I became a test development engineer with an annual salary of 30w+
Where should older test / development programmers go? Will it be abandoned by the times?
Apple's self-developed baseband chip failed again, which shows Huawei Hisilicon's technological leadership
Solution to the problem that the keypad light does not light up when starting up
picgo快捷键 绝了这人和我的想法 一模一样
Win11如何设置用户权限?Win11设置用户权限的方法
vim用户自动命令示例