Encriptação RSA no Android
Estou a escrever um programa que emprega a RSA no Android. Tenho o seguinte problema::
Vou buscar as chaves da RSA.
KeyPair kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();
a usar a função de encriptação para cifrar um texto de teste:
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);
na função de descodificação estou a descodificar os dados de volta para obter o texto original
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);
os dados em' p ' impressos no registo não correspondem ao texto original "teste" . Onde é que eu errei nisto?
6
1 answers
Aqui um exemplo de como fazê-lo, , MAS, na prática,
Você não pode realmente encriptar e descriptografar arquivos inteiros apenas com RSA. O O algoritmo RSA só pode encriptar um único bloco, e é bastante lento por fazer um arquivo inteiro.
Poderá encriptar o ficheiro com 3DES ou AES, e depois encriptar a chave AES usando a do destinatário RSA public key.
Algum código:
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();
}
5
Author: Frank, 2014-12-15 16:50:13