Here we only discuss the use of AES encryption algorithm, PKCS7PADDING,CBC mode mode for encryption.
Encryption Code:
Func encrypt (Planttext, key []byte) ([]byte, error) { block, err := aes. Newcipher (Key) //Select encryption Algorithm if err != nil { return nil, err } planttext = pkcs7padding ( Planttext, block. BlockSize ()) blockmodel := cipher. Newcbcencrypter (Block, key) ciphertext := make ([]byte, len (PlantText)) blockmodel.cryptblocks (Ciphertext, planttext) return ciphertext, nil}func pkcs7padding (Ciphertext []byte, blocksize int) []byte { padding := blocksize - len (ciphertext)%blocksize padtext := bytes. Repeat ([]byte{byte (padding)}, padding) return append (Ciphertext, padtext ...)}
Decrypt code:
Func decrypt (Ciphertext, key []byte) ([]byte, error) { keybytes := []byte (Key) block, err := aes. Newcipher (keybytes) //Select encryption Algorithm if err != nil { return nil, err } blockmodel := cipher. Newcbcdecrypter (block, keybytes) planttext := make ([]byte, len (ciphertext )) blockmodel.cryptblocks (Planttext, ciphertext) plantText = Pkcs7unpadding (Planttext, block. BlockSize ()) return planttext, nil}func pkcs7unpadding (Planttext []byte, blocksize int) []byte { length := len (plantText) unpadding := int (Planttext[length-1]) return planttext[:(length - unpadding)]}
OK, the code is finished, need to work immediately children's shoes, direct command+c & Command+v OK, want to toss the children's shoes then look down, we come to discuss the relevant conceptual things,
AES: Advanced Encryption Standard, also known as Rijndael encryption, is the standard used to replace the original des (encryption). AES encrypted block packet length must be 128bit (byte[16]), key length can be 128bit (byte[16]), 192bit (byte[24]), 256bit (byte[32]) Any one of the.
Block: When the plaintext is encrypted, the plaintext should be divided into 128bit first.
Fill way: Because the length of the plaintext is not always 128 of the integer times, so to complement, we are here to use the PKCS7 fill way, about PKCS7, please poke here
Mode: This, the introduction is a little complicated, please poke
AES of Golang Encryption series