【问题标题】:RSA encryption in AndroidAndroid 中的 RSA 加密
【发布时间】:2012-11-25 22:36:22
【问题描述】:

我正在编写一个在 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”不匹配。我哪里错了?

【问题讨论】:

  • 那么日志中打印出什么?如果您的密钥不匹配或密码乱码,您会得到一个异常,而不是错误的答案。
  • 另请注意,cipherData 将是一个类似随机的二进制字符串,因此仅使用原始字节 (String s = new String(cipherData);) 将其转换为字符串可能会给您带来奇怪的结果。

标签: java android encryption rsa


【解决方案1】:

这是一个关于如何做到这一点的例子,但是在实践中,

仅使用 RSA 无法真正加密和解密整个文件。这 RSA算法只能加密单个块,速度比较慢 用于制作整个文件。
您可以使用加密文件 3DES 或 AES,然后使用预期接收者的加密 AES 密钥 RSA 公钥。

一些代码:

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();
}

【讨论】:

  • 你提到了You can encrypt the file using 3DES or AES, and then encrypt the AES key using intended recipient's RSA public key. 我正是需要它来加密和解密视频文件。你能帮我吗...一些样本会有用
  • @nish 我有同样的要求,你能做到吗?
猜你喜欢
  • 1970-01-01
  • 2012-09-10
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多