Skip to content

Instantly share code, notes, and snippets.

@cannium
Forked from shautzin/AES.go
Created April 16, 2018 09:43
Show Gist options
  • Save cannium/c5262f378a1bddbaa7a5d9b40ca9de92 to your computer and use it in GitHub Desktop.
Save cannium/c5262f378a1bddbaa7a5d9b40ca9de92 to your computer and use it in GitHub Desktop.
AES/CBC/PKCS5Padding implementation by Golang
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)]
}
@VallabhaE
Copy link

will it works for files as well???

@cannium
Copy link
Author

cannium commented May 20, 2025

will it works for files as well???

why not, they are also bytes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment