【问题标题】:RSA Encryption on Windows using openssl C++ / Error in decryption在 Windows 上使用 openssl C++ 进行 RSA 加密/解密时出错
【发布时间】:2018-08-17 20:41:58
【问题描述】:

我在 Android 上生成 rsa public/private 使用:

KeyPairGenerator kpg;
KeyPair kp;
PublicKey publicKey;
PrivateKey privateKey;
kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();

然后我将公钥发送到 Windows 并使用 OpenSSL 库加密数据:

int resEncryption = RSA_public_encrypt(length, in, encrypted, rsaPkey, RSA_PKCS1_OAEP_PADDING);

然后我在 Windows 上将加密转换为十六进制:

stringstream ss;
for (int i = 0; i < resEncryption; i++)
    ss << std::hex << (int)encrypted[i] << std::setfill('0');

string hexEncrypted = ss.str();

我在 Android 上进行了 hexEncrypted 并将其放入字符串中:

StringBuilder sb = new StringBuilder();
char[] hexData = hex.toCharArray();
for (int count = 0; count < hexData.length - 1; count += 2) {
    int firstDigit = Character.digit(hexData[count], 16);
    int lastDigit = Character.digit(hexData[count + 1], 16);
    int decimal = firstDigit * 16 + lastDigit;
    sb.append((char)decimal);
}
String hexDecrypted = sb.toString();

我要解密这些数据:

byte[] encryptedBytes = hexDecrypted.getBytes();
Cipher cipher1 = Cipher.getInstance("RSA/None/OAEPwithSHA-1andMGF1Padding");//also tried RSA/ECB/OAEPwithSHA-1andMGF1Padding
cipher1.init(Cipher.DECRYPT_MODE, privateKey);
decryptedBytes = cipher1.doFinal(encryptedBytes);

但我在 CipherSpi.class 的 engineDoFinal 方法中遇到错误:

protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException {
    if(input != null) {
        this.bOut.write(input, inputOffset, inputLen);
    }

    if(this.cipher instanceof RSABlindedEngine) {
        if(this.bOut.size() > this.cipher.getInputBlockSize() + 1) {
            throw new ArrayIndexOutOfBoundsException("too much data for RSA block");
        }
    } else if(this.bOut.size() > this.cipher.getInputBlockSize()) {
        throw new ArrayIndexOutOfBoundsException("too much data for RSA block");//Error here 
    }

    return this.getOutput();
} 

【问题讨论】:

  • 您将十六进制字符转换为字节的方法不可靠,因此不正确。另外,没有String.toBytes()这样的方法,所以你的代码不会编译。
  • @JamesKPolk true 我编辑了我的问题(我想提出的是 getBytes)
  • @JamesKPolk 你会用什么来将十六进制字符转换为字节?
  • 我认为保留这个问题没有任何意义,因为它对任何对“使用 openssl C++ 在 Windows 上进行 RSA 加密”感兴趣的人都没有用。接受的自我回答只是切线相关,因为该错误结果是关于二进制到十六进制的转换,而不是关于加密。我会投票结束这个问题,但不幸的是我不能,因为它有一个活跃的赏金。

标签: java android encryption rsa


【解决方案1】:

看起来我在使用 C++ 进行十六进制转换时遇到了问题,这解决了我的问题。现在我在 Android 上得到了预期长度的十六进制字符串。

string asciiResEnc(reinterpret_cast<char*>(encrypted), resEncryption);
stringstream ss;
for(int i = 0; i < asciiResEnc.size(); i++)
    ss << std::hex << setw(2) << setfill('0') << (int) (unsigned char)asciiResEnc[i];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    相关资源
    最近更新 更多