go RC4加密解密

總結:

1. RC4加密和解密公用一個函數,即 XORKeyStream()

2. 加密和解密不能用同一個Cipher對象,必須重新生成一個,否則失敗

3. XORKeyStream()的兩個參數,可以是同一個對象,即覆蓋式的加密/解密

實驗如下圖

代碼如下

package main
import (
	"crypto/rc4"
	"fmt"
)
func main() {
	// 密鑰
	key := []byte("abcdefg")
	// 要加密的源數據
	str := []byte("this is my test!")

	// 加密方式1:加密/解密後的數據單獨存放
	{
		// 加密操作
		dest1 := make([]byte, len(str))
		fmt.Printf("方法1加密前:%s \n", str)
		cipher1, _ := rc4.NewCipher(key)
		cipher1.XORKeyStream(dest1, str)
		fmt.Printf("方法1加密後:%s \n", dest1)

		// 解密操作
		dest2 := make([]byte, len(dest1))
		cipher2, _ := rc4.NewCipher(key) // 切記:這裏不能重用cipher1,必須重新生成新的
		cipher2.XORKeyStream(dest2, dest1)
		fmt.Printf("方法1解密後:%s \n\n", dest2)
	}

	// 加密方式2:加密後的數據直接存放在源數據那裏,不需額外申請空間
	{
		// 加密操作
		fmt.Printf("方法2加密前:%s \n", str)
		cipher1, _ := rc4.NewCipher(key)
		cipher1.XORKeyStream(str, str) // 加密後的數據直接覆蓋到str中
		fmt.Printf("方法2加密後:%s \n", str)

		// 解密操作
		cipher2, _ := rc4.NewCipher(key)
		cipher2.XORKeyStream(str, str) // 解密後的數據直接覆蓋到str中
		fmt.Printf("方法2解密後:%s \n\n", str)
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章