在Android的RSA加密 [英] RSA encryption in Android
问题描述
我写一个程序,它采用了RSA的Android系统。我有以下问题: 我得到的RSA密钥:
I am writing a program which employs RSA in Android. I have the following problem: I am getting the RSA keys:
KeyPair kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();
使用加密功能来加密测试字符串:
Using the encryption function to encrypt a test string:
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);
在解密功能我解密数据传回,以获得原始字符串
In the decryption function i am decrypting the data back to get the original string
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在记录中打印出的数据不匹配原始字符串测试。我在哪里这个问题呢?
The data in 'p' printed out in the log does not match the original string "test" . Where am I going wrong in this?
推荐答案
下面是关于如何做到这一点的例子,但在实践中,
Here an example on how to do it, BUT in practice,
您真的不能加密和解密整个文件,只用RSA。该
RSA算法只能加密一个块,并且它是相当慢
做一个整个文件。
您可以使用加密文件
3DES或AES,然后加密AES密钥使用目标收件人的
RSA公钥。
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.
有些code:
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();
}
这篇关于在Android的RSA加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!