Skip to main content

crypto CFB 模式加密流

CFB(Cipher Feedback)模式是一种块密码的操作模式,它将块密码转化为一种自同步的流密码。这种模式在需要逐步处理数据的场景中非常有用,比如网络通信中的逐字节加密。

CFB 模式的工作原理

  1. 初始化向量(IV)

    • 与其他模式类似,CFB 模式需要一个初始化向量(IV),它在加密和解密过程中用作初始输入。
    • IV 的长度通常与块密码的块大小相同(例如,对于 AES,块大小是 16 字节)。
  2. 加密

    • 初始状态下,IV 被加密生成一个伪随机块。
    • 明文的第一个块与这个伪随机块进行异或操作,得到第一个密文块。
    • 然后,密文块被用作下一个输入,重复上述过程,直到所有明文块都被加密。
  3. 解密

    • 解密过程与加密过程类似,但方向相反。
    • 使用 IV 加密生成伪随机块。
    • 将密文块与伪随机块进行异或操作,得到明文块。
    • 使用密文块作为下一个输入,重复上述过程,直到所有密文块都被解密。

CFB 模式的代码示例

下面是一个使用 CFB 模式进行 AES 加密和解密的 Go 代码示例:

package main

import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
)

// 生成一个32字节的密钥(AES-256)
func generateKey(passphrase string) []byte {
hash := sha256.Sum256([]byte(passphrase))
return hash[:]
}

// AES CFB加密
func encryptCFB(plaintext, key []byte) (ciphertext []byte, err error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}

// 创建一个初始化向量(IV)
iv := make([]byte, aes.BlockSize)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}

// 使用CFB模式进行加密
stream := cipher.NewCFBEncrypter(block, iv)
ciphertext = make([]byte, len(plaintext))
stream.XORKeyStream(ciphertext, plaintext)

// 将IV附加在密文前面一起返回
return append(iv, ciphertext...), nil
}

// AES CFB解密
func decryptCFB(ciphertext, key []byte) (plaintext []byte, err error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}

// 提取IV
if len(ciphertext) < aes.BlockSize {
return nil, fmt.Errorf("ciphertext too short")
}
iv, ciphertext := ciphertext[:aes.BlockSize], ciphertext[aes.BlockSize:]

// 使用CFB模式进行解密
stream := cipher.NewCFBDecrypter(block, iv)
plaintext = make([]byte, len(ciphertext))
stream.XORKeyStream(plaintext, ciphertext)

return plaintext, nil
}

func main() {
passphrase := "my secret passphrase"
key := generateKey(passphrase)

plaintext := []byte("Hello, World!")

fmt.Printf("Original text: %s\n", plaintext)

// 加密
ciphertext, err := encryptCFB(plaintext, key)
if err != nil {
fmt.Printf("Encryption failed: %v\n", err)
return
}
fmt.Printf("Encrypted text: %s\n", hex.EncodeToString(ciphertext))

// 解密
decryptedText, err := decryptCFB(ciphertext, key)
if err != nil {
fmt.Printf("Decryption failed: %v\n", err)
return
}
fmt.Printf("Decrypted text: %s\n", decryptedText)
}

代码说明

  1. 生成密钥generateKey函数使用 SHA-256 哈希函数生成一个 32 字节的密钥。

  2. AES CFB 加密encryptCFB函数执行以下步骤:

    • 创建一个 AES 密码块。
    • 生成一个随机的初始化向量(IV)。
    • 使用 CFB 模式创建一个加密流。
    • 使用加密流对明文进行加密。
    • 将 IV 附加在密文前面一起返回。
  3. AES CFB 解密decryptCFB函数执行以下步骤:

    • 创建一个 AES 密码块。
    • 从密文中提取 IV。
    • 使用 CFB 模式创建一个解密流。
    • 使用解密流对密文进行解密,返回明文。
  4. 主函数main函数演示了如何使用上述函数进行加密和解密操作。

运行代码

将上述代码保存为一个.go文件(例如cfb_example.go),然后在终端运行以下命令:

go run cfb_example.go

你将看到加密和解密的输出结果。这个示例展示了如何使用 CFB 模式进行 AES 加密和解密,实际使用中请确保密钥和初始化向量的安全性。