網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
對(duì)稱加密 AES 算法
(Advanced Encryption Standard ,AES)
優(yōu)點(diǎn)
算法公開(kāi)、計(jì)算量小、加密速度快、加密效率高。
缺點(diǎn)
發(fā)送方和接收方必須商定好密鑰,然后使雙方都能保存好密鑰,密鑰管理成為雙方的負(fù)擔(dān)。
應(yīng)用場(chǎng)景
相對(duì)大一點(diǎn)的數(shù)據(jù)量或關(guān)鍵數(shù)據(jù)的加密。
加解密
package helpers import ( "bytes" "crypto/aes" "crypto/cipher" "encoding/base64" "errors" ) //加密過(guò)程: // 1、處理數(shù)據(jù),對(duì)數(shù)據(jù)進(jìn)行填充,采用PKCS7(當(dāng)密鑰長(zhǎng)度不夠時(shí),缺幾位補(bǔ)幾個(gè)幾)的方式。 // 2、對(duì)數(shù)據(jù)進(jìn)行加密,采用AES加密方法中CBC加密模式 // 3、對(duì)得到的加密數(shù)據(jù),進(jìn)行base64加密,得到字符串 // 解密過(guò)程相反 //16,24,32位字符串的話,分別對(duì)應(yīng)AES-128,AES-192,AES-256 加密方法 //key不能泄露 var PwdKey = []byte("ABCDABCDABCDABCD") //pkcs7Padding 填充 func pkcs7Padding(data []byte, blockSize int) []byte { //判斷缺少幾位長(zhǎng)度。最少1,最多 blockSize padding := blockSize - len(data)%blockSize //補(bǔ)足位數(shù)。把切片[]byte{byte(padding)}復(fù)制padding個(gè) padText := bytes.Repeat([]byte{byte(padding)}, padding) return append(data, padText...) } //pkcs7UnPadding 填充的反向操作 func pkcs7UnPadding(data []byte) ([]byte, error) { length := len(data) if length == 0 { return nil, errors.New("加密字符串錯(cuò)誤!") } //獲取填充的個(gè)數(shù) unPadding := int(data[length-1]) return data[:(length - unPadding)], nil } //AesEncrypt 加密 func AesEncrypt(data []byte, key []byte) ([]byte, error) { //創(chuàng)建加密實(shí)例 block, err := aes.NewCipher(key) if err != nil { return nil, err } //判斷加密快的大小 blockSize := block.BlockSize() //填充 encryptBytes := pkcs7Padding(data, blockSize) //初始化加密數(shù)據(jù)接收切片 crypted := make([]byte, len(encryptBytes)) //使用cbc加密模式 blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) //執(zhí)行加密 blockMode.CryptBlocks(crypted, encryptBytes) return crypted, nil } //AesDecrypt 解密 func AesDecrypt(data []byte, key []byte) ([]byte, error) { //創(chuàng)建實(shí)例 block, err := aes.NewCipher(key) if err != nil { return nil, err } //獲取塊的大小 blockSize := block.BlockSize() //使用cbc blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) //初始化解密數(shù)據(jù)接收切片 crypted := make([]byte, len(data)) //執(zhí)行解密 blockMode.CryptBlocks(crypted, data) //去除填充 crypted, err = pkcs7UnPadding(crypted) if err != nil { return nil, err } return crypted, nil } //EncryptByAes Aes加密 后 base64 再加 func EncryptByAes(data []byte) (string, error) { res, err := AesEncrypt(data, PwdKey) if err != nil { return "", err } return base64.StdEncoding.EncodeToString(res), nil } //DecryptByAes Aes 解密 func DecryptByAes(data string) ([]byte, error) { dataByte, err := base64.StdEncoding.DecodeString(data) if err != nil { return nil, err } return AesDecrypt(dataByte, PwdKey) }
使用
func testAes() { //加密 str, _ := helpers.EncryptByAes(data) //解密 str1,_:=helpers.DecryptByAes(str) //打印 fmt.Printf(" 加密:%v\n 解密:%s\n ", str,str1, ) } //測(cè)試速度 func testAesTime() { startTime := time.Now() count := 1000000 for i := 0; i < count; i++ { str, _ := helpers.EncryptByAes(data) helpers.DecryptByAes(str) } fmt.Printf("%v次 - %v", count, time.Since(startTime)) }
文件加密解密
// 更新 文件 的加解密 //EncryptFile 文件加密,filePath 需要加密的文件路徑 ,fName加密后文件名 func EncryptFile(filePath, fName string) (err error) { f, err := os.Open(filePath) if err != nil { fmt.Println("未找到文件") return } defer f.Close() fInfo, _ := f.Stat() fLen := fInfo.Size() fmt.Println("待處理文件大小:", fLen) maxLen := 1024 * 1024 * 100 //100mb 每 100mb 進(jìn)行加密一次 var forNum int64 = 0 getLen := fLen if fLen > int64(maxLen) { getLen = int64(maxLen) forNum = fLen / int64(maxLen) fmt.Println("需要加密次數(shù):", forNum+1) } //加密后存儲(chǔ)的文件 ff, err := os.OpenFile("encryptFile_"+fName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { fmt.Println("文件寫入錯(cuò)誤") return err } defer ff.Close() //循環(huán)加密,并寫入文件 for i := 0; i < int(forNum+1); i++ { a := make([]byte, getLen) n, err := f.Read(a) if err != nil { fmt.Println("文件讀取錯(cuò)誤") return err } getByte, err := EncryptByAes(a[:n]) if err != nil { fmt.Println("加密錯(cuò)誤") return err } //換行處理,有點(diǎn)亂了,想到更好的再改 getBytes := append([]byte(getByte), []byte("\n")...) //寫入 buf := bufio.NewWriter(ff) buf.WriteString(string(getBytes[:])) buf.Flush() } ffInfo, _ := ff.Stat() fmt.Printf("文件加密成功,生成文件名為:%s,文件大小為:%v Byte \n", ffInfo.Name(), ffInfo.Size()) return nil } //DecryptFile 文件解密 func DecryptFile(filePath, fName string) (err error) { f, err := os.Open(filePath) if err != nil { fmt.Println("未找到文件") return } defer f.Close() fInfo, _ := f.Stat() fmt.Println("待處理文件大小:", fInfo.Size()) br := bufio.NewReader(f) ff, err := os.OpenFile("decryptFile_"+fName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if err != nil { fmt.Println("文件寫入錯(cuò)誤") return err } defer ff.Close() num := 0 //逐行讀取密文,進(jìn)行解密,寫入文件 for { num = num + 1 a, err := br.ReadString('\n') if err != nil { break } getByte, err := DecryptByAes(a) if err != nil { fmt.Println("解密錯(cuò)誤") return err } buf := bufio.NewWriter(ff) buf.Write(getByte) buf.Flush() } fmt.Println("解密次數(shù):", num) ffInfo, _ := ff.Stat() fmt.Printf("文件解密成功,生成文件名為:%s,文件大小為:%v Byte \n", ffInfo.Name(), ffInfo.Size()) return }
文件加解密使用,放到main函數(shù)中。
startTime := time.Now() //helpers.EncryptFile("qtest.txt","test") helpers.DecryptFile("encryptFile_test","qtest.txt") fmt.Printf("耗時(shí):%v", time.Since(startTime))
說(shuō)明
我自己測(cè)試文件加解密時(shí)用的4g單文件,耗時(shí)如下
待處理文件大小: 4208311808
需要加密次數(shù): 41
文件加密成功,生成文件名為:encryptFile_test,文件大小為:5611083381
耗時(shí):20.484283978s
待處理文件大小: 5611083381
解密次數(shù): 42
文件解密成功,生成文件名為:decryptFile_qtest.txt,文件大小為:4208311808 Byte
耗時(shí):15.085721748s
關(guān)于超大文本的加解密,有兩個(gè)思路
1.單行超大文本
加密:分片去讀,加密后字符串寫入文件中,每次加密寫入一行,一定要換行,不然解密的時(shí)候區(qū)分不出來(lái)。
2.非單行
加密:可以逐行加密。密文也是逐行寫入文本中。
3.解密:逐行讀取解密文件,每一行為一個(gè)密文字串,將其解密,寫入到文本中。
原文鏈接:https://www.jianshu.com/p/0caab60fea9f
相關(guān)推薦
- 2022-04-12 【debug】TypeError: mel() takes 0 positional argumen
- 2022-10-31 Python3中的算術(shù)運(yùn)算符詳解_python
- 2022-03-14 @ConfigurationProperties獲取參數(shù)值
- 2022-06-18 Android自定義彈框Dialog效果_Android
- 2022-08-19 python查看自己安裝的所有庫(kù)并導(dǎo)出的命令_python
- 2022-09-24 pandas刪除某行或某列數(shù)據(jù)的實(shí)現(xiàn)示例_python
- 2022-04-18 python?如何讀取列表中字典的value值_python
- 2022-06-23 android中的adb命令學(xué)習(xí)_Android
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支