Android中的RSA加密

6

我正在编写一个在Android中使用RSA的程序。 我遇到了以下问题: 我已经获取了RSA密钥:

KeyPair kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();

使用加密函数对测试字符串进行加密:

String test ="test";
byte[] testbytes = test.getBytes();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherData = cipher.doFinal(testbytes);
String s = new String(cipherData);
Log.d("testbytes after encryption",s);

在解密函数中,我正在将数据解密回原始字符串。

Cipher cipher2 = Cipher.getInstance("RSA");
cipher2.init(Cipher.DECRYPT_MODE, privateKey);
byte[] plainData = cipher.doFinal(cipherData);
String p  = new String(plainData);
Log.d("decrypted data is:",p);

日志中打印出来的 'p' 数据与原始字符串 "test" 不匹配。我在哪里做错了?


日志中打印出了什么?如果您有不匹配的密钥或乱码密码,您将得到一个异常而不是错误答案。 - President James K. Polk
请注意,cipherData将是一个类似随机的二进制字符串,因此仅使用原始字节(String s = new String(cipherData);)将其转换为字符串可能会产生奇怪的结果。 - Nikolay Elenkov
1个回答

10

这里有一个关于如何实现的例子,但是在实际操作中,

你不能只使用RSA来加密和解密整个文件。RSA算法只能加密单个块,并且对于整个文件来说速度相对较慢。
你可以使用3DES或AES加密文件,然后使用预期接收方的RSA公钥加密AES密钥。

一些代码:

public static void main(String[] args) throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

    kpg.initialize(1024);
    KeyPair keyPair = kpg.generateKeyPair();
    PrivateKey privKey = keyPair.getPrivate();
    PublicKey pubKey = keyPair.getPublic();

    // Encrypt
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);

    String test = "My test string";
    String ciphertextFile = "ciphertextRSA.txt";
    InputStream fis = new ByteArrayInputStream(test.getBytes("UTF-8"));

    FileOutputStream fos = new FileOutputStream(ciphertextFile);
    CipherOutputStream cos = new CipherOutputStream(fos, cipher);

    byte[] block = new byte[32];
    int i;
    while ((i = fis.read(block)) != -1) {
        cos.write(block, 0, i);
    }
    cos.close();

    // Decrypt
    String cleartextAgainFile = "cleartextAgainRSA.txt";

    cipher.init(Cipher.DECRYPT_MODE, privKey);

    fis = new FileInputStream(ciphertextFile);
    CipherInputStream cis = new CipherInputStream(fis, cipher);
    fos = new FileOutputStream(cleartextAgainFile);

    while ((i = cis.read(block)) != -1) {
        fos.write(block, 0, i);
    }
    fos.close();
}

你提到了“您可以使用3DES或AES加密文件,然后使用预期接收者的RSA公钥加密AES密钥。” 我正需要这个来加密和解密视频文件。你能帮我吗...一些示例会很有用。 - Anish
@nish 我有同样的需求,你能做到吗? - user2028

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接