0

I am using this (Android: decrypt RSA text using a Public key stored in a file) as a guideline to encrypt a "string" using a public key and then decrypting with private key in ruby.

However, I am having difficulty. Part of the reason is that I am encrypting the bytes in Java and then when I am decrypting in Ruby I am not translating it. I am attaching the Android snippet below:

        // reads the public key stored in a file
    AssetManager am = mContext.getAssets();
    InputStream is = am.open("public_key.pem");     
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    List<String> lines = new ArrayList<String>();
    String line = null;
    while ((line = br.readLine()) != null)
        lines.add(line);

    // removes the first and last lines of the file (comments)
    if (lines.size() > 1 && lines.get(0).startsWith("-----") && lines.get(lines.size()-1).startsWith("-----")) {
        lines.remove(0);
        lines.remove(lines.size()-1);
    }

    // concats the remaining lines to a single String
    StringBuilder sb = new StringBuilder();
    for (String aLine: lines)
        sb.append(aLine);
    String keyString = sb.toString();

    // converts the String to a PublicKey instance
    byte[] keyBytes = Base64.decode(keyString.getBytes("utf-8"), 0);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey key = keyFactory.generatePublic(spec);

    //byte[] encryptedText = null;
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    String encryptedText = Base64.encodeToString(cipher.doFinal(message), 0);

   return encryptedText;

I am using following code in ruby to try and decode the encrypted data

pkey = OpenSSL::PKey::RSA.new private_key
print pkey.private_decrypt(Base64.decode64(android_encrypted_value))

I noticed a problem right away when testing that the base64 values generated in Java doesnt match the ones I generated in another code in ruby. Any idea?

Community
  • 1
  • 1
user1647708
  • 447
  • 3
  • 9
  • 22

1 Answers1

0

The following change worked for me:

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING"); 
cipher.init(Cipher.ENCRYPT_MODE, key); 
String encryptedText = Base64.encodeToString(cipher.doFinal(message), Base64.DEFAULT);

I was able to apply this to my Ruby code and make it work.

user1647708
  • 447
  • 3
  • 9
  • 22