如何使用crypto/rc4
How to use crypto/rc4
我正在尝试 encrypt/decrypt 使用 RC4 的 Go 中的一些数据。我发现 Go 在 crypto/rc4 包中提供了 rc4 算法。我尝试使用包 encrypt/decrypt 数据,但密文和解密的明文不是我所期望的。
我比较了类似 this 的 RC4 在线工具,但我确信 Go 的 rc4 包有一些问题。因为我用Go rc4加密明文并解密密文后解密的明文'不是我加密的。我应该找其他图书馆吗?
我运行的代码是这样的
package main
import (
"crypto/rc4"
"fmt"
"log"
)
func main() {
c, err := rc4.NewCipher([]byte("dsadsad"))
if err != nil {
log.Fatalln(err)
}
src := []byte("asdsad")
dst := make([]byte, len(src))
fmt.Println("Plaintext: ", src)
c.XORKeyStream(dst, src)
c.XORKeyStream(src, dst)
fmt.Println("Ciphertext: ", dst)
fmt.Println("Plaintext': ", src)
}
输出是这样的
Plaintext: [97 115 100 115 97 100]
Ciphertext: [98 41 227 117 93 79]
Plaintext': [111 154 128 112 250 88]
您不能使用相同的 RC4 密码加密然后解密,因为它具有内部状态。
使用相同的密钥构造一个新的密码来解密:
// ENCRYPT
c, err := rc4.NewCipher([]byte("dsadsad"))
if err != nil {
log.Fatalln(err)
}
src := []byte("asdsad")
fmt.Println("Plaintext: ", src)
dst := make([]byte, len(src))
c.XORKeyStream(dst, src)
fmt.Println("Ciphertext: ", dst)
// DECRYPT
c2, err := rc4.NewCipher([]byte("dsadsad"))
if err != nil {
log.Fatalln(err)
}
src2 := make([]byte, len(dst))
c2.XORKeyStream(src2, dst)
fmt.Println("Plaintext': ", src2)
这将输出(在 Go Playground 上尝试):
Plaintext: [97 115 100 115 97 100]
Ciphertext: [98 41 227 117 93 79]
Plaintext': [97 115 100 115 97 100]
但正如 package doc 所述:
RC4 is cryptographically broken and should not be used for secure applications.
所以使用另一种更安全的算法,例如 crypto/aes
。
我正在尝试 encrypt/decrypt 使用 RC4 的 Go 中的一些数据。我发现 Go 在 crypto/rc4 包中提供了 rc4 算法。我尝试使用包 encrypt/decrypt 数据,但密文和解密的明文不是我所期望的。
我比较了类似 this 的 RC4 在线工具,但我确信 Go 的 rc4 包有一些问题。因为我用Go rc4加密明文并解密密文后解密的明文'不是我加密的。我应该找其他图书馆吗?
我运行的代码是这样的
package main
import (
"crypto/rc4"
"fmt"
"log"
)
func main() {
c, err := rc4.NewCipher([]byte("dsadsad"))
if err != nil {
log.Fatalln(err)
}
src := []byte("asdsad")
dst := make([]byte, len(src))
fmt.Println("Plaintext: ", src)
c.XORKeyStream(dst, src)
c.XORKeyStream(src, dst)
fmt.Println("Ciphertext: ", dst)
fmt.Println("Plaintext': ", src)
}
输出是这样的
Plaintext: [97 115 100 115 97 100]
Ciphertext: [98 41 227 117 93 79]
Plaintext': [111 154 128 112 250 88]
您不能使用相同的 RC4 密码加密然后解密,因为它具有内部状态。
使用相同的密钥构造一个新的密码来解密:
// ENCRYPT
c, err := rc4.NewCipher([]byte("dsadsad"))
if err != nil {
log.Fatalln(err)
}
src := []byte("asdsad")
fmt.Println("Plaintext: ", src)
dst := make([]byte, len(src))
c.XORKeyStream(dst, src)
fmt.Println("Ciphertext: ", dst)
// DECRYPT
c2, err := rc4.NewCipher([]byte("dsadsad"))
if err != nil {
log.Fatalln(err)
}
src2 := make([]byte, len(dst))
c2.XORKeyStream(src2, dst)
fmt.Println("Plaintext': ", src2)
这将输出(在 Go Playground 上尝试):
Plaintext: [97 115 100 115 97 100]
Ciphertext: [98 41 227 117 93 79]
Plaintext': [97 115 100 115 97 100]
但正如 package doc 所述:
RC4 is cryptographically broken and should not be used for secure applications.
所以使用另一种更安全的算法,例如 crypto/aes
。