Go 언어는 AES의 CFB 모드 암호화 및 복호화를 구현합니다.

AES 소개

AES(Advanced Encryption Standard)라고도 하는 AES 암호화는 가장 일반적인 대칭 암호화 알고리즘입니다.

CFB 암호화 모드 소개

CFB 모드는 암호 피드백 모드라고도 합니다. 블록 데이터만 암호화할 수 있는 ECB 및 CBC 모드와 달리 CFB는 블록 암호문(Block Cipher)을 스트림 암호문(Stream Cipher)으로 변환할 수 있습니다.
원칙은 데이터 암호화 결과를 일반 텍스트와 XOR하여 암호문을 얻은 다음, 암호문을 암호화하고 이를 일반 텍스트와 XOR하여 다음 암호문을 얻는 식입니다.

초기화 벡터 소개

초기화 벡터(IV, 초기화 벡터)는 여러 작업 모드에서 암호화를 무작위화하는 데 사용되는 데이터입니다. 따라서 키를 재생성할 필요 없이 동일한 일반 텍스트와 동일한 키에서 서로 다른 암호문을 생성할 수 있습니다. 복잡한 과정.
초기화 벡터에는 키와 다른 보안 요구 사항이 있으므로 일반적으로 IV를 비밀로 유지할 필요가 없습니다. 그러나 대부분의 경우 동일한 IV를 동일한 키로 두 번 사용해서는 안 됩니다.
CBC 및 CFB의 경우 IV를 재사용하면 서로 다른 두 메시지의 동일한 접두사를 포함하여 일반 텍스트의 첫 번째 블록에 대한 일부 정보가 유출됩니다 . OFB 및 CTR의 경우 IV를 재사용하면 보안이 완전히 손실됩니다. 또한 CBC 모드에서는 암호화 시 IV를 예측할 수 없어야 하며, 특히 SSL2.0에서 사용되는 것과 같이 많은 구현에서 사용되는 IV를 생성하는 방법은 이전 메시지의 암호문의 마지막 블록을 다음과 같이 사용하는 것입니다. 다음 메시지의 IV는 안전하지 않습니다.

코드 예

package main

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
	"fmt"
)

//16,24,32位字符串的话,分别对应AES-128,AES-192,AES-256 加密方法
//key不能泄露
var keyStr = []byte("wobushipikaqiua.")

// 创建加密算法aes
func InitCipher() (cipher.Block, error) {
    
    
	c, err := aes.NewCipher([]byte(keyStr))
	if err != nil {
    
    
		fmt.Printf("Error: NewCipher(%d bytes) = %s", len(keyStr), err)
		return nil, err
	}
	return c, nil
}

//加密
func Encryption(commonIV []byte, plainStr string) (string, error) {
    
    
	c, err := InitCipher()
	if err != nil {
    
    
		fmt.Printf("Error: %s", err)
		return "", err
	}
	//加密字符串
	plainText := []byte(plainStr)
	cfb := cipher.NewCFBEncrypter(c, commonIV)
	cipherText := make([]byte, len(plainText))
	cfb.XORKeyStream(cipherText, plainText)
	//将[]byte转为16进制的字符串并返回
	//同:hex.EncodeToString(cipherText)
	return fmt.Sprintf("%x", cipherText), nil
}

//解密
func Decryption(commonIV []byte, cipherStr string) (string, error) {
    
    
	c, err := InitCipher()
	if err != nil {
    
    
		fmt.Printf("Error: %s", err)
		return "", err
	}
	//将十六进制的字符串解密为[]byte
	cipherText, _ := hex.DecodeString(cipherStr)
	// 解密字符串
	cfbdec := cipher.NewCFBDecrypter(c, commonIV)
	plaintextCopy := make([]byte, len(cipherText))
	cfbdec.XORKeyStream(plaintextCopy, cipherText)
	return fmt.Sprintf("%s", plaintextCopy), nil
}
func main() {
    
    
	//初始化向量
	var commonIV = []byte("2006010215040500")
	str := "测试加密"
	pwd, _ := Encryption(commonIV, str)
	fmt.Println(str + "=>加密后=>" + pwd)
	plainText, _ := Decryption(commonIV, pwd)
	fmt.Println(pwd + "=>解密后=>" + plainText)
}

실행 후 콘솔 출력

测试加密=>加密后=>d398aba7216ac9b770f83c35
d398aba7216ac9b770f83c35=>解密后=>测试加密

추천

출처blog.csdn.net/weixin_44058223/article/details/127528186