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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.