In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains "how to write an AES encryption and decryption tool through Golang", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to write an AES encryption and decryption tool through Golang.
Introduction and implementation principle of AES encryption
AES (advanced encryption standard) uses the same key for encryption and decryption, that is, symmetric encryption. Other symmetric encryption, such as DES, because the length of DES key is only 56 bits, and today's computing power can even be cracked in 5 minutes, while the highest level of AES reaches 256-bit key length. If you use exhaustive method, AES is currently a kind of encryption that can not be cracked.
Where is AES used?
If you are reading this article, you are using AES (symmetric encryption is used in part of the https protocol).
Green Internet access: securely connect to another stone-throwing server through encryption.
Wireless network WIFI: used with WAP2.
Applications: wechat, JD, Alipay, etc., use AES to encrypt photos and messages or payment information.
Archiving and compression tools: 7z, WinZip and RAR.
Operating system components: some operating system components, such as file systems, use advanced encryption standards to ensure security.
Programming language libraries: Go, Python and C++ coding libraries implement AES encryption (which will be used later).
How to implement AES encryption
Reference:
What-is-the-aes-algorithm?
What is AES encryption and how does it work?
Block cipher mode of operation
From a macro point of view, the round of AES encryption (the number of rounds varies depending on the key length, as described below) is as follows:
1. Data block
First of all, the plaintext is divided into several plaintext blocks according to 128bit (yellow blocks on the picture). A byte contains 8 bits, and the layout is 4 × 4 matrix (yellow part of the picture above). The last block is filled to 128bit, and the filling method is PKCS7Padding / PKCS5Padding/ZeroPadding. No matter how to fill the final decryption, you have to remove these redundant fills.
two。 Key expansion
AES expands the key to (nasty 1) keys through Rijndael's key schedule, where n is the number of rounds to follow in the encryption process. Each standard of AES specifies the number of rounds to be encrypted. For 128bit keys, the number of rounds is 10, and the number of keys to be generated is 10. 1, a total of 11 keys.
Standard key length rounds packet length AES-128128 bits (16 bytes) 10128 bits (16 bytes) AES-192192 bits (24 bytes) 12128 bits (16 bytes) AES-256256 bits (32 bytes) 14128 bits (16 bytes)
What to do in each round includes: byte substitution (SubBytes), row shift (ShiftRows), column obfuscation (MixColumns), and round key (AddRoundKey).
3. Byte substitution (SubBytes)
At the beginning of each round, SubBytes is performed first, and bytes are replaced according to the rules specified by the predefined Rijndael S-box (which can simply be thought of as a translation table). After a conversion of each byte in a [iQuery j], we get b [iPermine j].
4. Row shift (ShiftRows)
ShiftRows the matrix obtained in the previous step, the first row remains unchanged, the second row moves 1 bit, the third row 2 bits, and the fourth row 3 bits.
5. Column confusion (MixColumns)
Then multiply each column of the matrix with the two-dimensional constant array of the patched matrix fixed matrix to get the corresponding output column.
6. Add round key (AddRoundKey)
First, the extended key Kn is arranged into a 4 × 4 matrix, and then each byte of the input array a [iMagij] is XOR with the byte k [iMaginj] corresponding to the key, and the output b [iMaginj] is obtained. Do not participate in AddRoundKey in the last round.
After 10 rounds of operations as above, we get an encrypted character of a plaintext block. Decryption is performed by reverse encryption.
AES encryption mode
ECB
In the above encryption process, each plaintext block is encrypted independently, which is simple and efficient, but if there is a related plaintext block in a segment of data, the encrypted ciphertext will be the same, which also has a certain impact on security.
CBC
The CBC encryption mode is shown in the following figure, with the initial vector IV and plaintext XOR, and the ciphertext of each block as the "vector" of the subsequent blocks, making each ciphertext unique. We'll adopt this model later.
Implementation of AES encryption tool scode by Go
Ok, which has an overview of how AES encryption works, followed by the AES encryption and decryption tool implemented through the crypto/aes and crypto/cipher packages in Go.
PKCS7Padding takes the number of bytes to be filled as bytes to be filled
/ / pkcs7Padding fills func pkcs7Padding (data [] byte, blockSize int) [] byte {/ / determines how many bits are missing. Minimum 1, maximum blockSize padding: = blockSize-len (data)% blockSize / / make-up digits. Copy padding padText from slice [] byte {byte (padding)}: = bytes.Repeat ([] byte {byte (padding)}, padding) return append (data, padText...)} / / pkcs7UnPadding remove func pkcs7UnPadding (data [] byte) ([] byte, error) {length: = len (data) if length = = 0 {return nil, errors.New ("encrypted string error!") } / / get the number of padding unPadding: = int (data [length-1]) return data [: (length- unPadding)], nil}
Encrypt and decrypt block using cipher's CBC mode
/ / AesEncrypt encryption func AesEncrypt (data [] byte, key [] byte) ([] byte, error) {/ / NewCipher creates and returns a new cipher.Block. The key argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. Block, err: = aes.NewCipher (key) if err! = nil {return nil, err} / / determine the size of fast encryption blockSize: = block.BlockSize () / / fill encryptBytes: = pkcs7Padding (data, blockSize) / / initialize encrypted data receiving slices crypted: = make ([] byte, len (encryptBytes)) / / use cbc encryption mode blockMode: = cipher.NewCBCEncrypter (block) Key [: blockSize]) / / encrypt blockMode.CryptBlocks (crypted, encryptBytes) return crypted, nil} / / AesDecrypt decrypt func AesDecrypt (data [] byte, key [] byte) ([] byte, error) {block, err: = aes.NewCipher (key) if err! = nil {return nil, err} / / get the block size blockSize: = block.BlockSize () / / use cbc blockMode: = cipher.NewCBCDecrypter (block) Key [: blockSize]) / / initialize decryption data receiving slice crypted: = make ([] byte, len (data)) / / perform decryption blockMode.CryptBlocks (crypted, data) / / to fill crypted, err = pkcs7UnPadding (crypted) if err! = nil {return nil, err} return crypted, nil}
Loop to read 100MB source data from the file for encryption to write the ciphertext to the file, decryption to read the ciphertext and decrypt the source data to write to the file.
Func EncryptFile (fileName string) (err error) {f, err: = os.Open (fileName) if err! = nil {fmt.Println ("File not found") return} defer f.Close () fInfo, _: = f.Stat () fLen: = fInfo.Size () fmt.Println ("pending file size:" FLen) maxLen: = 1024 * 1024 * 100 / / 100mb encrypt once per 100mb var forNum int64 = 0 getLen: = fLen if fLen > int64 (maxLen) {getLen = int64 (maxLen) forNum = fLen / int64 (maxLen) fmt.Println ("number of encryption required:", forNum+1)} / / encryptd to file ff, err: = os.OpenFile ("en_" + fileName, os.O_RDWR | os.O_CREATE) 0666) if err! = nil {fmt.Println ("file write error") return err} defer ff.Close () / / cyclic encryption And write to the file for I: = 0 I < int (forNum+1) Nil + {a: = make ([] byte, getLen) n, err: = f.Read (a) if err! = nil {fmt.Println ("file read error") return err} getByte Err: = EncryptByAes (a [: n]) if err! = nil {fmt.Println ("encryption error") return err} getBytes: = append ([] byte (getByte)) [] byte ("\ n").) / / write buf: = bufio.NewWriter (ff) buf.WriteString (string (getBytes [:]) buf.Flush ()} ffInfo, _: = ff.Stat () fmt.Printf ("encrypted file is:% s File size:% v Byte\ n ", ffInfo.Name (), ffInfo.Size () return nil}
Reference: Golang sample code for AES encryption and decryption
After adding a command through cobra, create an anonymous function for the command
Func (cmd * cobra.Command, args [] string) {copy (PwdKey, readPass ()) Pwd: = [] byte ("csgoogo") if ByteSliceEqual (PwdKey, Pwd) {/ / 16 bytes key PwdKey = append (PwdKey, 7,3,5,5,6,0,8) if err: = DecryptFile (args [0]) Err! = nil {panic (err)}} else {fmt.Println ("password error") os.Exit (1)}}
How to use it looks like this:
The scode tool contains two commands, encode and decode, and a password is required to decrypt the file.
#. / scode encode xpower.tar.gz pending file size: 3397 encrypted file size: en_xpower.tar.gz, file size: 4545 Byte#. / scode decode en_xpower.tar.gzENTER PASSWORD: password error #. / scode decode en_xpower.tar.gzENTER PASSWORD: file size: 4545 decrypted file: de_en_xpower.tar.gz, file size: 3159 Byte I believe you have a deeper understanding of "how to write an AES encryption and decryption tool through Golang". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.