Golang加密/ rsa问题使用PEM文件中的私钥解密文本

所以我正在为Golang中的RSA密钥构建一个基本的生成器/加密器/解密器。

我有四个主要功能。

GenKeys() 使用 rsa 生成密钥对。生成密钥,然后将此私钥写入 pem 文件。

GetKeys()从 pem 文件中获取私钥。

加密()加密手动输入到控制台中的字符串,然后吐出密文

解密()接收密文并对其进行解密,使用 GetKeys 函数从 pem 文件中获取私钥。

GenKeys 函数工作正常。加密功能工作正常。输入字符串并吐出密文。

但是当我运行解密标志时,我得到了。crypto/rsa: decryption error

试:

当我生成密钥时,私钥与从pem文件再次导入它时相同。我尝试了加密包中包含的不同解密方法。我尝试过将密文直接从加密方法导入解密,以防万一在将其吐出控制台时遇到问题。

要注意:

当我只将私钥写入内存,而不是将其吐出到文件中时,这有效,这告诉我从pem文件再次导入密钥时出现问题。但我不知道是什么。

如果有人能看一下我的代码,告诉我如果我错过了什么,我会永远感激不尽。

main.go

func main() {


    var action = flag.String("action", "", "Whether to decrypt or encrypt")

    flag.Parse()

    task := *action


    var err error


    if task == "gen" {

        //gen the priv key and write to file

        err = services.GenKeys()

        if err != nil {

            fmt.Println("Could not generate keys:", err)

        }

    }

    

    if task == "encrypt" {


        //Get key from file

        privateKey, err := services.GetKeys()

        if err != nil {

            fmt.Println("Could not retrieve key file", err)

            return

        }


        reader := bufio.NewReader(os.Stdin)

        fmt.Println("Please enter the text you would like to encrypt: ")

        text, _ := reader.ReadString('\n')


        cipherText, err := services.Encrypt(&privateKey.PublicKey, text)

        if err != nil {

            fmt.Println("Could not encrypt", err)

            return

        }


        fmt.Printf("Encrypted message: %x", cipherText)

    }


    if task == "decrypt" {


        //Get key from file

        privateKey, err := services.GetKeys()

        if err != nil {

            fmt.Println("Could not retrieve key file", err)

        }


        reader := bufio.NewReader(os.Stdin)

        fmt.Println("Please enter the cypher text you would like to decrypt: ")

        text, _ := reader.ReadString('\n')


        decryptedText, err := services.Decrypt(privateKey, []byte(text))

        if err != nil {

            fmt.Println("Could not decrypt text", err.Error())

            return

        }


        fmt.Println("decrypted text: ", string(decryptedText))

    }


}


喵喔喔
浏览 338回答 1
1回答

侃侃无极

在加密部分,密文显示为十六进制编码。如果在解密部分输入十六进制编码,则必须相应地对其进行十六进制解码,这在发布的代码中丢失。十六进制解码可以使用十六进制包完成。此外,正如彼得的评论中提到的,必须删除尾随的换行符,例如字符串。TrimSendix().或者,fmt。Scan() 或 bufio.可以使用扫描仪代替 。最后两个选项不返回尾随换行符。bufio.Reader可能的实现(为简单起见,无需异常处理):...var text stringfmt.Println("Please enter the ciphertext you would like to decrypt: ")fmt.Scan(&text)textHexDec, _ := hex.DecodeString(text) decryptedText, _ := Decrypt(privateKey, textHexDec)fmt.Println("Decrypted text: ", string(decryptedText))...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go