1
public static String encryptByPublicKey(byte[] data, String key)
        throws Exception {

    byte[] keyBytes = decryptBASE64(key);

    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    Key publicKey = keyFactory.generatePublic(x509KeySpec);

    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);

    return new String(cipher.doFinal(data));
}

I have a public key, like MFWww.........EAAQ==. When I pass the string to that argument, the encrypted message is some unknown characters. Therefore I suspect I should do something on the key before passing it to the function. But I don't how could I make it. So see anyone can help.

Thank you

1
  • See BouncyCastle and Jasypt libraries, but I'm not sure if you will be able to use them on android Commented May 14, 2015 at 9:26

1 Answer 1

2

Never, ever, ever pass arbitrary binary data to the String constructor. You don't have encoded text, you have arbitrary bytes. That's not what the String constructor is for.

Ideally, don't represent the binary data as text at all - but if you have to, do so using base64 or hex, which will encode arbitrary binary data in ASCII.

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.