Created
March 24, 2017 01:59
-
-
Save shautzin/b306746041b48a8366d0f63507a4e7f3 to your computer and use it in GitHub Desktop.
AES/CBC/PKCS5Padding implementation by Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"crypto/aes" | |
"crypto/cipher" | |
"fmt" | |
) | |
func main() { | |
src := "NIJOAHS000000000" | |
key := []byte("1234567890123456") | |
fmt.Println("SOURCE!:", []byte(src)) | |
encrypted := AESEncrypt(src, key) | |
fmt.Println("ENCRYPT:", encrypted) | |
decrypted := AESDecrypt(encrypted, key) | |
fmt.Println("DECRYPT:", decrypted) | |
} | |
func AESEncrypt(src string, key []byte) []byte { | |
block, err := aes.NewCipher(key) | |
if err != nil { | |
fmt.Println("key error1", err) | |
} | |
if src == "" { | |
fmt.Println("plain content empty") | |
} | |
ecb := cipher.NewCBCEncrypter(block, []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) | |
content := []byte(src) | |
content = PKCS5Padding(content, block.BlockSize()) | |
crypted := make([]byte, len(content)) | |
ecb.CryptBlocks(crypted, content) | |
return crypted | |
} | |
func AESDecrypt(crypt []byte, key []byte) []byte { | |
block, err := aes.NewCipher(key) | |
if err != nil { | |
fmt.Println("key error1", err) | |
} | |
if len(crypt) == 0 { | |
fmt.Println("plain content empty") | |
} | |
ecb := cipher.NewCBCDecrypter(block, []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}) | |
decrypted := make([]byte, len(crypt)) | |
ecb.CryptBlocks(decrypted, crypt) | |
return PKCS5Trimming(decrypted) | |
} | |
func PKCS5Padding(ciphertext []byte, blockSize int) []byte { | |
padding := blockSize - len(ciphertext)%blockSize | |
padtext := bytes.Repeat([]byte{byte(padding)}, padding) | |
return append(ciphertext, padtext...) | |
} | |
func PKCS5Trimming(encrypt []byte) []byte { | |
padding := encrypt[len(encrypt)-1] | |
return encrypt[:len(encrypt)-int(padding)] | |
} |
Strictly speking PCKS5 always uses a blocksize of 8. What you have implemented is an attempt at PKCS7 wich takes in blocksize as parameter.
From Wikipedia about PKCS7 Padding:
f the length of the original data is an integer multiple of the block size B, then an extra block of bytes with value B is added. This is necessary so the deciphering algorithm can determine with certainty whether the last byte of the last block is a pad byte indicating the number of padding bytes added or part of the plaintext message.
if padding == 0 { padding = blockSize }
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
PKCS5Trimming has an error ; if the params did not padding will suffer an error;eg: 1111222233334444