Android Studio不会读取.pfx证书来签署应用

时间:2020-03-08 14:21:24

标签: java android certificate pfx

我想使用.pfx A1证书为我的应用程序签名一个字符串,但是Android Studio无法读取该文件。 下面的迭代*在Netbeans上可以正常运行,但是在Android Studio中返回false,因为它根本没有读取.pfx文件。听说必须将其转换为.JKS格式,但是我不确定。

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;        
    }

0 个答案:

没有答案