Java 类java.security.cert.X509Certificate 实例源码

项目:revolution-irc    文件:ServerCertificateManager.java   
public static String buildCertAppliesToString(X509Certificate cert) {
    List<String> elements = new ArrayList<>();
    try {
        Collection<List<?>> altNames = cert.getSubjectAlternativeNames();
        if (altNames != null) {
            for (List<?> altName : altNames) {
                Integer altNameType = (Integer) altName.get(0);
                if (altNameType != 2 && altNameType != 7) // dns or ip
                    continue;
                elements.add((String) altName.get(1));
            }
        }
    } catch (CertificateParsingException ignored) {
    }

    if (elements.size() == 0)
        return "none";
    return TextUtils.join(",", elements.toArray());
}
项目:azure-libraries-for-java    文件:HostNameSslBindingImpl.java   
private String getCertificateThumbprint(String pfxPath, String password) {
    try {
        InputStream inStream = new FileInputStream(pfxPath);

        KeyStore ks = KeyStore.getInstance("PKCS12");
        ks.load(inStream, password.toCharArray());

        String alias = ks.aliases().nextElement();
        X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
        inStream.close();
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        return BaseEncoding.base16().encode(sha.digest(certificate.getEncoded()));
    } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException ex) {
        throw new RuntimeException(ex);
    }
}
项目:lams    文件:EvaluableX509CertSelectorCredentialCriteria.java   
/** {@inheritDoc} */
public Boolean evaluate(Credential target) {
    if (target == null) {
        log.error("Credential target was null");
        return null;
    }
    if (!(target instanceof X509Credential)) {
        log.info("Credential is not an X509Credential, can not evaluate X509CertSelector criteria");
        return Boolean.FALSE;
    }
    X509Credential x509Cred = (X509Credential) target;

    X509Certificate entityCert = x509Cred.getEntityCertificate();
    if (entityCert == null) {
        log.info("X509Credential did not contain an entity certificate, can not evaluate X509CertSelector criteria");
        return Boolean.FALSE;
    }

    Boolean result = certSelector.match(entityCert);
    return result;
}
项目:revolution-irc    文件:UserOverrideTrustManager.java   
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
    try {
        sDefaultTrustManager.checkServerTrusted(chain, authType);
    } catch (Exception e) {
        try {
            mManager.checkServerTrusted(chain, authType);
        } catch (Exception e2) {
            synchronized (UserOverrideTrustManager.this) {
                if (mTempTrustedCertificates != null && mTempTrustedCertificates.contains(chain[0])) {
                    Log.i(TAG, "A temporarily trusted certificate is being used - trusting the server");
                    return;
                }
            }
            Log.i(TAG, "Unrecognized certificate");
            try {
                X509Certificate cert = chain[0];
                if (!askUser(cert, R.string.certificate_bad_cert).get())
                    throw new UserRejectedCertificateException();
            } catch (InterruptedException | ExecutionException e3) {
                throw new CertificateException("Asking user about the certificate failed");
            }
        }
    }
}
项目:jdk8u-jdk    文件:KeyStore.java   
/**
 * Generates a certificate chain from the collection of
 * certificates and stores the result into a key entry.
 */
private void generateCertificateChain(String alias,
    Collection<? extends Certificate> certCollection)
{
    try
    {
        X509Certificate[] certChain =
            new X509Certificate[certCollection.size()];

        int i = 0;
        for (Iterator<? extends Certificate> iter =
                certCollection.iterator(); iter.hasNext(); i++)
        {
            certChain[i] = (X509Certificate) iter.next();
        }

        storeWithUniqueAlias(alias,
                new KeyEntry(alias, null, certChain));
    }
    catch (Throwable e)
    {
        // Ignore the exception and skip this entry
        // TODO - throw CertificateException?
    }
}
项目:incubator-servicecomb-java-chassis    文件:TestTrustAllManager.java   
@Test
public void testTrustAllManager() throws Exception {
  TrustAllManager manager = new TrustAllManager();
  manager.checkClientTrusted((X509Certificate[]) null, (String) null);
  manager.checkServerTrusted((X509Certificate[]) null, (String) null);

  manager.checkClientTrusted((X509Certificate[]) null,
      (String) null,
      (Socket) null);
  manager.checkClientTrusted((X509Certificate[]) null,
      (String) null,
      (SSLEngine) null);

  manager.checkServerTrusted((X509Certificate[]) null,
      (String) null,
      (Socket) null);
  manager.checkServerTrusted((X509Certificate[]) null,
      (String) null,
      (SSLEngine) null);
  Assert.assertEquals(manager.getAcceptedIssuers() == null, true);
}
项目:cas-server-4.2.1    文件:FileTrustStoreSslSocketFactory.java   
@Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
    for (final X509TrustManager trustManager : trustManagers) {
        try {
            trustManager.checkServerTrusted(chain, authType);
            return;
        } catch (final CertificateException e) {
            LOGGER.debug(e.getMessage(), e);
        }
    }
    throw new CertificateException("None of the TrustManagers trust this certificate chain");
}
项目:dcos-maven-plugin    文件:DcosPluginHelper.java   
@SuppressWarnings("deprecation")
static CloseableHttpClient buildClient(boolean ignoreSSL) throws Exception {
  SSLSocketFactory sslsf = new SSLSocketFactory(new TrustStrategy() {

    public boolean isTrusted(
        final X509Certificate[] chain, String authType) throws CertificateException {
      // Oh, I am easy...
      return true;
    }

  });
  if (ignoreSSL) {
    return HttpClients.custom().setSSLSocketFactory(sslsf).build();
  } else {
    return HttpClients.createDefault();
  }
}
项目:java-buildpack-security-provider    文件:DelegatingX509ExtendedKeyManager.java   
@Override
public X509Certificate[] getCertificateChain(final String s) {
    return with(new Function<X509Certificate[]>() {

        @Override
        public X509Certificate[] apply(X509ExtendedKeyManager delegate) {
            return delegate.getCertificateChain(s);
        }

    });
}
项目:SecuritySample    文件:ExtendedKeyUsageImpl.java   
public ExtendedKeyUsageImpl(X509Certificate cert) throws IOException {
    keyPurposeIds = new ArrayList<>();
    byte[] extVal = cert.getExtensionValue(Extension.extendedKeyUsage.getId());
    if (extVal == null)
        return;
    org.bouncycastle.asn1.x509.ExtendedKeyUsage usage = org.bouncycastle.asn1.x509.ExtendedKeyUsage
            .getInstance(X509ExtensionUtil.fromExtensionValue(extVal));
    KeyPurposeId[] usages = usage.getUsages();
    for (int i = 0; i < usages.length; i++) {
        keyPurposeIds.add(usages[i].getId());
    }
}
项目:installcert    文件:InstallCert.java   
public static String getCommonName(X509Certificate cert)
        throws InvalidNameException {
    // use LDAP API to parse the certifiate Subject :)
    // see http://stackoverflow.com/a/7634755/972463
    LdapName ldapDN
            = new LdapName(cert.getSubjectX500Principal().getName());
    String cn = "";
    for (Rdn rdn : ldapDN.getRdns()) {
        if (rdn.getType().equals("CN")) {
            cn = rdn.getValue().toString();
        }
    }
    return cn;
}
项目:SecuritySample    文件:BasicConstraintsImpl.java   
public BasicConstraintsImpl(X509Certificate cert) throws CertificateException, IOException {
    byte[] extVal = cert.getExtensionValue(Extension.basicConstraints.getId());
    if (extVal == null)
        return;
    org.bouncycastle.asn1.x509.BasicConstraints bc = org.bouncycastle.asn1.x509.BasicConstraints
            .getInstance(X509ExtensionUtil.fromExtensionValue(extVal));
    isCA = bc.isCA();
    pathLen = bc.getPathLenConstraint();
}
项目:openjdk-jdk10    文件:RetrievalMethodResolver.java   
/**
 * Retrieves a x509Certificate from the given information
 * @param e
 * @param baseURI
 * @param storage
 * @return
 * @throws KeyResolverException
 */
private static X509Certificate resolveCertificate(
    Element e, String baseURI, StorageResolver storage
) throws KeyResolverException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}"
            + e.getLocalName() + " Element");
    }
    // An element has been provided
    if (e != null) {
        return KeyResolver.getX509Certificate(e, baseURI, storage);
    }
    return null;
}
项目:jdk8u-jdk    文件:X509IssuerSerialResolver.java   
/** @inheritDoc */
public PublicKey engineLookupAndResolvePublicKey(
    Element element, String baseURI, StorageResolver storage
) throws KeyResolverException {

    X509Certificate cert =
        this.engineLookupResolveX509Certificate(element, baseURI, storage);

    if (cert != null) {
        return cert.getPublicKey();
    }

    return null;
}
项目:cas-5.1.0    文件:X509SerialNumberPrincipalResolverTests.java   
@Test
public void verifyHexPrincipalEven() {
    final X509SerialNumberPrincipalResolver r = new X509SerialNumberPrincipalResolver(16, true);
    final X509Certificate mockCert = mock(X509Certificate.class);
    when(mockCert.getSerialNumber()).thenReturn(BigInteger.valueOf(60300L));

    final String principal = r.resolvePrincipalInternal(mockCert);
    assertEquals("eb8c", principal);
}
项目:ipack    文件:AttributeCertificateIssuer.java   
public boolean match(Object obj)
{
    if (!(obj instanceof X509Certificate))
    {
        return false;
    }

    return match((Certificate)obj);
}
项目:springboot-shiro-cas-mybatis    文件:FileTrustStoreSslSocketFactory.java   
@Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
    for (final X509TrustManager trustManager : trustManagers) {
        try {
            trustManager.checkServerTrusted(chain, authType);
            return;
        } catch (final CertificateException e) {
            LOGGER.debug(e.getMessage(), e);
        }
    }
    throw new CertificateException("None of the TrustManagers trust this certificate chain");
}
项目:openjdk-jdk10    文件:ConstraintsChecker.java   
/**
 * Internal method to check the name constraints against a cert
 */
private void verifyNameConstraints(X509Certificate currCert)
    throws CertPathValidatorException
{
    String msg = "name constraints";
    if (debug != null) {
        debug.println("---checking " + msg + "...");
    }

    // check name constraints only if there is a previous name constraint
    // and either the currCert is the final cert or the currCert is not
    // self-issued
    if (prevNC != null && ((i == certPathLength) ||
            !X509CertImpl.isSelfIssued(currCert))) {
        if (debug != null) {
            debug.println("prevNC = " + prevNC +
                ", currDN = " + currCert.getSubjectX500Principal());
        }

        try {
            if (!prevNC.verify(currCert)) {
                throw new CertPathValidatorException(msg + " check failed",
                    null, null, -1, PKIXReason.INVALID_NAME);
            }
        } catch (IOException ioe) {
            throw new CertPathValidatorException(ioe);
        }
    }

    // merge name constraints regardless of whether cert is self-issued
    prevNC = mergeNameConstraints(currCert, prevNC);

    if (debug != null)
        debug.println(msg + " verified.");
}
项目:OpenJSharp    文件:X509CertPath.java   
/**
 * Encode the CertPath using PKIPATH format.
 *
 * @return a byte array containing the binary encoding of the PkiPath object
 * @exception CertificateEncodingException if an exception occurs
 */
private byte[] encodePKIPATH() throws CertificateEncodingException {

    ListIterator<X509Certificate> li = certs.listIterator(certs.size());
    try {
        DerOutputStream bytes = new DerOutputStream();
        // encode certs in reverse order (trust anchor to target)
        // according to PkiPath format
        while (li.hasPrevious()) {
            X509Certificate cert = li.previous();
            // check for duplicate cert
            if (certs.lastIndexOf(cert) != certs.indexOf(cert)) {
                throw new CertificateEncodingException
                    ("Duplicate Certificate");
            }
            // get encoded certificates
            byte[] encoded = cert.getEncoded();
            bytes.write(encoded);
        }

        // Wrap the data in a SEQUENCE
        DerOutputStream derout = new DerOutputStream();
        derout.write(DerValue.tag_SequenceOf, bytes);
        return derout.toByteArray();

    } catch (IOException ioe) {
       throw new CertificateEncodingException("IOException encoding " +
               "PkiPath data: " + ioe, ioe);
    }
}
项目:Websocket-Smart-Card-Signer    文件:X509Utils.java   
public static ArrayList<String> getDistributionPointUrls(X509Certificate cert){

    ArrayList<String> ret = new ArrayList<String>();

    try{
        String data = cert.toString();

        if(data.indexOf("CRLDistributionPoints") == -1)
            return ret;

        data = data.substring(data.indexOf("CRLDistributionPoints"));
        data = data.substring(0, data.indexOf("]]") + 2);

        while(data.indexOf("URIName") != -1){
            data = data.substring(data.indexOf("URIName") + 9);

            String url = data.substring(0, data.indexOf("]"));

            if(url.contains(", URIName: ")){
                String[] urlTmpList = url.split(", URIName: ");
                for(String urlTmp:urlTmpList)
                    ret.add(urlTmp);
            }else
                ret.add(url);

            data = data.substring(data.indexOf("]") + 1);
        }
    }catch(Exception ex){ex.printStackTrace();}

    return ret;
}
项目:springboot-shiro-cas-mybatis    文件:FileTrustStoreSslSocketFactory.java   
@Override
public X509Certificate[] getAcceptedIssuers() {
    final List<X509Certificate> certificates = new ArrayList<>();
    for (final X509TrustManager trustManager : trustManagers) {
        final List<X509Certificate> list = Arrays.asList(trustManager.getAcceptedIssuers());
        certificates.addAll(list);
    }
    return certificates.toArray(new X509Certificate[] {});
}
项目:verify-matching-service-adapter    文件:FixedCertificateChainValidatorTest.java   
@Test
public void validate_shouldFailACertSignedByAnUnknownRootCACert() throws Exception {
    final X509Certificate otherChildCertificate =
            certificateFactory.createCertificate(childSignedByOtherRootCAString);

    assertExceptionMessage(
            certificateChainValidator,
            otherChildCertificate,
            CertificateChainValidationException.class,
            "Certificate is not valid: O=other_server, CN=localhost"
    );
}
项目:IJPay    文件:CertUtil.java   
/**
     * 检查证书链
     * 
     * @param rootCerts
     *            根证书
     * @param cert
     *            待验证的证书
     * @return
     */
    public static boolean verifyCertificate(X509Certificate cert) {

        if ( null == cert) {
            LogUtil.writeErrorLog("cert must Not null");
            return false;
        }
        try {
            cert.checkValidity();//验证有效期
//          cert.verify(middleCert.getPublicKey());
            if(!verifyCertificateChain(cert)){
                return false;
            }
        } catch (Exception e) {
            LogUtil.writeErrorLog("verifyCertificate fail", e);
            return false;
        }

        if(SDKConfig.getConfig().isIfValidateCNName()){
            // 验证公钥是否属于银联
            if(!UNIONPAY_CNNAME.equals(CertUtil.getIdentitiesFromCertficate(cert))) {
                LogUtil.writeErrorLog("cer owner is not CUP:" + CertUtil.getIdentitiesFromCertficate(cert));
                return false;
            }
        } else {
            // 验证公钥是否属于银联
            if(!UNIONPAY_CNNAME.equals(CertUtil.getIdentitiesFromCertficate(cert)) 
                    && !"00040000:SIGN".equals(CertUtil.getIdentitiesFromCertficate(cert))) {
                LogUtil.writeErrorLog("cer owner is not CUP:" + CertUtil.getIdentitiesFromCertficate(cert));
                return false;
            }
        }
        return true;        
    }
项目:jdk8u-jdk    文件:X509CertPath.java   
/**
 * Encode the CertPath using PKIPATH format.
 *
 * @return a byte array containing the binary encoding of the PkiPath object
 * @exception CertificateEncodingException if an exception occurs
 */
private byte[] encodePKIPATH() throws CertificateEncodingException {

    ListIterator<X509Certificate> li = certs.listIterator(certs.size());
    try {
        DerOutputStream bytes = new DerOutputStream();
        // encode certs in reverse order (trust anchor to target)
        // according to PkiPath format
        while (li.hasPrevious()) {
            X509Certificate cert = li.previous();
            // check for duplicate cert
            if (certs.lastIndexOf(cert) != certs.indexOf(cert)) {
                throw new CertificateEncodingException
                    ("Duplicate Certificate");
            }
            // get encoded certificates
            byte[] encoded = cert.getEncoded();
            bytes.write(encoded);
        }

        // Wrap the data in a SEQUENCE
        DerOutputStream derout = new DerOutputStream();
        derout.write(DerValue.tag_SequenceOf, bytes);
        return derout.toByteArray();

    } catch (IOException ioe) {
       throw new CertificateEncodingException("IOException encoding " +
               "PkiPath data: " + ioe, ioe);
    }
}
项目:OutsourcedProject    文件:HttpUtil.java   
@Override
public void checkClientTrusted(X509Certificate certificates[],
                               String authType) throws CertificateException {
    if (this.certificates == null) {
        this.certificates = certificates;
        log.info("init at checkClientTrusted");
    }


}
项目:ARCLib    文件:CertificateDecoder.java   
public X509Certificate decode(String certStr) {
    try {
        byte[] decoded = Base64.getDecoder().decode(certStr);

        return (X509Certificate)factory.generateCertificate(new ByteArrayInputStream(decoded));
    } catch (IllegalArgumentException | CertificateException e) {
        log.warn("Failed to decode certificate {}.", certStr);
        return null;
    }
}
项目:aos-FileCoreLibrary    文件:FTPSTrustManager.java   
public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException
{
    for (X509Certificate certificate : certificates)
    {
        certificate.checkValidity();
    }
}
项目:springboot-shiro-cas-mybatis    文件:PoolingLdaptiveResourceCRLFetcherTests.java   
@Test
public void getCrlFromLdapWithNoCaching() throws Exception {
    for (int i = 0; i < 10; i++) {
        CacheManager.getInstance().removeAllCaches();
        final Cache cache = new Cache("crlCache-1", 100, false, false, 20, 10);
        CacheManager.getInstance().addCache(cache);
        final CRLDistributionPointRevocationChecker checker = new CRLDistributionPointRevocationChecker(cache, fetcher);
        checker.setThrowOnFetchFailure(true);
        checker.setUnavailableCRLPolicy(new AllowRevocationPolicy());
        final X509Certificate cert = CertUtils.readCertificate(new ClassPathResource("ldap-crl.crt"));
        checker.check(cert);
    }
}
项目:Java_CTe    文件:Assinatura.java   
private static void loadCertificates(XMLSignatureFactory signatureFactory) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException, NoSuchProviderException, CertificateException, IOException, CertificadoException {

        Certificado certificado = configuracoesCte.getCertificado();
        KeyStore keyStore = CertificadoService.getKeyStore(certificado);
        KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(certificado.getNome(), new KeyStore.PasswordProtection(certificado.getSenha().toCharArray()));
        privateKey = pkEntry.getPrivateKey();

        KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
        List<X509Certificate> x509Content = new ArrayList<X509Certificate>();

        x509Content.add(CertificadoService.getCertificate(certificado, keyStore));
        X509Data x509Data = keyInfoFactory.newX509Data(x509Content);
        keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data));
    }
项目:lams    文件:KeyInfoHelper.java   
/**
 * Build an {@link X509Digest} containing the digest of the specified certificate.
 * 
 * @param javaCert the Java X509Certificate to digest
 * @param algorithmURI  digest algorithm URI
 * @return a new X509Digest object
 * @throws NoSuchAlgorithmException if the algorithm specified cannot be used
 * @throws CertificateEncodingException if the certificate cannot be encoded
 */
public static X509Digest buildX509Digest(X509Certificate javaCert, String algorithmURI)
        throws NoSuchAlgorithmException, CertificateEncodingException {

    String jceAlg = SecurityHelper.getAlgorithmIDFromURI(algorithmURI);
    if (jceAlg == null) {
        throw new NoSuchAlgorithmException("No JCE algorithm found for " + algorithmURI);
    }
    MessageDigest md = MessageDigest.getInstance(jceAlg);
    byte[] hash = md.digest(javaCert.getEncoded());

    X509Digest xmlDigest = (X509Digest) Configuration.getBuilderFactory()
        .getBuilder(X509Digest.DEFAULT_ELEMENT_NAME)
        .buildObject(X509Digest.DEFAULT_ELEMENT_NAME);
    xmlDigest.setAlgorithm(algorithmURI);
    xmlDigest.setValue(Base64.encodeBytes(hash));

    return xmlDigest;
}
项目:verify-hub    文件:ConfigServiceKeyStore.java   
private void validate(final X509Certificate certificate, final KeyStore trustStore) {
    CertificateValidity certificateValidity = certificateChainValidator.validate(certificate, trustStore);
    if (!certificateValidity.isValid()) {
        throw new CertificateChainValidationException(
                format("Certificate is not valid: {0}", getDnForCertificate(certificate)),
                certificateValidity.getException().get());
    }
}
项目:okhttpUtil    文件:HttpsUtil.java   
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
    // TODO Auto-generated method stub
        try
        {
            defaultTrustManager.checkServerTrusted(arg0, arg1);
        } catch (CertificateException ce)
        {
            localTrustManager.checkServerTrusted(arg0, arg1);
        }
}
项目:ARCLib    文件:PathCertificateFilter.java   
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
    X509Certificate cert = extractClientCertificate(request);

    if (cert == null) {
        return null;
    }

    return principalExtractor.extractPrincipal(cert);
}
项目:zabbkit-android    文件:LoginActivity.java   
@Override
public void onCertificateRequest(final X509Certificate[] certificate) {
    dismissDialog();
    if (certificate == null) {
        performLogin();
    } else {
        DialogHelper.showSslDialog(LoginActivity.this,
                certificate, LoginActivity.this);
    }

}
项目:jdk8u-jdk    文件:BasicChecker.java   
/**
 * Internal method to check that cert has a valid DN to be next in a chain
 */
private void verifyNameChaining(X509Certificate cert)
    throws CertPathValidatorException
{
    if (prevSubject != null) {

        String msg = "subject/issuer name chaining";
        if (debug != null)
            debug.println("---checking " + msg + "...");

        X500Principal currIssuer = cert.getIssuerX500Principal();

        // reject null or empty issuer DNs
        if (X500Name.asX500Name(currIssuer).isEmpty()) {
            throw new CertPathValidatorException
                (msg + " check failed: " +
                 "empty/null issuer DN in certificate is invalid", null,
                 null, -1, PKIXReason.NAME_CHAINING);
        }

        if (!(currIssuer.equals(prevSubject))) {
            throw new CertPathValidatorException
                (msg + " check failed", null, null, -1,
                 PKIXReason.NAME_CHAINING);
        }

        if (debug != null)
            debug.println(msg + " verified.");
    }
}
项目:openjdk-jdk10    文件:SSLServerCertStore.java   
private static List<X509Certificate> getMatchingCerts
    (List<X509Certificate> certs, CertSelector selector)
{
    // if selector not specified, all certs match
    if (selector == null) {
        return certs;
    }
    List<X509Certificate> matchedCerts = new ArrayList<>(certs.size());
    for (X509Certificate cert : certs) {
        if (selector.match(cert)) {
            matchedCerts.add(cert);
        }
    }
    return matchedCerts;
}
项目:https-github.com-apache-zookeeper    文件:X509AuthTest.java   
@Test
public void testTrustedAuth() {
    X509AuthenticationProvider provider = createProvider(clientCert);
    MockServerCnxn cnxn = new MockServerCnxn();
    cnxn.clientChain = new X509Certificate[] { clientCert };
    Assert.assertEquals(KeeperException.Code.OK, provider.handleAuthentication(cnxn, null));
}
项目:atlas    文件:LocalSignedJarBuilder.java   
/**
 * Creates a {@link SignedJarBuilder} with a given output stream, and signing information.
 * <p/>If either <code>key</code> or <code>certificate</code> is <code>null</code> then
 * the archive will not be signed.
 *
 * @param out         the {@link OutputStream} where to write the Jar archive.
 * @param key         the {@link PrivateKey} used to sign the archive, or <code>null</code>.
 * @param certificate the {@link X509Certificate} used to sign the archive, or
 *                    <code>null</code>.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
public LocalSignedJarBuilder(@NonNull OutputStream out,
                             @Nullable PrivateKey key,
                             @Nullable X509Certificate certificate,
                             @Nullable String builtBy,
                             @Nullable String createdBy,
                             @Nullable String signFile) throws IOException, NoSuchAlgorithmException {
    mOutputJar = new JarOutputStream(new BufferedOutputStream(out));
    mOutputJar.setLevel(9);
    mKey = key;
    mCertificate = certificate;
    mSignFile = signFile;

    if (mKey != null && mCertificate != null) {
        mManifest = new Manifest();
        Attributes main = mManifest.getMainAttributes();
        main.putValue("Manifest-Version", "1.0");
        if (builtBy != null) {
            main.putValue("Built-By", builtBy);
        }
        if (createdBy != null) {
            main.putValue("Created-By", createdBy);
        }

        mMessageDigest = MessageDigest.getInstance(DIGEST_ALGORITHM);
    }
}
项目:FApkSigner    文件:ApkSigner.java   
/**
 * Constructs a new {@code Builder}.
 *
 * @param name signer's name. The name is reflected in the name of files comprising the
 *        JAR signature of the APK.
 * @param privateKey signing key
 * @param certificates list of one or more X.509 certificates. The subject public key of
 *        the first certificate must correspond to the {@code privateKey}.
 */
public Builder(
        String name,
        PrivateKey privateKey,
        List<X509Certificate> certificates) {
    if (name.isEmpty()) {
        throw new IllegalArgumentException("Empty name");
    }
    mName = name;
    mPrivateKey = privateKey;
    mCertificates = new ArrayList<>(certificates);
}
项目:mobile-store    文件:IndexV1Updater.java   
/**
 * Verify that the signing certificate used to sign {@link #SIGNED_FILE_NAME}
 * matches the signing stored in the database for this repo.  {@link #repo} and
 * {@code repo.signingCertificate} must be pre-loaded from the database before
 * running this, if this is an existing repo.  If the repo does not exist,
 * this will run the TOFU process.
 * <p>
 * Index V1 works with two copies of the signing certificate:
 * <li>in the downloaded jar</li>
 * <li>stored in the local database</li>
 * <p>
 * A new repo can be added with or without the fingerprint of the signing
 * certificate.  If no fingerprint is supplied, then do a pure TOFU and just
 * store the certificate as valid.  If there is a fingerprint, then first
 * check that the signing certificate in the jar matches that fingerprint.
 * <p>
 * This is also responsible for adding the {@link Repo} instance to the
 * database for the first time.
 * <p>
 * This is the same as {@link RepoUpdater#verifyCerts(String, X509Certificate)},
 * {@link RepoUpdater#verifyAndStoreTOFUCerts(String, X509Certificate)}, and
 * {@link RepoUpdater#assertSigningCertFromXmlCorrect()} except there is no
 * embedded copy of the signing certificate in the index data.
 *
 * @param rawCertFromJar the {@link X509Certificate} embedded in the downloaded jar
 * @see RepoUpdater#verifyAndStoreTOFUCerts(String, X509Certificate)
 * @see RepoUpdater#verifyCerts(String, X509Certificate)
 * @see RepoUpdater#assertSigningCertFromXmlCorrect()
 */
private void verifySigningCertificate(X509Certificate rawCertFromJar) throws SigningException {
    String certFromJar = Hasher.hex(rawCertFromJar);

    if (TextUtils.isEmpty(certFromJar)) {
        throw new SigningException(repo,
                SIGNED_FILE_NAME + " must have an included signing certificate!");
    }

    if (repo.signingCertificate == null) {
        if (repo.fingerprint != null) {
            String fingerprintFromJar = Utils.calcFingerprint(rawCertFromJar);
            if (!repo.fingerprint.equalsIgnoreCase(fingerprintFromJar)) {
                throw new SigningException(repo,
                        "Supplied certificate fingerprint does not match!");
            }
        }
        Utils.debugLog(TAG, "Saving new signing certificate to database for " + repo.address);
        ContentValues values = new ContentValues(2);
        values.put(Schema.RepoTable.Cols.LAST_UPDATED, Utils.formatDate(new Date(), ""));
        values.put(Schema.RepoTable.Cols.SIGNING_CERT, Hasher.hex(rawCertFromJar));
        RepoProvider.Helper.update(context, repo, values);
        repo.signingCertificate = certFromJar;
    }

    if (TextUtils.isEmpty(repo.signingCertificate)) {
        throw new SigningException(repo, "A empty repo signing certificate is invalid!");
    }

    if (repo.signingCertificate.equals(certFromJar)) {
        return; // we have a match!
    }

    throw new SigningException(repo, "Signing certificate does not match!");
}