【问题标题】:Decode data using openssl that has been encoded using java使用已使用 java 编码的 openssl 解码数据
【发布时间】:2019-03-29 05:55:27
【问题描述】:

我必须与一个用 java 编写的系统交互,该系统使用以下 java 方法加密数据:

public final void rsaEncrypt(String data, String filePath) {
    try {
            Base64.Encoder encoder = Base64.getEncoder();
            PublicKey pubKey = readKeyFromFile("/" + Constants.PUBLIC_KEY_FILE_NAME, filePath);
            Cipher cipher = Cipher.getInstance(Constants.RSA_INSTANCE);
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            byte[] cipherData = cipher.doFinal(data.getBytes("UTF-8"));
            writeToFile(Constants.ENCRYPTED_STRING_FILE_NAME, filePath, encoder.encodeToString(cipherData));
        } catch (BadPaddingException | InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException
                | IllegalBlockSizeException | UnsupportedEncodingException e) {
            if (LOG.isErrorEnabled())
                LOG.error("Error encrypting String.", e);
            throw new EncryptionException("Error encrypting data", e);
        }
}

我的代码是使用 openssl 用 c++ 编写的:

std::string prv =
    "-----BEGIN RSA PRIVATE KEY-----\n"
     // cut  key data

    "-----END RSA PRIVATE KEY-----\n";  
BIO *bio = BIO_new_mem_buf((void*)prv.c_str(), -1);
RSA* rsaPrivKey = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, NULL);

if (!rsaPrivKey)
    printf("ERROR: Could not load PRIVATE KEY!  PEM_read_bio_RSAPrivateKey FAILED: %s\n", ERR_error_string(ERR_get_error(), NULL));

BIO_free(bio);
// where enc[] holds the Base64 decoded data, but len becomes -1  and no data is decoded.
int len = RSA_private_decrypt(64,(unsigned char *)&enc, (unsigned char *)&dec, private_key_, RSA_PKCS1_PADDING);

我可以解码我用公钥加密自己的数据,但似乎与 java 选项不匹配。

有什么建议吗?

【问题讨论】:

  • 您是否尝试过致电ERR_get_error 以获取有关错误状态的更多详细信息?
  • 我解决了这个问题,因为事实证明 Java 代码没有正确创建它们的密钥,也没有反映给我的 .pem 文件。

标签: java c++ openssl


【解决方案1】:

正如我的评论所说,这里没有答案,事实证明 Java 代码在创建他们的密钥时不正确,这与给我的 .pem 文件不匹配。

【讨论】:

    猜你喜欢
    • 2016-05-18
    • 2015-11-04
    • 2015-04-30
    • 1970-01-01
    • 2015-12-09
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多