Search code examples
javaandroidencryptionx509

How to encrypt using a X509 public cert with Android?


I am trying to encrypt a text file using a .pfx certificate file using :

public void EncryptUsingPublicKey(File in, File out, File publicKeyFile) throws IOException, GeneralSecurityException {

    byte[] encodedKey = new byte[(int)publicKeyFile.length()];
    new FileInputStream(publicKeyFile).read(encodedKey);

    // create public key
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey pk = kf.generatePublic(publicKeySpec);

    FileInputStream is = new FileInputStream(in);
    Cipher pkCipher = Cipher.getInstance("RSA");
    pkCipher.init(Cipher.ENCRYPT_MODE, pk);
    CipherOutputStream os = new CipherOutputStream(new FileOutputStream(out), pkCipher);
    copy(is, os);
    os.close();
}

I have two problems:

  1. Where should I store the .pfx file on the device?
  2. Is this function correct?

Solution

  • I don't think that your code will work. PFX files are internally AFAIR PKCS#12 files with can contain multiple certificates and keys. The X509EncodedKeySpec you are using requires to have exactly one certificate in a .CER file (DER/binary format).

    Therefore you have the following two options:

    1. Extract the certificate from the PFX file as CER file (e.g. with the GUI tool portecle) or
    2. Try to read the PFX file as a PKCS#12 KeyStore at it is presented here: PKCS12 Java Keystore from CA and User certificate in java

    In the end you can include the PFX/CER file as resource into your andoid app: Load file from resource