How to decrypt encrypted messages using an RSA private key

PHPz
Release: 2024-02-09 15:30:20
forward
873 people have browsed it

如何使用 RSA 私钥解密加密消息

php editor Youzi will introduce you how to use RSA private key to decrypt encrypted messages. RSA is an asymmetric encryption algorithm that encrypts and decrypts information by generating public and private keys. When using RSA to decrypt an encrypted message, you need to have the corresponding private key and use the private key to decrypt the encrypted message. During the decryption process, the private key will decode the encrypted message and restore it to the original plaintext information. By mastering RSA private key decryption, you can deliver and protect sensitive information more securely. Next, we will introduce the steps and precautions for RSA private key decryption in detail to help you better understand and apply this encryption and decryption technology.

Question content

I am accessing an api that requires my public key, which will then return a response containing a vector and a token, but they are in encrypted form (I think they Use my public key to do this). In order to decrypt it I need to use my private key. Both private and public keys are der encoded. I basically want to implement something like this https://www.devglan.com/online-tools/rsa-encryption-decryption

The keys I used (again, they are virtual!) Public: migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqcbi1sofn/zpsprblpaw/c4gdkho6idv3j/p5leeupasbvvpq6wy7tf6lfbstcirq48omd34p3z5sx1jyy15oxnxnkbpoodv8byqdnk/lffcz5 720yunka0 xihuol/zi0c0pwb6hkaakt0sbeglbcux6yr6sbjbfai2ofikk/mgswidaqab

Private: miicdqibadanbgkqhkig9w0baqefaascal8wggjbageaaogbajsjvkh839k ymsgu8bb9zgymoejoh2/cn8/ksqrskcxtvwmrrbjtn/qv8fjnykurjygwpfinfpmxfwnjlxk5c3e0og mg52/wfhb2cr8t8 vxnnvbtjq2rrtgidsix9mlrzq9yhoeqacrpsxt4ytsk5frkvpjskevojah8gqt yazagmbaaecgya5kaed/z8tmslujhxgajzzgldkczms6uhxasdw/1fwxooeatbs5ha7gumcerhkib sps8hmlkxgvp2sin/8fb9mo1yhaan2 g52 cvpr2qmeeuowfuztm/gllt4ruib7smc5uxl7sw55bghrxqdfhjskow4rpga irjuysy5gizswqjbandtff vwpkrr8mhyvagollkra1cfn8g9x1ega3mgwpny oh5nmjfe0ibaxo69jlrnbajk oxnpsyh/azzseehascqqc f15 dvsjh8tjsxz8rcdpmdp p9j/eoi7 v0igwkaasjczfywxeckaaipvwit7fkj3n83nj0ppm9xwh22cygszakaaviwotleoken71v/tt kauyt32ahgwnkckwvwmv4/ws6rflcnvdxr/cnkcgeqlkxtlkkp /clg3gy6o 2ymi5xnaka8l4jsycryb8sw0rlvomoq2vz /lacrnkzsecpywk4uupcu9ffrutaje6mnaj2pna9wjxw5c exk5rcmq7rcgrxakajize3jbwuu3mx5tdmhfgcviz38jnfsujfryblkanjegod 4zcxrzxfo7ikda ptfmre7ztnu7wucm0yut2qa0j

Encrypted message: buy5nr/pujncfxeuxqd4oxkcvmo2jilwh5vkzlz1udm4m0vxdv4ba1oanhbttqetqeny1vfw2v4v9pw5hmdics1sdgn69ceehjbned46rk1evtmvqzgp9ha54axie5v/1t dkywj aft0fxv j4kffxgxezf19q8lb2aojcaejk6s= Let's get into the encoding part: I'm retrieving my private and public keys from env file:

public := godotenvvariable("publickey")
private := godotenvvariable("privatekey")
Copy after login

Now, after hitting the api and getting the result, I try to decrypt the message using the rsa.decryptoaep function but it keeps giving me [] crypto/rsa: decryption error . After debugging inside the package itself, I get the error here:

k := priv.size() // private key size
if len(ciphertext) > k || //ciphertext is the encrypted text and hash.size()*2+2 is the hash size that im using
    k < hash.size()*2+2 {
    return nil, errdecryption
}
Copy after login

The result of the if statement: k = 128 hash.size()*2 2=66 cipher = 172 At first I had problems converting the private key (in my case a string as it comes from an env file) to an rsa private key. Here's what I did to resolve the issue:

senc, err := b64.stdencoding.decodestring(private) //using this package "encoding/base64"
Copy after login

Then I convert it like this:

block := &pem.Block{
    Type:  "RSA PRIVATE KEY",
    Bytes: sEnc,
    }
    parseResult, err := x509.ParsePKCS8PrivateKey(block.Bytes)
Copy after login

What did i do wrong?

Workaround

If rsa is selected in the Select Password Type field, the devglan website will apply pkcs#1 v1.5 as padding, Therefore rsa.decryptpkcs1v15() must be used. The private key is a base64 encoded pkcs#8 der key that can be imported using x509.parsepkcs8privatekey().

Together:

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    b64 "encoding/base64"
    "fmt"
)

func main() {

    // Base64 decode ciphertext
    ciphertext, _ := b64.StdEncoding.DecodeString("BUy5nR/PuJNCFXeUxQd4oxkCvMo2JiLwH5VkzLz1UdM4M0VXDv4Ba1OaNHbttqETQENy1VfW2V4v9Pw5HmDIcS1sdGN69ceEHJbned46rK1EVtMVQZGP9ha54AXie5v/1TdKYWJ+AFt0FxVj4kfFXGXEzF19Q8LB2AOJCAEJK6s=")

    // Import PKCS#8 key
    pkcs8DerKey, _ := b64.StdEncoding.DecodeString("MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJsjVKh839k+ymsGU8Bb9zgYMoejoh2/cn8/ksQRSkCxtVWmrrBjtN/qV8FJNyKurjygwPfinfPmxfWNjLXk5c3E0oGmg52/wFhB2cr8t8VxnnvbTJQ2RrTGIdSiX9mLRzQ9YHoeQACRPSxt4YtsK5frKvpJskEVojah8gqT+YazAgMBAAECgYA5KaeD/Z8tmSlUjhxGAJzzGldkCzMs6uHxaSdW/1fwxooeaTBs5hA7gUmcerHKIbsps8HmlKXGvP2sIN/8Fb9mo1yHaAN2g52+cvpr2QmeeUOwfuZTM/gllT4rUIB7sMC5Uxl7sW55bGhRxqdfHJskow4rPga+irjuYSy5GIZSwQJBANDtfF+VWPKrR8MHYvaGoLLkrA1cFn8g9x1eGA3mgWPNYoH5nMJfe0IBaXo69jlrnBAjK+oxnPSyh/AZzsEehasCQQC+F15dVSjH8tJSXz8RCDpMdp+P9J/eoi7+V0IgwKAaSJCZfYWXeckAAIpvwit7fkj3n83nj0PPm9Xwh22CYGsZAkAAvIWOtLEOken71v/TTKAuYT32AhgWNKCKWvWMvv4/ws6RFLcnvDxr/CNKCgEqLKXtLKKP/cLG3gY6o2ymI5xnAkA8l4JSycRYB8SW0RlvOmoq2Vz/LACRnKzSEcpYWk4uUpcU9ffRUtaJE6MNAJ2Pna9wjxW5C+eXk5rcMq7rcgRxAkAjizE3JbwUu3MX5TDmHfGCvIZ38jnfSUjFrYBLKaNJegOD4zcxRZXfO7iKDa+PtFMRe7ZtnU7WuCM0yUT2Qa0j")
    key, _ := x509.ParsePKCS8PrivateKey(pkcs8DerKey)
    var privateKey *rsa.PrivateKey
    privateKey, _ = key.(*rsa.PrivateKey)

    // Decrypt (using RSA with PKCS#1 v1.5 padding)
    rng := rand.Reader
    plaintext, _ := rsa.DecryptPKCS1v15(rng, privateKey, ciphertext)

    fmt.Println(string(plaintext)) // {"token":"312ade4b52e7bb4cadf59b4c7c83cb41","vector":"2b8db4fdb11f361d","id":"63876cf63ec7a641db8f1def"}
}
Copy after login

The above is the detailed content of How to decrypt encrypted messages using an RSA private key. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!