Situation:
I need an application that encrypts a string using RSA. I have a public key stored in res / raw, and since the key is 1024 bits, the resulting string should be 128 bytes long. However, the resulting string after encryption has a length of 124 and, as a result, decryption fails.
The function that I use to recover the public key:
private PublicKey getPublicKey() throws Exception { InputStream is = getResources().openRawResource(R.raw.publickey); DataInputStream dis = new DataInputStream(is); byte [] keyBytes = new byte [(int) is.available()]; dis.readFully(keyBytes); dis.close(); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePublic(spec); }
And the code of the function that I use for encryption:
private String rsaEncrypt (String plain) { byte [] encryptedBytes; Cipher cipher = Cipher.getInstance("RSA"); PublicKey publicKey = getPublicKey(); cipher.init(Cipher.ENCRYPT_MODE, publicKey); encryptedBytes = cipher.doFinal(plain.getBytes()); String encrypted = new String(encryptedBytes); return encrypted;
}
PD: The code works fine in a desktop application, it just crashes in Android.
I really would appreciate any help,
Many thanks.
android string rsa
Ullfoll
source share