test.sql在当前目录下 package main import ( "bytes" "crypto/cipher" "crypto/aes" // "encoding/base64" "fmt" "os" "io/ioutil" ) func main() { //data dataFile:= "test.sql" file,err:=os.Open(dataFile) if err!=nil{ fmt.Println("未找到文件") os.Exit(0) } defer file.Close() plain,_:=ioutil.ReadAll(file) //key // keyFile:= "encrypt.key" // tmpKey,err:=os.Open(keyFile) // if err!=nil{ //     fmt.Println("未找到key") //     os.Exit(0) // } // defer tmpKey.Close() // key,_:=ioutil.ReadAll(tmpKey) key := "MC0CAQACBQC6x579MC0CAQACBQC6x578" byteKey := []byte(key) block, err := aes.NewCipher(byteKey) fmt.Println(block.BlockSize()) return testAes(plain, byteKey) } func testAes(plain []byte, key []byte) { // AES-128。key长度:16, 24, 32 bytes 对应 AES-128, AES-192, AES-256 result, err := AesEncrypt([]byte(plain), key) if err != nil { panic(err) } fileName := "加密后的文件.sql" saveErr := ioutil.WriteFile(fileName,result,0777) if saveErr != nil{ fmt.Println("保存加密后文件失败!") }else{ fmt.Println("保存加密后文件成功!") } // fmt.Println(base64.StdEncoding.EncodeToString(result)) origData, err := AesDecrypt(result, key) if err != nil { panic(err) } DecryptName := "解密后.sql" saveDeErr := ioutil.WriteFile(DecryptName,origData,0777) if saveDeErr != nil{ fmt.Println("保存解密后文件失败!") }else{ fmt.Println("保存解密后文件成功!") } // fmt.Println(string(origData)) } func AesEncrypt(origData, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } blockSize := block.BlockSize() origData = PKCS5Padding(origData, blockSize) // origData = ZeroPadding(origData, block.BlockSize()) blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) crypted := make([]byte, len(origData)) // 根据CryptBlocks方法的说明,如下方式初始化crypted也可以 // crypted := origData blockMode.CryptBlocks(crypted, origData) return crypted, nil } 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)) // origData := crypted blockMode.CryptBlocks(origData, crypted) origData = PKCS5UnPadding(origData) // origData = ZeroUnPadding(origData) return origData, nil } func ZeroPadding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize padtext := bytes.Repeat([]byte{0}, padding) return append(ciphertext, padtext...) } func ZeroUnPadding(origData []byte) []byte { length := len(origData) unpadding := int(origData[length-1]) return origData[:(length - unpadding)] } func PKCS5Padding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padtext...) } func PKCS5UnPadding(origData []byte) []byte { length := len(origData) // 去掉最后一个字节 unpadding 次 unpadding := int(origData[length-1]) return origData[:(length - unpadding)] }

分类: web

标签: