Android RSA Bar Encryption

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.

+6
android string rsa
source share
1 answer

String encrypted = new String(encryptedBytes);

- error. The result of cryptographic conversions is binary bytes. You cannot securely store them as Strings.

Using is.available() is probably also a mistake, but I'm not sure about this.

Finally, this is one of my favorite motives when people use the default charset versions new String(...) and String.getBytes() . This is very rare to do, especially in the fact that Java claims to "write once, run everywhere." The default encoding is different on different platforms, which will cause an error in your code, even if you do everything right. You should always specify a specific encoding. In every case that I have ever seen, simply using the UTF-8 encoding ( Charset.forName("UTF-8"); ) will always work and present data efficiently.

+6
source share

All Articles