golang:AES暗号解読

9792 ワード

golang:AES暗号解読コードの例:
package main

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"fmt"
)

func padding(src []byte, blocksize int) []byte {
	padnum := blocksize - len(src)%blocksize
	pad := bytes.Repeat([]byte{byte(padnum)}, padnum)
	return append(src, pad...)
}

func unPadding(src []byte) []byte {
	n := len(src)
	unPadNum := int(src[n-1])
	if unPadNum > n {
		return nil
	}
	return src[:n-unPadNum]
}

func EncryptAES(src []byte, key []byte) []byte {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil
	}
	src = padding(src, block.BlockSize())
	blockMode := cipher.NewCBCEncrypter(block, key)
	blockMode.CryptBlocks(src, src)
	return src
}

func DecryptAES(src []byte, key []byte) []byte {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil
	}
	blockMode := cipher.NewCBCDecrypter(block, key)
	blockMode.CryptBlocks(src, src)
	src = unPadding(src)
	return src
}

func main() {
	raw := []byte("guoshuaijie")
	key := []byte("huyanyan87654321")
	//key2:=[]byte("guoshuai87654321")
	encryptByte := EncryptAES(raw, key)
	if encryptByte != nil {
		decryptByte := DecryptAES(encryptByte, key)
		if decryptByte != nil {
			fmt.Println(string(decryptByte))
		}
	}
}

出力結果:
guoshuaijie