Skip to content

Instantly share code, notes, and snippets.

@wudi
Forked from yingray/main.go
Created January 23, 2021 15:31
Show Gist options
  • Save wudi/b1149a3ba3308c5ba4748992e7ff2aa2 to your computer and use it in GitHub Desktop.
Save wudi/b1149a3ba3308c5ba4748992e7ff2aa2 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...)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment