-
-
Save wudi/b1149a3ba3308c5ba4748992e7ff2aa2 to your computer and use it in GitHub Desktop.
Golang: aes-256-cbc examples (with iv, blockSize)
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" | |
"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