Golang : Padding data for encryption and un-padding data for decryption
Continuing from our last tutorial on TripleDES encryption. We purposely left out the padding/un-padding functions to keep the tutorial as simple as possible for reader to understand. In this tutorial we will elaborate more on the need for padding the input plaintext data before encryption.
For crypto algorithms that operate on blocks of data such as those in cipher-block chaining (CBC) mode. We have to make sure that the data passed in is a multiple of our block size. In reality, most of the time our data won't be and we need to add padding to the end of our plaintext data to make it a multiple. Padding process is to add extra bytes to the end of the data and when un-pad, is the process of removing the last byte and check to see if the un-padded result make sense.
The rule of thumb is that, padding and un-padding take place outside of encryption and decryption.
func PKCS5Padding(src []byte, blockSize int) []byte {
padding := blockSize - len(src)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, padtext...)
}
func PKCS5UnPadding(src []byte) []byte {
length := len(src)
unpadding := int(src[length-1])
return src[:(length - unpadding)]
}
Below is the source code from previous tutorial on TripleDES encryption/decryption but with padding and un-padding of the plaintext.
package main
import (
"fmt"
"crypto/des"
"crypto/cipher"
"os"
"bytes"
)
func PKCS5Padding(src []byte, blockSize int) []byte {
padding := blockSize - len(src)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, padtext...)
}
func PKCS5UnPadding(src []byte) []byte {
length := len(src)
unpadding := int(src[length-1])
return src[:(length - unpadding)]
}
func main() {
// because we are going to use TripleDES... therefore we Triple it!
triplekey := "12345678" + "12345678" + "12345678"
// you can use append as well if you want
// plaintext will cause panic: crypto/cipher: input not full blocks
// IF it is not the correct BlockSize. ( des.BlockSize = 8 bytes )
// to fix this issue, plaintext will be padded to full blocks
// and unpadded upon decryption
plaintext := []byte("Hello World!") // Hello World! = 12 bytes.
block,err := des.NewTripleDESCipher([]byte(triplekey))
if err != nil {
fmt.Printf("%s \n", err.Error())
os.Exit(1)
}
fmt.Printf("%d bytes NewTripleDESCipher key with block size of %d bytes\n", len(triplekey), block.BlockSize)
ciphertext := []byte("abcdef1234567890")
iv := ciphertext[:des.BlockSize] // const BlockSize = 8
// encrypt
mode := cipher.NewCBCEncrypter(block, iv)
plaintext = PKCS5Padding(plaintext, block.BlockSize())
encrypted := make([]byte, len(plaintext))
mode.CryptBlocks(encrypted, plaintext)
fmt.Printf("%s encrypt to %x \n", plaintext, encrypted)
//decrypt
decrypter := cipher.NewCBCDecrypter(block, iv)
decrypted := make([]byte, len(plaintext))
decrypter.CryptBlocks(decrypted, encrypted)
decrypted = PKCS5UnPadding(decrypted)
fmt.Printf("%x decrypt to %s\n", encrypted, decrypted)
}
Output :
go run tripledescrypto.go
24 bytes NewTripleDESCipher key with block size of 10848 bytes
Hello World! encrypt to 5fe6b99beabfbb25cf94ffd23b7ccf87
5fe6b99beabfbb25cf94ffd23b7ccf87 decrypt to Hello World!
Reference :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+12.9k Facebook PHP getUser() returns 0
+4.7k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+12.1k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+13.2k Golang : Get dimension(width and height) of image file
+6.8k Golang : Null and nil value
+10.5k Golang : Natural string sorting example
+27.6k Golang : Connect to database (MySQL/MariaDB) server
+5k Golang : If else example and common mistake
+7k Golang : How to convert strange string to JSON with json.MarshalIndent
+6.4k Nginx : Password protect a directory/folder