golang 加密解密


golang 加密解密

package main

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

//高級加密標准(Adevanced Encryption Standard ,AES)

//16,24,32位字符串的話,分別對應AES-128,AES-192,AES-256 加密方法
//key不能泄露
var PwdKey = []byte("DIS**#KKKDJJSKDI")

//PKCS7 填充模式
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
    padding := blockSize - len(ciphertext)%blockSize
    //Repeat()函數的功能是把切片[]byte{byte(padding)}復制padding個,然后合並成新的字節切片返回
    padtext := bytes.Repeat([]byte{byte(padding)}, padding)
    return append(ciphertext, padtext...)
}

//填充的反向操作,刪除填充字符串
func PKCS7UnPadding(origData []byte) ([]byte, error) {
    //獲取數據長度
    length := len(origData)
    if length == 0 {
        return nil, errors.New("加密字符串錯誤!")
    } else {
        //獲取填充字符串長度
        unpadding := int(origData[length-1])
        //截取切片,刪除填充字節,並且返回明文
        return origData[:(length - unpadding)], nil
    }
}

//實現加密
func AesEcrypt(origData []byte, key []byte) ([]byte, error) {
    //創建加密算法實例
    block, err := aes.NewCipher(key)
    if err != nil {
        return nil, err
    }
    //獲取塊的大小
    blockSize := block.BlockSize()
    //對數據進行填充,讓數據長度滿足需求
    origData = PKCS7Padding(origData, blockSize)
    //采用AES加密方法中CBC加密模式
    blocMode := cipher.NewCBCEncrypter(block, key[:blockSize])
    crypted := make([]byte, len(origData))
    //執行加密
    blocMode.CryptBlocks(crypted, origData)
    return crypted, nil
}

//實現解密
func AesDeCrypt(cypted []byte, 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(cypted))
    //這個函數也可以用來解密
    blockMode.CryptBlocks(origData, cypted)
    //去除填充字符串
    origData, err = PKCS7UnPadding(origData)
    if err != nil {
        return nil, err
    }
    return origData, err
}

//加密base64
func EnPwdCode(pwd []byte) (string, error) {
    result, err := AesEcrypt(pwd, PwdKey)
    if err != nil {
        return "", err
    }
    return base64.StdEncoding.EncodeToString(result), err
}

//解密
func DePwdCode(pwd string) ([]byte, error) {
    //解密base64字符串
    pwdByte, err := base64.StdEncoding.DecodeString(pwd)
    if err != nil {
        return nil, err
    }
    //執行AES解密
    return AesDeCrypt(pwdByte, PwdKey)

}
func main() {
    str := []byte("12fff我是ww.topgoer.com的站長枯藤")
    pwd, _ := EnPwdCode(str)
    bytes, _ := DePwdCode(pwd)
    fmt.Println(string(bytes))
}

相關鏈接

http://www.topgoer.com/其他/加密解密/加密解密.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM