gpt4 book ai didi

java - Android 中的 RSA 加密

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:01:10 25 4
gpt4 key购买 nike

我正在编写一个在 Android 中使用 RSA 的程序。我有以下问题:我正在获取 RSA key :

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"不匹配。我哪里出错了?

最佳答案

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

You can't really encrypt and decrypt whole files with just RSA. The RSA algorithm can only encrypt a single block, and it is rather slow for doing a whole file.
You can encrypt the file using 3DES or AES, and then encrypt the AES key using intended recipient's RSA public key.

部分代码:

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

关于java - Android 中的 RSA 加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13556295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com