Preciso assinar uma String contendo a Chave da NFe usando um app feito no Android Studio através de um Certificado A1 (arquivo .pfx). Consegui abri-lo, mas ao contrário do Netbeans, o Android Studio não está lendo-o. A leitura é feita no laço de iteração while() para eu pegar o alias necessário para obter a chave primária e fazer a assinatura. Mas o laço retorna falso, como se estivesse vazio, sem propriedade nenhuma. Ou seja, abre o arquivo .pfx mas não lê. O que devo fazer?aliases.hasMoreElements()
public String assinarChave(String input) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, KeyStoreException, IOException, CertificateException, UnrecoverableEntryException {
InputStream certificado;
char[] senha = null;
KeyStore keystore = null;
Enumeration aliases;
String alias = “”;
//Abrir o Certificado
certificado = getClass().getResourceAsStream(“imediata.pfx”);
senha = “1234”.toCharArray();
keystore = KeyStore.getInstance(“PKCS12”);
keystore.load(certificado, senha);
//Pegar o alias
KeyStore.PrivateKeyEntry pkEntry = null;
PrivateKey pk = null;
try {
aliases = keystore.aliases();
while(aliases.hasMoreElements()) {
alias = aliases.nextElement();
if (keystore.isKeyEntry(alias)) {
pkEntry = (KeyStore.PrivateKeyEntry) keystore.getEntry(alias, new
KeyStore.PasswordProtection(senha));
pk = pkEntry.getPrivateKey();
}
}
} catch (KeyStoreException e) {
throw new RuntimeException(“CATCH”, e);
}
//Keystore
Key key = (PrivateKey) keystore.getKey(alias, senha);
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()); // Sua Key
signatureProvider.initSign(pk);
signatureProvider.update(buffer, 0, buffer.length);
byte[] signature = signatureProvider.sign();
String encoded = Base64.getEncoder().encodeToString(signature);
return encoded;
}