Android中的RSA加密

DaT*_*omB 6 java encryption android rsa

我正在编写一个在Android中使用RSA的程序.我有以下问题:我收到了RSA密钥:

KeyPair kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();
Run Code Online (Sandbox Code Playgroud)

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

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);
Run Code Online (Sandbox Code Playgroud)

在解密功能中,我正在解密数据以获得原始字符串

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);
Run Code Online (Sandbox Code Playgroud)

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

Fra*_*ank 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();
}
Run Code Online (Sandbox Code Playgroud)