使用RSA私钥解密

时间:2013-12-11 22:43:00

标签: java android encryption

所以我正在尝试使用RSA公钥和私钥加密/解密字符串。它加密很好,但每当我尝试解密加密的字符串时,我得到一个非常奇怪的输出。例如,“你好”解密为:

  

] T1#Z} - pԏh25〜E'bh〜-Itk> +   ·V不然[@jp 2PX @盎司$ 5 @&安培;!V = AeAm; @ d<” &} }r q5U ? J c �Db�A�! { w| IE Ì魈S ] {{1} } {EJ04l3Ύn3

我不确定我的解密算法是否有问题,或者它是否与将解密的字节转换为字符串(或沿着这些行的某些内容)有关。

这是解密方法:

�'����88��%������   ��O.N:S

加密:

public String decryptString(PrivateKey key, String string) {
    try {

        pubDecryptCipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decodedBytes = Base64.decodeBase64(string.getBytes());
        byte[] unencryptedByteArray = pubDecryptCipher.doFinal(decodedBytes);
        return new String(unencryptedByteArray, "UTF8");

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

以十六进制解密的字符串:

public String encryptString(PublicKey key, String string) {
    try {
        pubEncryptCipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] eba = pubEncryptCipher.doFinal(string.getBytes("UTF8"));
        byte[] encodedBytes = Base64.encodeBase64(eba);

        return encodedBytes.toString();

    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (BadPaddingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    }
    return null;
}

通过字符串算法,你的意思是:

efbfbdefbfbdefbfbdc78d2defbfbd6e2fefbfbdefbfbdefbfbd50efbfbd73efbfbd6defbfbd31efbfbd40117defbfbdefbfbd2cefbfbd576ed39c2aefbfbd41533defbfbdefbfbd1a167c23efbfbdd0a11a3213355eefbfbdefbfbdefbfbd6145efbfbd55efbfbdefbfbd7d09efbfbd700814efbfbdefbfbd687b225eefbfbd3c00efbfbdefbfbd3509efbfbd6c5eefbfbdefbfbd79efbfbdefbfbd033d77efbfbd71efbfbd57efbfbd7e76d6a101efbfbd4aefbfbd4a0540efbfbdefbfbd297f6fefbfbd73efbfbdefbfbdefbfbd010defbfbdefbfbdefbfbd00efbfbd490706efbfbdefbfbdefbfbd322435efbfbd02efbfbdefbfbd1dd79477efbfbd13efbfbdd5bb57efbfbdefbfbd0aefbfbd39404b53efbfbdefbfbd06165aefbfbd32efbfbdefbfbd4665efbfbddd9d6aefbfbd0842efbfbdefbfbd7c35efbfbdefbfbdefbfbd3e7eefbfbdefbfbd11efbfbd1fc7b839efbfbd44efbfbdefbfbd1aefbfbd3a314ac48eefbfbd7cefbfbd77efbfbd097449efbfbdcaa8351aefbfbdefbfbd5befbfbdefbfbd655a62efbfbd3651efbfbdefbfbd41efbfbd64efbfbd1150efbfbd65efbfbd224720060cefbfbd11efbfbdefbfbdefbfbdefbfbd0defbfbd1439efbfbdefbfbd

1 个答案:

答案 0 :(得分:0)

问题是encodedBytes.toString()没有按照您的预期行事。您需要改为new String(encodedBytes, StandardCharsets.ASCII);。或者在Java SE 1.7兼容代码之前new String(encodedBytes, Charset.forName("ASCII"));

您应始终指示填充模式;请使用例如"RSA/None/PKCS1Padding"代替"RSA"