Skip to content

Instantly share code, notes, and snippets.

@daijinload
Created April 17, 2019 13:04
Show Gist options
  • Save daijinload/a3b59aeeec1ff53ae9730b7be611d0ca to your computer and use it in GitHub Desktop.
Save daijinload/a3b59aeeec1ff53ae9730b7be611d0ca to your computer and use it in GitHub Desktop.
package main
import (
"crypto/aes"
"crypto/cipher"
"encoding/hex"
"fmt"
)
func main() {
main2()
}
func main3() {
plainText := []byte("This is 16 bytes")
key := []byte("passw0rdpassw0rdpassw0rdpassw0rd")
block, err := aes.NewCipher(key)
if err != nil {
fmt.Printf("err: %s\n", err)
return
}
// Encrypt
encTxtBytes := make([]byte, len(plainText))
block.Encrypt(encTxtBytes, plainText)
//fmt.Printf("Cipher text: %x\n", cipherText)
fmt.Println(encTxtBytes)
fmt.Println(hex.EncodeToString(encTxtBytes))
fmt.Println(string(encTxtBytes))
encTxtBytes, _ = hex.DecodeString("46fa10fded0bc105a2c63365fe56f932")
// Decrypt
decryptedText := make([]byte, len(encTxtBytes))
block.Decrypt(decryptedText, encTxtBytes)
fmt.Printf("Decrypted text: %s\n", string(decryptedText))
}
func main2() {
iv := []byte("1234567890abcdef") // initialization vector
//iv, _ := hex.DecodeString("5a61e625e2036c3c8cbcc2d40b451b0e") // initialization vector
//hexEnc := enc("someplaintext", "1234567812345678", iv)
hexEnc := enc("someplaintext123456789", "1234567812345678", iv)
fmt.Println(hexEnc) //
dec(hexEnc, "1234567812345678", iv)
//dec("00000000000000000000000000000000bb1bd0be1850ed8e55bfea196f", "1234567812345678", iv)
}
func dec(hexCipherText string, skey string, iv []byte) {
bCipherText, _ := hex.DecodeString(hexCipherText)
plaintext := make([]byte, len(bCipherText)) // ここのバイト配列のサイズは大きくても大丈夫なので、暗号化後の長さを入れている。
key := []byte(skey)
fmt.Println(plaintext)
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(plaintext, bCipherText[aes.BlockSize:])
fmt.Println(plaintext)
fmt.Println(string(plaintext))
}
func enc(src string, skey string, iv []byte) string {
srcTxtBytes := []byte(src)
key := []byte(skey)
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
// init
encTxtBytes := make([]byte, aes.BlockSize+len(srcTxtBytes))
stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(encTxtBytes[aes.BlockSize:], srcTxtBytes)
fmt.Println(encTxtBytes)
fmt.Println(hex.EncodeToString(encTxtBytes))
fmt.Println(string(encTxtBytes))
return hex.EncodeToString(encTxtBytes)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment