Search in sources :

Example 91 with Certificate

use of com.android.apksig.internal.x509.Certificate in project snowflake-jdbc by snowflakedb.

the class SFTrustManager method validateRevocationStatus.

/**
 * Certificate Revocation checks
 *
 * @param chain chain of certificates attached.
 * @param peerHost Hostname of the server
 * @throws CertificateException if any certificate validation fails
 */
void validateRevocationStatus(X509Certificate[] chain, String peerHost) throws CertificateException {
    final List<Certificate> bcChain = convertToBouncyCastleCertificate(chain);
    final List<SFPair<Certificate, Certificate>> pairIssuerSubjectList = getPairIssuerSubject(bcChain);
    if (peerHost.startsWith("ocspssd")) {
        return;
    }
    if (ocspCacheServer.new_endpoint_enabled) {
        ocspCacheServer.resetOCSPResponseCacheServer(peerHost);
    }
    setOCSPResponseCacheServerURL();
    boolean isCached = isCached(pairIssuerSubjectList);
    if (useOCSPResponseCacheServer() && !isCached) {
        if (!ocspCacheServer.new_endpoint_enabled) {
            LOGGER.debug("Downloading OCSP response cache from the server. URL: {}", SF_OCSP_RESPONSE_CACHE_SERVER_URL_VALUE);
        } else {
            LOGGER.debug("Downloading OCSP response cache from the server. URL: {}", ocspCacheServer.SF_OCSP_RESPONSE_CACHE_SERVER);
        }
        try {
            readOcspResponseCacheServer();
        } catch (SFOCSPException ex) {
            LOGGER.debug("Error downloading OCSP Response from cache server : {}." + "OCSP Responses will be fetched directly from the CA OCSP" + "Responder ", ex.getMessage());
        }
    // if the cache is downloaded from the server, it should be written
    // to the file cache at all times.
    }
    executeRevocationStatusChecks(pairIssuerSubjectList, peerHost);
    if (WAS_CACHE_UPDATED.getAndSet(false)) {
        JsonNode input = encodeCacheToJSON();
        fileCacheManager.writeCacheFile(input);
    }
}
Also used : JsonNode(com.fasterxml.jackson.databind.JsonNode) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate) SFPair(net.snowflake.client.util.SFPair)

Example 92 with Certificate

use of com.android.apksig.internal.x509.Certificate in project snowflake-jdbc by snowflakedb.

the class SFTrustManager method createRequest.

/**
 * Creates a OCSP Request
 *
 * @param pairIssuerSubject a pair of issuer and subject certificates
 * @return OCSPReq object
 */
private OCSPReq createRequest(SFPair<Certificate, Certificate> pairIssuerSubject) throws IOException {
    Certificate issuer = pairIssuerSubject.left;
    Certificate subject = pairIssuerSubject.right;
    OCSPReqBuilder gen = new OCSPReqBuilder();
    try {
        DigestCalculator digest = new SHA1DigestCalculator();
        X509CertificateHolder certHolder = new X509CertificateHolder(issuer.getEncoded());
        CertificateID certId = new CertificateID(digest, certHolder, subject.getSerialNumber().getValue());
        gen.addRequest(certId);
        return gen.build();
    } catch (OCSPException ex) {
        throw new IOException("Failed to build a OCSPReq.", ex);
    }
}
Also used : X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) DigestCalculator(org.bouncycastle.operator.DigestCalculator) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate)

Example 93 with Certificate

use of com.android.apksig.internal.x509.Certificate in project apksig by venshine.

the class X509CertificateUtils method generateCertificate.

/**
 * Generates an {@code X509Certificate} from the encoded form using the provided
 * {@code CertificateFactory}.
 *
 * @throws CertificateException if the encodedForm cannot be decoded to a valid certificate.
 */
public static X509Certificate generateCertificate(byte[] encodedForm, CertificateFactory certFactory) throws CertificateException {
    X509Certificate certificate;
    try {
        certificate = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(encodedForm));
        return certificate;
    } catch (CertificateException e) {
    // This could be expected if the certificate is encoded using a BER encoding that does
    // not use the minimum number of bytes to represent the length of the contents; attempt
    // to decode the certificate using the BER parser and re-encode using the DER encoder
    // below.
    }
    try {
        // Some apps were previously signed with a BER encoded certificate that now results
        // in exceptions from the CertificateFactory generateCertificate(s) methods. Since
        // the original BER encoding of the certificate is used as the signature for these
        // apps that original encoding must be maintained when signing updated versions of
        // these apps and any new apps that may require capabilities guarded by the
        // signature. To maintain the same signature the BER parser can be used to parse
        // the certificate, then it can be re-encoded to its DER equivalent which is
        // accepted by the generateCertificate method. The positions in the ByteBuffer can
        // then be used with the GuaranteedEncodedFormX509Certificate object to ensure the
        // getEncoded method returns the original signature of the app.
        ByteBuffer encodedCertBuffer = getNextDEREncodedCertificateBlock(ByteBuffer.wrap(encodedForm));
        int startingPos = encodedCertBuffer.position();
        Certificate reencodedCert = Asn1BerParser.parse(encodedCertBuffer, Certificate.class);
        byte[] reencodedForm = Asn1DerEncoder.encode(reencodedCert);
        certificate = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(reencodedForm));
        // If the reencodedForm is successfully accepted by the CertificateFactory then copy the
        // original encoding from the ByteBuffer and use that encoding in the Guaranteed object.
        byte[] originalEncoding = new byte[encodedCertBuffer.position() - startingPos];
        encodedCertBuffer.position(startingPos);
        encodedCertBuffer.get(originalEncoding);
        GuaranteedEncodedFormX509Certificate guaranteedEncodedCert = new GuaranteedEncodedFormX509Certificate(certificate, originalEncoding);
        return guaranteedEncodedCert;
    } catch (Asn1DecodingException | Asn1EncodingException | CertificateException e) {
        throw new CertificateException("Failed to parse certificate", e);
    }
}
Also used : Asn1EncodingException(com.android.apksig.internal.asn1.Asn1EncodingException) ByteArrayInputStream(java.io.ByteArrayInputStream) Asn1DecodingException(com.android.apksig.internal.asn1.Asn1DecodingException) CertificateException(java.security.cert.CertificateException) ByteBuffer(java.nio.ByteBuffer) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(com.android.apksig.internal.x509.Certificate)

Example 94 with Certificate

use of com.android.apksig.internal.x509.Certificate in project apksig by venshine.

the class ApkSignerTest method testPublicKeyHasPositiveModulusAfterSigning.

@Test
public void testPublicKeyHasPositiveModulusAfterSigning() throws Exception {
    // The V2 and V3 signature schemes include the public key from the certificate in the
    // signing block. If a certificate with an RSAPublicKey is improperly encoded with a
    // negative modulus this was previously written to the signing block as is and failed on
    // device verification since on device the public key in the certificate was reencoded with
    // the correct encoding for the modulus. This test uses an improperly encoded certificate to
    // sign an APK and verifies that the public key in the signing block is corrected with a
    // positive modulus to allow on device installs / updates.
    List<ApkSigner.SignerConfig> signersList = Collections.singletonList(getDefaultSignerConfigFromResources(FIRST_RSA_2048_SIGNER_RESOURCE_NAME, FIRST_RSA_2048_SIGNER_CERT_WITH_NEGATIVE_MODULUS));
    File signedApk = sign("original.apk", new ApkSigner.Builder(signersList).setV1SigningEnabled(true).setV2SigningEnabled(true).setV3SigningEnabled(true));
    RSAPublicKey v2PublicKey = getRSAPublicKeyFromSigningBlock(signedApk, ApkSigningBlockUtils.VERSION_APK_SIGNATURE_SCHEME_V2);
    assertTrue("The modulus in the public key in the V2 signing block must not be negative", v2PublicKey.modulus.compareTo(BigInteger.ZERO) > 0);
    RSAPublicKey v3PublicKey = getRSAPublicKeyFromSigningBlock(signedApk, ApkSigningBlockUtils.VERSION_APK_SIGNATURE_SCHEME_V3);
    assertTrue("The modulus in the public key in the V3 signing block must not be negative", v3PublicKey.modulus.compareTo(BigInteger.ZERO) > 0);
}
Also used : RSAPublicKey(com.android.apksig.internal.x509.RSAPublicKey) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) Test(org.junit.Test)

Example 95 with Certificate

use of com.android.apksig.internal.x509.Certificate in project java-security-private-ca by googleapis.

the class CreateCertificate method createCertificate.

// Create a Certificate which is issued by the Certificate Authority present in the CA Pool.
// The public key used to sign the certificate can be generated using any crypto
// library/framework.
public static void createCertificate(String project, String location, String pool_Id, String certificateAuthorityName, String certificateName, ByteString publicKeyBytes) throws InterruptedException, ExecutionException, IOException {
    // clean up any remaining background resources.
    try (CertificateAuthorityServiceClient certificateAuthorityServiceClient = CertificateAuthorityServiceClient.create()) {
        // commonName: Enter a title for your certificate.
        // orgName: Provide the name of your company.
        // domainName: List the fully qualified domain name.
        // certificateLifetime: The validity of the certificate in seconds.
        String commonName = "common-name";
        String orgName = "org-name";
        String domainName = "dns.your-domain.com";
        long certificateLifetime = 1000L;
        // Set the Public Key and its format.
        PublicKey publicKey = PublicKey.newBuilder().setKey(publicKeyBytes).setFormat(KeyFormat.PEM).build();
        SubjectConfig subjectConfig = SubjectConfig.newBuilder().setSubject(Subject.newBuilder().setCommonName(commonName).setOrganization(orgName).build()).setSubjectAltName(SubjectAltNames.newBuilder().addDnsNames(domainName).build()).build();
        // Set the X.509 fields required for the certificate.
        X509Parameters x509Parameters = X509Parameters.newBuilder().setKeyUsage(KeyUsage.newBuilder().setBaseKeyUsage(KeyUsageOptions.newBuilder().setDigitalSignature(true).setKeyEncipherment(true).setCertSign(true).build()).setExtendedKeyUsage(ExtendedKeyUsageOptions.newBuilder().setServerAuth(true).build()).build()).setCaOptions(CaOptions.newBuilder().setIsCa(true).buildPartial()).build();
        // Create certificate.
        Certificate certificate = Certificate.newBuilder().setConfig(CertificateConfig.newBuilder().setPublicKey(publicKey).setSubjectConfig(subjectConfig).setX509Config(x509Parameters).build()).setLifetime(Duration.newBuilder().setSeconds(certificateLifetime).build()).build();
        // Create the Certificate Request.
        CreateCertificateRequest certificateRequest = CreateCertificateRequest.newBuilder().setParent(CaPoolName.of(project, location, pool_Id).toString()).setCertificateId(certificateName).setCertificate(certificate).setIssuingCertificateAuthorityId(certificateAuthorityName).build();
        // Get the Certificate response.
        ApiFuture<Certificate> future = certificateAuthorityServiceClient.createCertificateCallable().futureCall(certificateRequest);
        Certificate response = future.get();
        // Get the PEM encoded, signed X.509 certificate.
        System.out.println(response.getPemCertificate());
        // To verify the obtained certificate, use this intermediate chain list.
        System.out.println(response.getPemCertificateChainList());
    }
}
Also used : SubjectConfig(com.google.cloud.security.privateca.v1.CertificateConfig.SubjectConfig) X509Parameters(com.google.cloud.security.privateca.v1.X509Parameters) CreateCertificateRequest(com.google.cloud.security.privateca.v1.CreateCertificateRequest) PublicKey(com.google.cloud.security.privateca.v1.PublicKey) CertificateAuthorityServiceClient(com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient) ByteString(com.google.protobuf.ByteString) Certificate(com.google.cloud.security.privateca.v1.Certificate)

Aggregations

Certificate (org.bouncycastle.asn1.x509.Certificate)53 IOException (java.io.IOException)40 X509Certificate (java.security.cert.X509Certificate)37 CertificateException (java.security.cert.CertificateException)27 File (java.io.File)12 Test (org.junit.Test)11 BigInteger (java.math.BigInteger)9 CertificateEncodingException (java.security.cert.CertificateEncodingException)9 TBSCertificate (org.bouncycastle.asn1.x509.TBSCertificate)9 Test (org.junit.jupiter.api.Test)9 Certificate (com.google.cloud.security.privateca.v1.Certificate)8 CertificateAuthorityServiceClient (com.google.cloud.security.privateca.v1.CertificateAuthorityServiceClient)8 SQLException (java.sql.SQLException)8 X500Name (org.bouncycastle.asn1.x500.X500Name)8 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)7 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)7 Certificate (com.beanit.asn1bean.compiler.pkix1explicit88.Certificate)6 Extension (org.bouncycastle.asn1.x509.Extension)6 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)6 ArrayList (java.util.ArrayList)5