• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

How to open and read a .pfx file?

Tito Schmidt

Lurker
Mar 8, 2020
1
0
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);
}


//Keystore

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.initSign(kPair.getPrivate());
signatureProvider.initSign(pk);
signatureProvider.update(buffer, 0, buffer.length);
byte[] signature = signatureProvider.sign();
signedString = Base64.getEncoder().encodeToString(signature);
return signedString;
}
 
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! :)
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones