Rsa decryption return error 0D0680A8:asn1 encoding routines:asn1_check_tlen:wrong tag in openssl cpp

末鹿安然 提交于 2020-03-05 04:04:51

问题


I used openssl library for RSA encryption/decrytion in c++ (android ndk) and it's working fine. But when I encrypted data in RSA tester site and decrypted it in c++, openssl return this error:

0D0680A8:asn1 encoding routines:asn1_check_tlen:wrong tag

Here is my code:

typedef unsigned char byte;

char plainText[256] = "Test";
char publicKey[2048] = "-----BEGIN PUBLIC KEY-----\n
..."
char privateKey[2048] = "-----BEGIN RSA PRIVATE KEY-----\n"
...

RSA *rsa = createRSA(reinterpret_cast<unsigned char *>(publicKey), 1);

int size = RSA_size(rsa);
if (size < 0)
        throw std::runtime_error("RSA_size failed");

 std::string encrypted = "BVAbJHA8v1qo8JIyqLZb/wpAQQeQnSiUzO3Ajfo3cT0nQ+fWay1MLHY6Ra+XM6OswX7f4CVG0mgvJlLmMrEki12tEDNmVR63FZZOgW2jMRLSR6ZH2zPVW1fVh709xhFgp/YWagCmtlAHLCzwvbYkpDDSnZ5HLPL5oZE9VeMUlDCsVz4cvN8+e1Qv7PXwxtJjirDpwXUCW89qoKGk1UOoTPacRN8GpNo0ci96rqodoG5D8RYhBd0J1XBwtxWT91/qMUAV+xJbuO7mNLBjY+6tyJ1yOL4s2Ka0wQmLC+Kpk8IqBiuW16xcXdQXmtMU3r5gP6gl7SuQyFp0C8gK5aOpwQ==";

unsigned char decrypted[2048] = {};
char *errorChar = new char[120];

//padding RSA_PKCS1_PADDING

//int retEnc = RSA_public_encrypt(strlen(plainText),
//                                    reinterpret_cast<const unsigned char //*>(plainText), (byte*)&encrypted[0], rsa, RSA_PKCS1_PADDING);

//if (retEnc < 0) {
//      std::string errorMsg;
//      errorMsg.resize(256);
//      (void) ERR_error_string(ERR_get_error(), &errorMsg[0]);
//      throw std::runtime_error("RSA_public_encrypt failed");
// }
//    encrypted.resize(retEnc);

RSA *pk = createRSA(
            reinterpret_cast<unsigned char *>(privateKey), 0);

int decrypted_length = RSA_private_decrypt(RSA_size(rsa), reinterpret_cast<const unsigned char *>(encrypted.c_str()), decrypted, pk , RSA_PKCS1_PADDING);

if (decrypted_length == -1) {
    long Error = ERR_get_error();
    const char *MSG = ERR_error_string(Error, NULL);
    exit(0);
}

What is the reason of getting the error?

来源:https://stackoverflow.com/questions/59953092/rsa-decryption-return-error-0d0680a8asn1-encoding-routinesasn1-check-tlenwron

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!