登录
首页 >  Golang >  Go问答

使用 RSA/PEM 文件解密测试消息时出错

来源:stackoverflow

时间:2024-04-09 14:51:33 309浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《使用 RSA/PEM 文件解密测试消息时出错》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

大家好,我目前正在尝试使用以下代码完成三件事。

  1. 使用 crypto/rsa 库生成公钥/私钥对。

  2. 将公钥和私钥导出到单独的 pem 文件中,以便在单独的程序中使用。

  3. 将 pem 文件分别加载到各自的脚本中以对消息进行编码/解码。

一切正常,直到我尝试使用“private-key-decryption.go”解密测试消息。我在解密密文时收到此错误“解密错误:加密/rsa:解密错误”

其中包括我正在使用的所有代码块

密钥生成.go

package main

import (
    "crypto"
    "crypto/rand"
    "crypto/rsa"
    "crypto/sha256"
    "crypto/x509"
    "encoding/pem"
    "fmt"
    "os"
)

//write_private_key_to_file write pem_key to a file
func writetofile(pem_key string, filename string) {

    f, err := os.create(filename)
    if err != nil {
        fmt.println(err)
        return
    }
    l, err := f.writestring(pem_key)
    if err != nil {
        fmt.println(err)
        f.close()
        return
    }
    fmt.println(l, "bytes written successfully")
    err = f.close()
    if err != nil {
        fmt.println(err)
        return
    }

}

//exportrsaprivatekeyaspemstr returns private pem key
func exportrsaprivatekeyaspemstr(privkey *rsa.privatekey) string {
    privkey_bytes := x509.marshalpkcs1privatekey(privkey)
    privkey_pem := pem.encodetomemory(
        &pem.block{
            type:  "rsa private key",
            bytes: privkey_bytes,
        },
    )
    return string(privkey_pem)
}

//exportrsapublickeyaspemstr_to_pem_file extracts public key from generated private key
func exportrsapublickeyaspemstr(publickey *rsa.publickey) (string, error) {
    pubkey_bytes, err := x509.marshalpkixpublickey(publickey)
    if err != nil {
        return "", err
    }
    //fmt.println(pubkey_bytes)
    pubkey_pem := pem.encodetomemory(
        &pem.block{
            type:  "rsa public key",
            bytes: pubkey_bytes,
        },
    )

    return string(pubkey_pem), nil
}

func main() {
    // generate a 1024-bit private-key
    priv, err := rsa.generatekey(rand.reader, 1024)

    // extract the public key from the private key as string
    pub := &priv.publickey

    message := []byte("test message")

    hashed := sha256.sum256(message)

    signature, err := rsa.signpkcs1v15(rand.reader, priv, crypto.sha256, hashed[:])
    if err != nil {
        fmt.printf("error from signing: %s\n", err)
        return
    }

    err = rsa.verifypkcs1v15(&priv.publickey, crypto.sha256, hashed[:], signature)
    if err != nil {
        fmt.printf("error from verification: %s\n", err)
        return
    } else {
        fmt.printf("signature is verified\n")
    }

    //calling function to export private key into pem file
    pem_priv := exportrsaprivatekeyaspemstr(priv)

    //writing private key to file
    writetofile(pem_priv, "private-key.pem")

    //calling function to export public key as ppem file
    pem_pub, _ := exportrsapublickeyaspemstr(pub)
    writetofile(pem_pub, "public-key.pem")
}

公钥加密.go

package main

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/sha256"
    "crypto/x509"
    "encoding/pem"
    "errors"
    "fmt"
    "io/ioutil"
)

//parsersapublickeyfrompemstr takes a publickeypem file as a string and returns a rsa.publickey object
func parsersapublickeyfrompemstr(pubpem string) (*rsa.publickey, error) {
    block, _ := pem.decode([]byte(pubpem))
    if block == nil {
        return nil, errors.new("failed to parse pem block containing the key")
    }

    pub, err := x509.parsepkixpublickey(block.bytes)
    if err != nil {
        return nil, err
    }

    switch pub := pub.(type) {
    case *rsa.publickey:
        return pub, nil
    default:
        break // fall through
    }
    return nil, errors.new("key type is not rsa")
}

func main() {

    //reading in the public key file to be passed the the rsa object creator
    publickeyasstring, err := ioutil.readfile("public-key.pem")
    if err != nil {
        fmt.print(err)
    }

    //creating parsing public pem key to *rsa.publickey
    rsa_public_key_object, _ := parsersapublickeyfrompemstr(string(publickeyasstring))

    challengemsg := []byte("c")

    ciphertext, err := rsa.encryptoaep(sha256.new(), rand.reader, rsa_public_key_object, challengemsg, nil)
    if err != nil {
        fmt.printf("error from encryption: %s\n", err)
        return
    }

    fmt.printf("%x", ciphertext)
}

私钥解密.go

package main

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/sha256"
    "crypto/x509"
    "encoding/pem"
    "errors"
    "fmt"
    "io/ioutil"
)

//takes a privatekey PEM file as a string and returns a pointer rsa.PublicKey object
func parseRsaPrivateKeyFromPemStr(p string) (*rsa.PrivateKey, error) {
    block, _ := pem.Decode([]byte(p))
    if block == nil {
        return nil, errors.New("failed to parse PEM block containing the key")
    }

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

    return key, nil
}

func main() {

    //reading in the public key file to be passed the the rsa object creator
    PrivateKeyAsString, err := ioutil.ReadFile("private-key.pem")
    if err != nil {
        fmt.Print(err)
    }

    //Creating parsing private PEM key to *rsa.PublicKey
    rsa_private_key_object, _ := parseRsaPrivateKeyFromPemStr(string(PrivateKeyAsString))

    ciphertext := []byte("1f58ab29106c7971c9a4307c39b6b09f8910b7ac38a8d0abc15de14cbb0f651aa5c7ca377fd64a20017eaaff0a57358bc8dd05645c8b2b24bbb137ab2e5cf657f9a6a7593ce8d043dd774d79986b00f679fc1492a6ed4961f0e1941a5ef3c6ec99f952b0756700a05314c31c768fe9463f77f23312a51a97587b04b4d8b50de0")

    plaintext, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, rsa_private_key_object, ciphertext, nil)
    if err != nil {
        fmt.Printf("Error from decryption: %s\n", err)
        return
    }

    fmt.Printf("\nPlaintext: %s\n", string(plaintext))

}

请让我知道需要更改哪些内容。这是我的第一个加密项目,我的眼袋开始出现了,哈哈


解决方案


你已经很接近了。在加密部分,您将生成一个具有 %x 格式字符串的十六进制字符串。所以,在解密部分,应该进行相应的十六进制解码。

在您的 private-key-decryption.go 中,更改

ciphertext := []byte("1f58ab29106c7971c9a4307c39b6b09f8910b7ac38a8d0abc15de14cbb0f651aa5c7ca377fd64a20017eaaff0a57358bc8dd05645c8b2b24bbb137ab2e5cf657f9a6a7593ce8d043dd774d79986b00f679fc1492a6ed4961f0e1941a5ef3c6ec99f952b0756700a05314c31c768fe9463f77f23312a51a97587b04b4d8b50de0")

ciphertext, err := hex.DecodeString("1f58ab29106c7971c9a4307c39b6b09f8910b7ac38a8d0abc15de14cbb0f651aa5c7ca377fd64a20017eaaff0a57358bc8dd05645c8b2b24bbb137ab2e5cf657f9a6a7593ce8d043dd774d79986b00f679fc1492a6ed4961f0e1941a5ef3c6ec99f952b0756700a05314c31c768fe9463f77f23312a51a97587b04b4d8b50de0")
if err != nil {
        fmt.Printf("Error from hex decode: %s\n", err)
        return
}

今天关于《使用 RSA/PEM 文件解密测试消息时出错》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>