golang aes復号化、対称暗号化を実現

2170 ワード

ダイレクトコード
package main

import (
    "bytes"
    "crypto/aes"
    "crypto/cipher"
    "encoding/base64"
    "fmt"
    "strconv"
)

func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
    padding := blockSize - len(ciphertext)%blockSize
    padtext := bytes.Repeat([]byte{byte(padding)}, padding)
    return append(ciphertext, padtext...)
}

func PKCS7UnPadding(origData []byte) []byte {
    length := len(origData)
    unpadding := int(origData[length-1])
    return origData[:(length - unpadding)]
}

//AES ,CBC
func AesEncrypt(origData, key []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }
    blockSize := block.BlockSize()
    origData = PKCS7Padding(origData, blockSize)
    blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
    crypted := make([]byte, len(origData))
    blockMode.CryptBlocks(crypted, origData)
    return crypted, nil
}

//AES 
func AesDecrypt(crypted, key []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }
    blockSize := block.BlockSize()
    blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
    origData := make([]byte, len(crypted))
    blockMode.CryptBlocks(origData, crypted)
    origData = PKCS7UnPadding(origData)
    return origData, nil
}

よびだし
func main() {
    text := "123" //  
    AesKey := []byte("#HvL%$o0oNNoOZnk#o2qbqCeQB1iXeIR") //  16 

    fmt.Printf(" : %s
: %s
", text, string(AesKey)) encrypted, err := AesEncrypt([]byte(text), AesKey) if err != nil { panic(err) } fmt.Printf(" : %s
", base64.StdEncoding.EncodeToString(encrypted)) //encrypteds, _ := base64.StdEncoding.DecodeString("j4H4Tv5VcXv0oNLwB/fr+g==") origin, err := AesDecrypt(encrypted, AesKey) if err != nil { panic(err) } fmt.Printf(" : %s
", string(origin)) }

データを返します.
 : 123
 : #HvL%$o0oNNoOZnk#o2qbqCeQB1iXeIR
 : xvhqp8bT0mkEcAsNK+L4fw==
 : 123