2012-11-25 47 views
6

我正在编写一个在Android中使用RSA的程序。我有以下问题: 我收到RSA密钥:Android中的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”不匹配。我在哪里错了?

+0

那么是什么在日志中打印出来?如果你有不匹配的密钥或乱码,你会得到一个异常,而不是一个错误的答案。 –

+0

另外请注意''cipherData'将是一个随机的二进制字符串,所以通过使用原始字节('String s = new String(cipherData);')将它转换为一个字符串可能会给你奇怪的结果。 –

回答

5

这里就如何做到这一点,但在实践中一个例子,

你不能真正的加密和解密,只需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(); 
} 
+0

你已经提到'你可以使用3DES或AES加密文件,然后使用预期收件人的RSA公钥对AES密钥进行加密。'我完全需要加密和解密视频文件。你能帮我吗?一些样品将是有用的 – Vishnu

+0

@nish我有同样的要求,你能够做到这一点吗? – Siddharth