Skip to content

Instantly share code, notes, and snippets.

@yingray
Last active August 28, 2024 04:40
Show Gist options
  • Save yingray/57fdc3264b1927ef0f984b533d63abab to your computer and use it in GitHub Desktop.
Save yingray/57fdc3264b1927ef0f984b533d63abab to your computer and use it in GitHub Desktop.
Golang: aes-256-cbc examples (with iv, blockSize)
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/hex"
"fmt"
)
func main() {
key := "12345678901234567890123456789012"
iv := "1234567890123456"
plaintext := "abcdefghijklmnopqrstuvwxyzABCDEF"
fmt.Printf("Result: %v\n", Ase256(plaintext, key, iv, aes.BlockSize))
}
func Ase256(plaintext string, key string, iv string, blockSize int) string {
bKey := []byte(key)
bIV := []byte(iv)
bPlaintext := PKCS5Padding([]byte(plaintext), blockSize, len(plaintext))
block, _ := aes.NewCipher(bKey)
ciphertext := make([]byte, len(bPlaintext))
mode := cipher.NewCBCEncrypter(block, bIV)
mode.CryptBlocks(ciphertext, bPlaintext)
return hex.EncodeToString(ciphertext)
}
func PKCS5Padding(ciphertext []byte, blockSize int, after int) []byte {
padding := (blockSize - len(ciphertext)%blockSize)
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
@andyfcx
Copy link

andyfcx commented Mar 23, 2021

Nice!

@robihg
Copy link

robihg commented Apr 5, 2021

then how i can decrypt the incoming request using this function?
sorry im new in go lang

@awadhwana
Copy link

@Dj-Codeman
Copy link

Thanks !

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