프로그래밍 검색 블로그

go AES 암호화 본문

go

go AES 암호화

코딩조무사 2018. 5. 22. 14:05
package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"io"
)

type AESCipher struct {
	block cipher.Block
}

func NewAesCipher(key []byte) (*AESCipher, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	return &AESCipher{block}, nil
}

func (a *AESCipher) EncryptString(s string) string {
	byteString := []byte(s)
	encryptByteArray := make([]byte, aes.BlockSize+len(s))

	iv := encryptByteArray[:aes.BlockSize]

	io.ReadFull(rand.Reader, iv)

	stream := cipher.NewCFBEncrypter(a.block, iv)
	stream.XORKeyStream(encryptByteArray[aes.BlockSize:], byteString)

	return base64.URLEncoding.EncodeToString(encryptByteArray)
}

func (a *AESCipher) DecryptString(base64String string) string {

	b, _ := base64.URLEncoding.DecodeString(base64String)
	byteString := []byte(b)

	decryptByteArray := make([]byte, len(byteString))
	iv := byteString[:aes.BlockSize]

	stream := cipher.NewCFBDecrypter(a.block, iv)
	stream.XORKeyStream(decryptByteArray, byteString[aes.BlockSize:])

	return string(decryptByteArray)
}

func main() {
	//키는 16, 24, 32만 가능합니다
	var key = []byte("the_key_hello_wo")

	a, _ := NewAesCipher(key)
	e := a.EncryptString("Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!")
	fmt.Println(e)
	d := a.DecryptString(e)

	fmt.Println(d)

}


AES 암호화 -> Base64 인코딩

디코딩

'go' 카테고리의 다른 글

go context Timeout, deadline  (0) 2018.12.22
go reflect 호출  (0) 2018.05.15
go 파일 압축  (0) 2018.05.12
Comments