我需要使用公鑰來加密訊息“Message”并將其保存為檔案 ciphertext.txt 通過將預先接收的資料轉換為十六進制編碼。我不需要生成公鑰,我已經有一個現成的公鑰。使用此公鑰,您需要對訊息進行加密。這是我能夠做的:
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/pem"
"errors"
"log"
"os"
)
func main() {
publicKeyBytes, err := os.ReadFile("publicik.key")
if err!= nil {
return
}
publicKey, err := decodepublicKey(publicKeyBytes)
if err != nil {
return
}
plaintext := []byte("Message")
ciphertext, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, plaintext, nil)
if err != nil {
return
}
log.Printf( "%x", ciphertext)
privateKeyBytes, err := os.ReadFile("private.key")
if err != nil {
return
}
privateKey, err := decodePrivateKey(privateKeyBytes)
if err != nil {
return
}
decryptedtext, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, privateKey,ciphertext, nil)
if err != nil {
return
}
log.Printf("%s", decryptedtext)
}
func decodepublicKey(key []byte) (*rsa.PublicKey, error) {
block, _:= pem.Decode(key)
if block == nil {
return nil, errors.New("can't decode pem block")
}
publicKey, err := x509.ParsePKCS1PublicKey(block.Bytes)
if err != nil {
return nil, err
}
return publicKey, nil
}
func decodePrivateKey(key []byte) (*rsa.PrivateKey,error) { block, _ := pem.Decode(key)
if block == nil {
return nil, errors.New("can't decode pem block")
}
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return privateKey, nil
}
那我不知道怎么解決這個問題?請幫助解決這個問題
uj5u.com熱心網友回復:
我除錯了您的代碼并發現了 2 個潛在問題:
- 仔細檢查您是否需要使用
x509.ParsePKCS1PublicKey()或x509.ParsePKIXPublicKey(). 這取決于您的公鑰的格式。更多資訊:https : //stackoverflow.com/a/54775627/9698467 - 您可能需要在
decodepublicKey函式中輸入 assert 公鑰:return publicKey.(*rsa.PublicKey), nil。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/400779.html
標籤:去
下一篇:簡單的godoc你好世界
