1. Are you ready for the Galaxy S20? Here is everything we know so far!

How to open and read a .pfx file?

Discussion in 'Android Development' started by Tito Schmidt, Mar 8, 2020.

  1. Tito Schmidt

    Tito Schmidt Lurker
    Thread Starter

    I want to sign a String for my app using a .pfx A1 Certificate but Android Studio isn't reading the file. The iteration below* works on Netbeans just fine but in Android Studio returns false as it was not reading the .pfx file at all.

    public String signApp(String input) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, KeyStoreException, IOException, CertificateException, UnrecoverableEntryException {
    String signedString = "";
    InputStream certificado;
    char[] password = null;
    KeyStore keystore = null;
    Enumeration<String> aliases;
    String alias = "";
    //Open the .pfx file
    certificado = getClass().getResourceAsStream("imediata.pfx");

    password = "1234".toCharArray();
    keystore = KeyStore.getInstance("PKCS12");
    keystore.load(certificado, password );
    //Get the alias
    KeyStore.PrivateKeyEntry pkEntry = null;
    PrivateKey pk = null;
    try {
    aliases = keystore.aliases();
    while(aliases.hasMoreElements()) { //* problem: it's returning false as it not reading at
    // all!!
    alias = aliases.nextElement();
    if (keystore.isKeyEntry(alias)) {
    pkEntry = (KeyStore.PrivateKeyEntry) keystore.getEntry(alias, new
    KeyStore.PasswordProtection(password ));
    pk = pkEntry.getPrivateKey();
    } catch (KeyStoreException e) {
    throw new RuntimeException("CATCH", e);


    Key key = (PrivateKey) keystore.getKey(alias, password );
    java.security.cert.Certificate cert = keystore.getCertificate(alias);
    PublicKey publicKey = cert.getPublicKey();
    KeyPair kPair = new KeyPair(publicKey, (PrivateKey) key);

    byte[] buffer = chave.getBytes();
    // Signature
    Signature signatureProvider = Signature.getInstance("SHA1withRSA");
    signatureProvider.update(buffer, 0, buffer.length);
    byte[] signature = signatureProvider.sign();
    signedString = Base64.getEncoder().encodeToString(signature);
    return signedString;

    1. Download the Forums for Android™ app!


  2. MoodyBlues

    MoodyBlues Compassion is cool!
    VIP Member

    Welcome to Android Forums, Tito Schmidt!

    You're most likely to get help with this problem by posting on our Android Development board. Your fellow app developers hang out there! We can have this thread moved, or you can just copy/paste from this one.

    One suggestion: use the 'code' tag to contain your code--it makes for neater, shorter posts.

    Good luck with your project! :)

Share This Page