所以我正在為Golang中的RSA密鑰構建一個基本的生成器/加密器/解密器。我有四個主要功能。GenKeys() 使用 rsa 生成密鑰對。生成密鑰,然后將此私鑰寫入 pem 文件。GetKeys()從 pem 文件中獲取私鑰。加密()加密手動輸入到控制臺中的字符串,然后吐出密文解密()接收密文并對其進行解密,使用 GetKeys 函數從 pem 文件中獲取私鑰。GenKeys 函數工作正常。加密功能工作正常。輸入字符串并吐出密文。但是當我運行解密標志時,我得到了。crypto/rsa: decryption error試:當我生成密鑰時,私鑰與從pem文件再次導入它時相同。我嘗試了加密包中包含的不同解密方法。我嘗試過將密文直接從加密方法導入解密,以防萬一在將其吐出控制臺時遇到問題。要注意:當我只將私鑰寫入內存,而不是將其吐出到文件中時,這有效,這告訴我從pem文件再次導入密鑰時出現問題。但我不知道是什么。如果有人能看一下我的代碼,告訴我如果我錯過了什么,我會永遠感激不盡。main.gofunc 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)) }}
1 回答

侃侃無極
TA貢獻2051條經驗 獲得超10個贊
在加密部分,密文顯示為十六進制編碼。如果在解密部分輸入十六進制編碼,則必須相應地對其進行十六進制解碼,這在發布的代碼中丟失。十六進制解碼可以使用十六進制包完成。
此外,正如彼得的評論中提到的,必須刪除尾隨的換行符,例如字符串。TrimSendix()
.或者,fmt。Scan()
或 bufio.可以使用掃描儀
代替 。最后兩個選項不返回尾隨換行符。bufio.Reader
可能的實現(為簡單起見,無需異常處理):
...
var text string
fmt.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))
...
- 1 回答
- 0 關注
- 321 瀏覽
添加回答
舉報
0/150
提交
取消