提问者:小点点

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


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

我有四个主要功能。

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

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

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

Decrypt()接收密码文本并对其进行解密,使用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))
    }

}

crypto_service去吧

func Encrypt(pub *rsa.PublicKey, text string) ([]byte, error) {

    encryptedBytes, err := rsa.EncryptOAEP(
        sha256.New(),
        rand.Reader,
        pub,
        []byte(text),
        nil)
    if err != nil {
        return nil, err
    }

    return encryptedBytes, nil
}

func Decrypt(privKey *rsa.PrivateKey, cipherText []byte) ([]byte, error) {

    decryptedBytes, err := rsa.DecryptOAEP(sha256.New(), nil, privKey, cipherText, nil)
    if err != nil {
        return nil, err
    }

    return decryptedBytes, nil
}

gen_keys_service去吧

func GenKeys() error {

    privKey, err := rsa.GenerateKey(rand.Reader, 2048)
    if err != nil {
        return err
    }

    privFile, err := os.Create("private_key.pem")
    if err != nil {
        return err
    }

    pemData := &pem.Block{
            Type:    "RSA PRIVATE KEY",
            Bytes:   x509.MarshalPKCS1PrivateKey(privKey),
    }

    err = pem.Encode(privFile, pemData)
    if err != nil {
        return err
    }

    privFile.Close()

    fmt.Println("Your keys have been written to private_key.pem")

    return nil

}

func GetKeys() (*rsa.PrivateKey, error) {

    file, err := os.Open("private_key.pem")
    if err != nil {
        return nil, err
    }

    defer file.Close()

    //Create a byte slice (pemBytes) the size of the file size
    pemFileInfo, _ := file.Stat()
    var size = pemFileInfo.Size()
    pemBytes := make([]byte, size)

    //Create new reader for the file and read into pemBytes
    buffer := bufio.NewReader(file)
    _, err = buffer.Read(pemBytes)
    if err != nil {
        return nil, err
    }

    //Now decode the byte slice
    data, _ := pem.Decode(pemBytes)
    if data == nil {
        return nil, errors.New("could not read pem file")
    }


    privKeyImport, err := x509.ParsePKCS1PrivateKey(data.Bytes)
    if err != nil {
        return nil, err
    }

    return privKeyImport, nil

}

哦,这是我的pem文件的格式:

-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEApX2AUrhtH3FHSds3JAWmBDZcSwixydY/M52WmWfqDmQDRc6X
V4FqLyiEIMSq3Z7zOR9GH4a2Ps3HPlTvJa2EGkgKDk7h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BFM6q5+wn11IqmI/2V94isI3y6aLMLMLD/1pFJwA5EzQhrbS2SARlTtMc9UB3x
SR2abj5lX+09KycsvkDTFwsCgYEAhG4b509W4GlQHo/uL9XlPwtCHP3zXhdEKz7K
lv6Q2ynVF2B7G1L2SME0kf6YdIn39eEgXS2gjqK+AX+mpTKfYU1xWjsZj0CR8d+F
IC4Nms2yeYRtU54jWvyU1KwGSY6zRB1L3E4LfdGQ9L7ciA/xS16tUNQ0Wos8JGCV
inskT2kCgYBg4zzkUAmQ75hlRsM0r7ezrx4xt8GHrlxwOTeQYgVcymiSSMXVITNI
ByBfs+wqV7PrXjM69xPdV/CHczFcA7g/M0o0CJZhWead403knjZmGFlZypvWskOT
aK4nArJ0zaS7FGhCe24QORYZPGjCzg7dLKhKDvK1PB4ogRVo4dDckA==
-----END RSA PRIVATE KEY-----

共1个答案

匿名用户

在加密部分,密文显示十六进制编码。如果在解密部分输入了十六进制编码,则必须进行相应的十六进制解码,这在发布的代码中是缺失的。十六进制解码可以使用十六进制包完成。

此外,正如Peter的评论中提到的,必须删除尾随换行符,例如使用string. TrimSuffix()。或者,可以使用fmt.Scan()bufio.Scanner代替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))
...