I am trying to decrypt a string that I encrypted elsewhere. Here is my code:
private void test() {
try {
String stringMessage="Sf3O7Lr2+WN5szGyLejL3CjuBRZtQ72+ZBmgVTgWnatQZxUElzaBqFa1p0SVBqe9VWVxCxdEkejMVtDGEr0UJSVSK8EB/fPI6v8JE8dIu0JN0mMs4xlowhITy0tQR+1pcBtDFjzOl33xxQcq5JuPezxRDxFIp+IVkD8FdpqlttEKf2Tvqw9tqsdgiBKb5xDvKrkIDQXdLBh1gbAVZDSJYGHRkcOA8vz2ty/PeooKkfDK6IOn7KBwOBgSRgQr/MLBF3Xk2vRWgVGRh/fRkzu21EWo99Q5moWKxWl3HW/bbgTBQTb097XP3NTID9kSPhCfL0BEfBxonuNse5GBoeRnCw==";
byte[] byteMessage = Base64.decodeBase64(stringMessage.getBytes("UTF-8"));
System.out.println("ENCRYPTED MESSAGE byte Length: "+byteMessage.length);
String decryptedMsg = decryptString(byteMessage, loadCASPrivateKey());
System.out.println(decryptedMsg);
} catch (Exception e) {
e.printStackTrace();
return;
}
}
private static String decryptString(byte[] message, Key privateKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] cipherData = cipher.doFinal(message);
return new String(cipherData, "UTF-8");
}
private PrivateKey loadCASPrivateKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
InputStream is = getClass().getResourceAsStream( "/keys/app-private.key" );
if (is == null) {
System.out.println("NULL");
}
byte[] encodedPrivateKey = new byte[(int) 2000];
is.read(encodedPrivateKey);
is.close();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
return privateKey;
}
This works 100% as I would like under my JVM desktop, however when I run it in the Android emulator, I get:
04-24 22: 42: 21.011: I / System.out (1041): k_ * ݣ 93 | @ 04 g) Qk; * Ae # A
oiu: W5@$ w j uSROcx & L w '/ d8uA {4 $ U0 {Ԑt! 9n a 'Jdt2 t TD k + k; GF \ r ڼ>] y + ^ w <" {8R] ZHyuζ 軟 ށ 掱 {A # ȟ
I suppose my problem boils down to coding, but I have been trying all day to figure out that I am really too fixated.
The string is initially encrypted with:
private void test() {
String message="22223334490384903432221";
try {
byte[] encryptedMsg = Base64.encodeBase64(encryptString(message, temp.loadCASPublicKey()));
} catch (Exception e) {
e.printStackTrace();
return;
}
}
private static byte[] encryptString(String message, Key publicKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherData = cipher.doFinal(message.getBytes("UTF-8"));
return cipherData;
}
source
share