Skip to content

Instantly share code, notes, and snippets.

@secondarykey
Created November 21, 2016 00:13
Show Gist options
  • Save secondarykey/eda7af936f1cf92619e5b10fff1772c5 to your computer and use it in GitHub Desktop.
Save secondarykey/eda7af936f1cf92619e5b10fff1772c5 to your computer and use it in GitHub Desktop.
Go言語でAES256(CBC)の暗号を作る(opensslでsaltを指定した場合)
//
// 暗号的に弱いsalt方式なので、サンプルは一生でないと思いなんとなく作成しておいた
//
// echo "test" | openssl enc -e -aes-256-cbc
//
// と同じかな?
// p=パスフレーズ,d=暗号化するデータ
//
func encrypt(p, d string) (string, error) {
leng := 48
keyData := ""
hashTmp := []byte("")
salt := make([]byte, 8)
_, err := rand.Read(salt)
if err != nil {
return "", fmt.Errorf("Random read error:%s", err)
}
//EVP-BytesToKey()
for len(keyData) < leng {
hash := md5.Sum([]byte(string(hashTmp) + p + string(salt)))
hashTmp = hash[:]
keyData += string(hash[:])
}
key := keyData[0:32]
iv := keyData[32:48]
fmt.Printf("KEY[%s]\n", hex.EncodeToString([]byte(key)))
fmt.Printf("IV [%s]\n", hex.EncodeToString([]byte(iv)))
block, err := aes.NewCipher([]byte(key))
if err != nil {
return "", fmt.Errorf("Create Cipher:%s", err)
}
plain := []byte(d)
//PCKS5
plain = paddingPKCS5(plain, block.BlockSize())
cipherTxt := make([]byte, aes.BlockSize+len(plain))
mode := cipher.NewCBCEncrypter(block, []byte(iv))
mode.CryptBlocks(cipherTxt[aes.BlockSize:], plain)
salted := fmt.Sprintf("Salted__%s%s", string(salt), string(cipherTxt[16:]))
sEnc := base64.StdEncoding.EncodeToString([]byte(salted))
return sEnc, nil
}
func paddingPKCS5(src []byte, blockSize int) []byte {
padding := blockSize - len(src)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(src, padtext...)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment