【问题标题】:How to use crypto/rc4如何使用加密/rc4
【发布时间】:2020-12-14 03:00:19
【问题描述】:

我正在尝试使用 RC4 加密/解密 Go 中的一些数据。我发现 Go 在 crypto/rc4 包中提供了 rc4 算法。我尝试使用包加密/解密数据,但密文和解密的明文不是我所期望的。

我与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]

【问题讨论】:

  • 谁提交了近距离投票,原因为“不可复制或由拼写错误引起”?这篇文章中描述的问题对您来说如何无法重现?你看到了什么错别字?这个问题显然是可以重现的。在这里查看:play.golang.org/p/P1Pegmo_s19。这样做的人是在对多个 Go 帖子进行此操作,这种行为对善意的 Go 初学者怀有敌意,他们在提供minimum, reproducible example 的同时来论坛寻求帮助。

标签: go encryption rc4-cipher


【解决方案1】:

您不能使用相同的 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 已被密码破解,不应用于安全应用程序。

所以使用另一种更安全的算法,例如crypto/aes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 2021-12-27
    相关资源
    最近更新 更多