net.lightbody.bmp.mitm.util.EncryptionUtil Java Examples

The following examples show how to use net.lightbody.bmp.mitm.util.EncryptionUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PemFileCertificateSource.java    From CapturePacket with MIT License 6 votes vote down vote up
private CertificateAndKey loadCertificateAndKeyFiles() {
    if (certificateFile == null) {
        throw new IllegalArgumentException("PEM root certificate file cannot be null");
    }

    if (privateKeyFile == null) {
        throw new IllegalArgumentException("PEM private key file cannot be null");
    }

    if (privateKeyPassword == null) {
        log.warn("Attempting to load private key from file without password. Private keys should be password-protected.");
    }

    String pemEncodedCertificate = EncryptionUtil.readPemStringFromFile(certificateFile);
    X509Certificate certificate = securityProviderTool.decodePemEncodedCertificate(new StringReader(pemEncodedCertificate));

    String pemEncodedPrivateKey = EncryptionUtil.readPemStringFromFile(privateKeyFile);
    PrivateKey privateKey = securityProviderTool.decodePemEncodedPrivateKey(new StringReader(pemEncodedPrivateKey), privateKeyPassword);

    return new CertificateAndKey(certificate, privateKey);
}
 
Example #2
Source File: PemFileCertificateSource.java    From AndroidHttpCapture with MIT License 6 votes vote down vote up
private CertificateAndKey loadCertificateAndKeyFiles() {
    if (certificateFile == null) {
        throw new IllegalArgumentException("PEM root certificate file cannot be null");
    }

    if (privateKeyFile == null) {
        throw new IllegalArgumentException("PEM private key file cannot be null");
    }

    if (privateKeyPassword == null) {
        log.warn("Attempting to load private key from file without password. Private keys should be password-protected.");
    }

    String pemEncodedCertificate = EncryptionUtil.readPemStringFromFile(certificateFile);
    X509Certificate certificate = securityProviderTool.decodePemEncodedCertificate(new StringReader(pemEncodedCertificate));

    String pemEncodedPrivateKey = EncryptionUtil.readPemStringFromFile(privateKeyFile);
    PrivateKey privateKey = securityProviderTool.decodePemEncodedPrivateKey(new StringReader(pemEncodedPrivateKey), privateKeyPassword);

    return new CertificateAndKey(certificate, privateKey);
}
 
Example #3
Source File: PemFileCertificateSource.java    From Dream-Catcher with MIT License 6 votes vote down vote up
private CertificateAndKey loadCertificateAndKeyFiles() {
    if (certificateFile == null) {
        throw new IllegalArgumentException("PEM root certificate file cannot be null");
    }

    if (privateKeyFile == null) {
        throw new IllegalArgumentException("PEM private key file cannot be null");
    }

    if (privateKeyPassword == null) {
        log.warn("Attempting to load private key from file without password. Private keys should be password-protected.");
    }

    String pemEncodedCertificate = EncryptionUtil.readPemStringFromFile(certificateFile);
    X509Certificate certificate = securityProviderTool.decodePemEncodedCertificate(new StringReader(pemEncodedCertificate));

    String pemEncodedPrivateKey = EncryptionUtil.readPemStringFromFile(privateKeyFile);
    PrivateKey privateKey = securityProviderTool.decodePemEncodedPrivateKey(new StringReader(pemEncodedPrivateKey), privateKeyPassword);

    return new CertificateAndKey(certificate, privateKey);
}
 
Example #4
Source File: BouncyCastleSecurityProviderTool.java    From AndroidHttpCapture with MIT License 4 votes vote down vote up
@Override
public CertificateAndKey createCARootCertificate(CertificateInfo certificateInfo,
                                                 KeyPair keyPair,
                                                 String messageDigest) {
    if (certificateInfo.getNotBefore() == null) {
        throw new IllegalArgumentException("Must specify Not Before for server certificate");
    }

    if (certificateInfo.getNotAfter() == null) {
        throw new IllegalArgumentException("Must specify Not After for server certificate");
    }

    // create the X500Name that will be both the issuer and the subject of the new root certificate
    X500Name issuer = createX500NameForCertificate(certificateInfo);

    BigInteger serial = EncryptionUtil.getRandomBigInteger(CERTIFICATE_SERIAL_NUMBER_SIZE);

    PublicKey rootCertificatePublicKey = keyPair.getPublic();

    String signatureAlgorithm = EncryptionUtil.getSignatureAlgorithm(messageDigest, keyPair.getPrivate());

    // this is a CA root certificate, so it is self-signed
    ContentSigner selfSigner = getCertificateSigner(keyPair.getPrivate(), signatureAlgorithm);

    ASN1EncodableVector extendedKeyUsages = new ASN1EncodableVector();
    extendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth);
    extendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth);
    extendedKeyUsages.add(KeyPurposeId.anyExtendedKeyUsage);

    X509CertificateHolder certificateHolder;
    try {
        certificateHolder = new JcaX509v3CertificateBuilder(
                issuer,
                serial,
                certificateInfo.getNotBefore(),
                certificateInfo.getNotAfter(),
                issuer,
                rootCertificatePublicKey)
                .addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(rootCertificatePublicKey))
                .addExtension(Extension.basicConstraints, true, new BasicConstraints(true))
                .addExtension(Extension.keyUsage, false, new KeyUsage(
                        KeyUsage.keyCertSign
                                | KeyUsage.digitalSignature
                                | KeyUsage.keyEncipherment
                                | KeyUsage.dataEncipherment
                                | KeyUsage.cRLSign))
                .addExtension(Extension.extendedKeyUsage, false, new DERSequence(extendedKeyUsages))
                .build(selfSigner);
    } catch (CertIOException e) {
        throw new CertificateCreationException("Error creating root certificate", e);
    }

    // convert the Bouncy Castle X590CertificateHolder to a JCA cert
    X509Certificate cert = convertToJcaCertificate(certificateHolder);

    return new CertificateAndKey(cert, keyPair.getPrivate());
}
 
Example #5
Source File: ImpersonatingMitmManager.java    From CapturePacket with MIT License 4 votes vote down vote up
/**
 * Generates an {@link SslContext} using an impersonated certificate containing the information in the specified
 * certificateInfo.
 *
 * @param certificateInfo certificate information to impersonate
 * @return an SslContext that will present the impersonated certificate to the client
 */
private SslContext createImpersonatingSslContext(CertificateInfo certificateInfo) {
    long impersonationStart = System.currentTimeMillis();

    // generate a public and private key pair for the forged certificate. the SslContext will send the impersonated certificate to clients
    // to impersonate the real upstream server, and will use the private key to encrypt the channel.
    KeyPair serverKeyPair = serverKeyGenerator.generate();

    // get the CA root certificate and private key that will be used to sign the forged certificate
    X509Certificate caRootCertificate = rootCertificate.get().getCertificate();
    PrivateKey caPrivateKey = rootCertificate.get().getPrivateKey();
    if (caRootCertificate == null || caPrivateKey == null) {
        throw new IllegalStateException("A CA root certificate and private key are required to sign a server certificate. Root certificate was: "
                + caRootCertificate + ". Private key was: " + caPrivateKey);
    }

    // determine if the server private key was signed with an RSA private key. though TLS no longer requires the server
    // certificate to use the same private key type as the root certificate, Java bug JDK-8136442 prevents Java from creating a opening an SSL socket
    // if the CA and server certificates are not of the same type. see https://bugs.openjdk.java.net/browse/JDK-8136442
    // note this only applies to RSA CAs signing EC server certificates; Java seems to properly handle EC CAs signing
    // RSA server certificates.
    if (EncryptionUtil.isEcKey(serverKeyPair.getPrivate()) && EncryptionUtil.isRsaKey(caPrivateKey)) {
        log.warn("CA private key is an RSA key and impersonated server private key is an Elliptic Curve key. JDK bug 8136442 may prevent the proxy server from creating connections to clients due to 'no cipher suites in common'.");
    }

    // create the forged server certificate and sign it with the root certificate and private key
    CertificateAndKey impersonatedCertificateAndKey = securityProviderTool.createServerCertificate(
            certificateInfo,
            caRootCertificate,
            caPrivateKey,
            serverKeyPair,
            serverCertificateMessageDigest);

    X509Certificate[] certChain = {impersonatedCertificateAndKey.getCertificate(), caRootCertificate};
    SslContext sslContext;
    try {
        sslContext = SslContextBuilder.forServer(impersonatedCertificateAndKey.getPrivateKey(), certChain)
                .ciphers(clientCipherSuites, SupportedCipherSuiteFilter.INSTANCE)
                .build();

    } catch (SSLException e) {
        throw new MitmException("Error creating SslContext for connection to client using impersonated certificate and private key", e);
    }

    long impersonationFinish = System.currentTimeMillis();

    statistics.certificateCreated(impersonationStart, impersonationFinish);

    log.debug("Impersonated certificate for {} in {}ms", certificateInfo.getCommonName(), impersonationFinish - impersonationStart);

    return sslContext;
}
 
Example #6
Source File: BouncyCastleSecurityProviderTool.java    From AndroidHttpCapture with MIT License 4 votes vote down vote up
@Override
public CertificateAndKey createServerCertificate(CertificateInfo certificateInfo,
                                                 X509Certificate caRootCertificate,
                                                 PrivateKey caPrivateKey,
                                                 KeyPair serverKeyPair,
                                                 String messageDigest) {
    // make sure certificateInfo contains all fields necessary to generate the certificate
    if (certificateInfo.getCommonName() == null) {
        throw new IllegalArgumentException("Must specify CN for server certificate");
    }

    if (certificateInfo.getNotBefore() == null) {
        throw new IllegalArgumentException("Must specify Not Before for server certificate");
    }

    if (certificateInfo.getNotAfter() == null) {
        throw new IllegalArgumentException("Must specify Not After for server certificate");
    }

    // create the subject for the new server certificate. when impersonating an upstream server, this should contain
    // the hostname of the server we are trying to impersonate in the CN field
    X500Name serverCertificateSubject = createX500NameForCertificate(certificateInfo);

    // get the algorithm that will be used to sign the new certificate, which is a combination of the message digest
    // and the digital signature from the CA's private key
    String signatureAlgorithm = EncryptionUtil.getSignatureAlgorithm(messageDigest, caPrivateKey);

    // get a ContentSigner with our CA private key that will be used to sign the new server certificate
    ContentSigner signer = getCertificateSigner(caPrivateKey, signatureAlgorithm);

    // generate a serial number for the new certificate. serial numbers only need to be unique within our
    // certification authority; a large random integer will satisfy that requirement.
    BigInteger serialNumber = EncryptionUtil.getRandomBigInteger(CERTIFICATE_SERIAL_NUMBER_SIZE);

    // create the X509Certificate using Bouncy Castle. the BC X509CertificateHolder can be converted to a JCA X509Certificate.
    X509CertificateHolder certificateHolder;
    try {
        certificateHolder = new JcaX509v3CertificateBuilder(caRootCertificate,
                serialNumber,
                certificateInfo.getNotBefore(),
                certificateInfo.getNotAfter(),
                serverCertificateSubject,
                serverKeyPair.getPublic())
                .addExtension(Extension.subjectAlternativeName, false, getDomainNameSANsAsASN1Encodable(certificateInfo.getSubjectAlternativeNames()))
                .addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(serverKeyPair.getPublic()))
                .addExtension(Extension.basicConstraints, false, new BasicConstraints(false))
                .build(signer);
    } catch (CertIOException e) {
        throw new CertificateCreationException("Error creating new server certificate", e);
    }

    // convert the Bouncy Castle certificate holder into a JCA X509Certificate
    X509Certificate serverCertificate = convertToJcaCertificate(certificateHolder);

    return new CertificateAndKey(serverCertificate, serverKeyPair.getPrivate());
}
 
Example #7
Source File: RootCertificateGenerator.java    From AndroidHttpCapture with MIT License 4 votes vote down vote up
/**
 * Saves the root certificate as PEM-encoded data to the specified file.
 */
public void saveRootCertificateAsPemFile(File file) {
    String pemEncodedCertificate = securityProviderTool.encodeCertificateAsPem(generatedCertificateAndKey.get().getCertificate());

    EncryptionUtil.writePemStringToFile(file, pemEncodedCertificate);
}
 
Example #8
Source File: ImpersonatingMitmManager.java    From AndroidHttpCapture with MIT License 4 votes vote down vote up
/**
 * Generates an {@link SslContext} using an impersonated certificate containing the information in the specified
 * certificateInfo.
 *
 * @param certificateInfo certificate information to impersonate
 * @return an SslContext that will present the impersonated certificate to the client
 */
private SslContext createImpersonatingSslContext(CertificateInfo certificateInfo) {
    long impersonationStart = System.currentTimeMillis();

    // generate a public and private key pair for the forged certificate. the SslContext will send the impersonated certificate to clients
    // to impersonate the real upstream server, and will use the private key to encrypt the channel.
    KeyPair serverKeyPair = serverKeyGenerator.generate();

    // get the CA root certificate and private key that will be used to sign the forged certificate
    X509Certificate caRootCertificate = rootCertificate.get().getCertificate();
    PrivateKey caPrivateKey = rootCertificate.get().getPrivateKey();
    if (caRootCertificate == null || caPrivateKey == null) {
        throw new IllegalStateException("A CA root certificate and private key are required to sign a server certificate. Root certificate was: "
                + caRootCertificate + ". Private key was: " + caPrivateKey);
    }

    // determine if the server private key was signed with an RSA private key. though TLS no longer requires the server
    // certificate to use the same private key type as the root certificate, Java bug JDK-8136442 prevents Java from creating a opening an SSL socket
    // if the CA and server certificates are not of the same type. see https://bugs.openjdk.java.net/browse/JDK-8136442
    // note this only applies to RSA CAs signing EC server certificates; Java seems to properly handle EC CAs signing
    // RSA server certificates.
    if (EncryptionUtil.isEcKey(serverKeyPair.getPrivate()) && EncryptionUtil.isRsaKey(caPrivateKey)) {
        log.warn("CA private key is an RSA key and impersonated server private key is an Elliptic Curve key. JDK bug 8136442 may prevent the proxy server from creating connections to clients due to 'no cipher suites in common'.");
    }

    // create the forged server certificate and sign it with the root certificate and private key
    CertificateAndKey impersonatedCertificateAndKey = securityProviderTool.createServerCertificate(
            certificateInfo,
            caRootCertificate,
            caPrivateKey,
            serverKeyPair,
            serverCertificateMessageDigest);

    X509Certificate[] certChain = {impersonatedCertificateAndKey.getCertificate(), caRootCertificate};
    SslContext sslContext;
    try {
        sslContext = SslContextBuilder.forServer(impersonatedCertificateAndKey.getPrivateKey(), certChain)
                .ciphers(clientCipherSuites, SupportedCipherSuiteFilter.INSTANCE)
                .build();

    } catch (SSLException e) {
        throw new MitmException("Error creating SslContext for connection to client using impersonated certificate and private key", e);
    }

    long impersonationFinish = System.currentTimeMillis();

    statistics.certificateCreated(impersonationStart, impersonationFinish);

    log.debug("Impersonated certificate for {} in {}ms", certificateInfo.getCommonName(), impersonationFinish - impersonationStart);

    return sslContext;
}
 
Example #9
Source File: BouncyCastleSecurityProviderTool.java    From Dream-Catcher with MIT License 4 votes vote down vote up
@Override
public CertificateAndKey createCARootCertificate(CertificateInfo certificateInfo,
                                                 KeyPair keyPair,
                                                 String messageDigest) {
    if (certificateInfo.getNotBefore() == null) {
        throw new IllegalArgumentException("Must specify Not Before for server certificate");
    }

    if (certificateInfo.getNotAfter() == null) {
        throw new IllegalArgumentException("Must specify Not After for server certificate");
    }

    // create the X500Name that will be both the issuer and the subject of the new root certificate
    X500Name issuer = createX500NameForCertificate(certificateInfo);

    BigInteger serial = EncryptionUtil.getRandomBigInteger(CERTIFICATE_SERIAL_NUMBER_SIZE);

    PublicKey rootCertificatePublicKey = keyPair.getPublic();

    String signatureAlgorithm = EncryptionUtil.getSignatureAlgorithm(messageDigest, keyPair.getPrivate());

    // this is a CA root certificate, so it is self-signed
    ContentSigner selfSigner = getCertificateSigner(keyPair.getPrivate(), signatureAlgorithm);

    ASN1EncodableVector extendedKeyUsages = new ASN1EncodableVector();
    extendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth);
    extendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth);
    extendedKeyUsages.add(KeyPurposeId.anyExtendedKeyUsage);

    X509CertificateHolder certificateHolder;
    try {
        certificateHolder = new JcaX509v3CertificateBuilder(
                issuer,
                serial,
                certificateInfo.getNotBefore(),
                certificateInfo.getNotAfter(),
                issuer,
                rootCertificatePublicKey)
                .addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(rootCertificatePublicKey))
                .addExtension(Extension.basicConstraints, true, new BasicConstraints(true))
                .addExtension(Extension.keyUsage, false, new KeyUsage(
                        KeyUsage.keyCertSign
                                | KeyUsage.digitalSignature
                                | KeyUsage.keyEncipherment
                                | KeyUsage.dataEncipherment
                                | KeyUsage.cRLSign))
                .addExtension(Extension.extendedKeyUsage, false, new DERSequence(extendedKeyUsages))
                .build(selfSigner);
    } catch (CertIOException e) {
        throw new CertificateCreationException("Error creating root certificate", e);
    }

    // convert the Bouncy Castle X590CertificateHolder to a JCA cert
    X509Certificate cert = convertToJcaCertificate(certificateHolder);

    return new CertificateAndKey(cert, keyPair.getPrivate());
}
 
Example #10
Source File: BouncyCastleSecurityProviderTool.java    From Dream-Catcher with MIT License 4 votes vote down vote up
@Override
public CertificateAndKey createServerCertificate(CertificateInfo certificateInfo,
                                                 X509Certificate caRootCertificate,
                                                 PrivateKey caPrivateKey,
                                                 KeyPair serverKeyPair,
                                                 String messageDigest) {
    // make sure certificateInfo contains all fields necessary to generate the certificate
    if (certificateInfo.getCommonName() == null) {
        throw new IllegalArgumentException("Must specify CN for server certificate");
    }

    if (certificateInfo.getNotBefore() == null) {
        throw new IllegalArgumentException("Must specify Not Before for server certificate");
    }

    if (certificateInfo.getNotAfter() == null) {
        throw new IllegalArgumentException("Must specify Not After for server certificate");
    }

    // create the subject for the new server certificate. when impersonating an upstream server, this should contain
    // the hostname of the server we are trying to impersonate in the CN field
    X500Name serverCertificateSubject = createX500NameForCertificate(certificateInfo);

    // get the algorithm that will be used to sign the new certificate, which is a combination of the message digest
    // and the digital signature from the CA's private key
    String signatureAlgorithm = EncryptionUtil.getSignatureAlgorithm(messageDigest, caPrivateKey);

    // get a ContentSigner with our CA private key that will be used to sign the new server certificate
    ContentSigner signer = getCertificateSigner(caPrivateKey, signatureAlgorithm);

    // generate a serial number for the new certificate. serial numbers only need to be unique within our
    // certification authority; a large random integer will satisfy that requirement.
    BigInteger serialNumber = EncryptionUtil.getRandomBigInteger(CERTIFICATE_SERIAL_NUMBER_SIZE);

    // create the X509Certificate using Bouncy Castle. the BC X509CertificateHolder can be converted to a JCA X509Certificate.
    X509CertificateHolder certificateHolder;
    try {
        certificateHolder = new JcaX509v3CertificateBuilder(caRootCertificate,
                serialNumber,
                certificateInfo.getNotBefore(),
                certificateInfo.getNotAfter(),
                serverCertificateSubject,
                serverKeyPair.getPublic())
                .addExtension(Extension.subjectAlternativeName, false, getDomainNameSANsAsASN1Encodable(certificateInfo.getSubjectAlternativeNames()))
                .addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(serverKeyPair.getPublic()))
                .addExtension(Extension.basicConstraints, false, new BasicConstraints(false))
                .build(signer);
    } catch (CertIOException e) {
        throw new CertificateCreationException("Error creating new server certificate", e);
    }

    // convert the Bouncy Castle certificate holder into a JCA X509Certificate
    X509Certificate serverCertificate = convertToJcaCertificate(certificateHolder);

    return new CertificateAndKey(serverCertificate, serverKeyPair.getPrivate());
}
 
Example #11
Source File: RootCertificateGenerator.java    From Dream-Catcher with MIT License 4 votes vote down vote up
/**
 * Saves the root certificate as PEM-encoded data to the specified file.
 */
public void saveRootCertificateAsPemFile(File file) {
    String pemEncodedCertificate = securityProviderTool.encodeCertificateAsPem(generatedCertificateAndKey.get().getCertificate());

    EncryptionUtil.writePemStringToFile(file, pemEncodedCertificate);
}
 
Example #12
Source File: ImpersonatingMitmManager.java    From Dream-Catcher with MIT License 4 votes vote down vote up
/**
 * Generates an {@link SslContext} using an impersonated certificate containing the information in the specified
 * certificateInfo.
 *
 * @param certificateInfo certificate information to impersonate
 * @return an SslContext that will present the impersonated certificate to the client
 */
private SslContext createImpersonatingSslContext(CertificateInfo certificateInfo) {
    long impersonationStart = System.currentTimeMillis();

    // generate a public and private key pair for the forged certificate. the SslContext will send the impersonated certificate to clients
    // to impersonate the real upstream server, and will use the private key to encrypt the channel.
    KeyPair serverKeyPair = serverKeyGenerator.generate();

    // get the CA root certificate and private key that will be used to sign the forced certificate
    X509Certificate caRootCertificate = rootCertificate.get().getCertificate();
    PrivateKey caPrivateKey = rootCertificate.get().getPrivateKey();
    if (caRootCertificate == null || caPrivateKey == null) {
        throw new IllegalStateException("A CA root certificate and private key are required to sign a server certificate. Root certificate was: "
                + caRootCertificate + ". Private key was: " + caPrivateKey);
    }

    // determine if the server private key was signed with an RSA private key. though TLS no longer requires the server
    // certificate to use the same private key type as the root certificate, Java bug JDK-8136442 prevents Java from creating a opening an SSL socket
    // if the CA and server certificates are not of the same type. see https://bugs.openjdk.java.net/browse/JDK-8136442
    // note this only applies to RSA CAs signing EC server certificates; Java seems to properly handle EC CAs signing
    // RSA server certificates.
    if (EncryptionUtil.isEcKey(serverKeyPair.getPrivate()) && EncryptionUtil.isRsaKey(caPrivateKey)) {
        log.warn("CA private key is an RSA key and impersonated server private key is an Elliptic Curve key. JDK bug 8136442 may prevent the proxy server from creating connections to clients due to 'no cipher suites in common'.");
    }

    // create the forged server certificate and sign it with the root certificate and private key
    CertificateAndKey impersonatedCertificateAndKey = securityProviderTool.createServerCertificate(
            certificateInfo,
            caRootCertificate,
            caPrivateKey,
            serverKeyPair,
            serverCertificateMessageDigest);

    X509Certificate[] certChain = {impersonatedCertificateAndKey.getCertificate(), caRootCertificate};
    SslContext sslContext;
    try {
        sslContext = SslContextBuilder.forServer(impersonatedCertificateAndKey.getPrivateKey(), certChain)
                .ciphers(clientCipherSuites, SupportedCipherSuiteFilter.INSTANCE)
                .build();

    } catch (SSLException e) {
        throw new MitmException("Error creating SslContext for connection to client using impersonated certificate and private key", e);
    }

    long impersonationFinish = System.currentTimeMillis();

    statistics.certificateCreated(impersonationStart, impersonationFinish);

    log.debug("Impersonated certificate for {} in {}ms", certificateInfo.getCommonName(), impersonationFinish - impersonationStart);

    return sslContext;
}
 
Example #13
Source File: BouncyCastleSecurityProviderTool.java    From CapturePacket with MIT License 4 votes vote down vote up
@Override
public CertificateAndKey createCARootCertificate(CertificateInfo certificateInfo,
                                                 KeyPair keyPair,
                                                 String messageDigest) {
    if (certificateInfo.getNotBefore() == null) {
        throw new IllegalArgumentException("Must specify Not Before for server certificate");
    }

    if (certificateInfo.getNotAfter() == null) {
        throw new IllegalArgumentException("Must specify Not After for server certificate");
    }

    // create the X500Name that will be both the issuer and the subject of the new root certificate
    X500Name issuer = createX500NameForCertificate(certificateInfo);

    BigInteger serial = EncryptionUtil.getRandomBigInteger(CERTIFICATE_SERIAL_NUMBER_SIZE);

    PublicKey rootCertificatePublicKey = keyPair.getPublic();

    String signatureAlgorithm = EncryptionUtil.getSignatureAlgorithm(messageDigest, keyPair.getPrivate());

    // this is a CA root certificate, so it is self-signed
    ContentSigner selfSigner = getCertificateSigner(keyPair.getPrivate(), signatureAlgorithm);

    ASN1EncodableVector extendedKeyUsages = new ASN1EncodableVector();
    extendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth);
    extendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth);
    extendedKeyUsages.add(KeyPurposeId.anyExtendedKeyUsage);

    X509CertificateHolder certificateHolder;
    try {
        certificateHolder = new JcaX509v3CertificateBuilder(
                issuer,
                serial,
                certificateInfo.getNotBefore(),
                certificateInfo.getNotAfter(),
                issuer,
                rootCertificatePublicKey)
                .addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(rootCertificatePublicKey))
                .addExtension(Extension.basicConstraints, true, new BasicConstraints(true))
                .addExtension(Extension.keyUsage, false, new KeyUsage(
                        KeyUsage.keyCertSign
                                | KeyUsage.digitalSignature
                                | KeyUsage.keyEncipherment
                                | KeyUsage.dataEncipherment
                                | KeyUsage.cRLSign))
                .addExtension(Extension.extendedKeyUsage, false, new DERSequence(extendedKeyUsages))
                .build(selfSigner);
    } catch (CertIOException e) {
        throw new CertificateCreationException("Error creating root certificate", e);
    }

    // convert the Bouncy Castle X590CertificateHolder to a JCA cert
    X509Certificate cert = convertToJcaCertificate(certificateHolder);

    return new CertificateAndKey(cert, keyPair.getPrivate());
}
 
Example #14
Source File: BouncyCastleSecurityProviderTool.java    From CapturePacket with MIT License 4 votes vote down vote up
@Override
public CertificateAndKey createServerCertificate(CertificateInfo certificateInfo,
                                                 X509Certificate caRootCertificate,
                                                 PrivateKey caPrivateKey,
                                                 KeyPair serverKeyPair,
                                                 String messageDigest) {
    // make sure certificateInfo contains all fields necessary to generate the certificate
    if (certificateInfo.getCommonName() == null) {
        throw new IllegalArgumentException("Must specify CN for server certificate");
    }

    if (certificateInfo.getNotBefore() == null) {
        throw new IllegalArgumentException("Must specify Not Before for server certificate");
    }

    if (certificateInfo.getNotAfter() == null) {
        throw new IllegalArgumentException("Must specify Not After for server certificate");
    }

    // create the subject for the new server certificate. when impersonating an upstream server, this should contain
    // the hostname of the server we are trying to impersonate in the CN field
    X500Name serverCertificateSubject = createX500NameForCertificate(certificateInfo);

    // get the algorithm that will be used to sign the new certificate, which is a combination of the message digest
    // and the digital signature from the CA's private key
    String signatureAlgorithm = EncryptionUtil.getSignatureAlgorithm(messageDigest, caPrivateKey);

    // get a ContentSigner with our CA private key that will be used to sign the new server certificate
    ContentSigner signer = getCertificateSigner(caPrivateKey, signatureAlgorithm);

    // generate a serial number for the new certificate. serial numbers only need to be unique within our
    // certification authority; a large random integer will satisfy that requirement.
    BigInteger serialNumber = EncryptionUtil.getRandomBigInteger(CERTIFICATE_SERIAL_NUMBER_SIZE);

    // create the X509Certificate using Bouncy Castle. the BC X509CertificateHolder can be converted to a JCA X509Certificate.
    X509CertificateHolder certificateHolder;
    try {
        certificateHolder = new JcaX509v3CertificateBuilder(caRootCertificate,
                serialNumber,
                certificateInfo.getNotBefore(),
                certificateInfo.getNotAfter(),
                serverCertificateSubject,
                serverKeyPair.getPublic())
                .addExtension(Extension.subjectAlternativeName, false, getDomainNameSANsAsASN1Encodable(certificateInfo.getSubjectAlternativeNames()))
                .addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(serverKeyPair.getPublic()))
                .addExtension(Extension.basicConstraints, false, new BasicConstraints(false))
                .build(signer);
    } catch (CertIOException e) {
        throw new CertificateCreationException("Error creating new server certificate", e);
    }

    // convert the Bouncy Castle certificate holder into a JCA X509Certificate
    X509Certificate serverCertificate = convertToJcaCertificate(certificateHolder);

    return new CertificateAndKey(serverCertificate, serverKeyPair.getPrivate());
}
 
Example #15
Source File: RootCertificateGenerator.java    From CapturePacket with MIT License 4 votes vote down vote up
/**
 * Saves the root certificate as PEM-encoded data to the specified file.
 */
public void saveRootCertificateAsPemFile(File file) {
    String pemEncodedCertificate = securityProviderTool.encodeCertificateAsPem(generatedCertificateAndKey.get().getCertificate());

    EncryptionUtil.writePemStringToFile(file, pemEncodedCertificate);
}
 
Example #16
Source File: RootCertificateGenerator.java    From Dream-Catcher with MIT License 2 votes vote down vote up
/**
 * Saves the private key as PEM-encoded data to a file, using the specified password to encrypt the private key and
 * the {@link #DEFAULT_PEM_ENCRYPTION_ALGORITHM}. If the password is null, the private key will be stored unencrypted.
 * In general, private keys should not be stored unencrypted.
 *
 * @param file                  file to save the private key to
 * @param passwordForPrivateKey password to protect the private key
 */
public void savePrivateKeyAsPemFile(File file, String passwordForPrivateKey) {
    String pemEncodedPrivateKey = securityProviderTool.encodePrivateKeyAsPem(generatedCertificateAndKey.get().getPrivateKey(), passwordForPrivateKey, DEFAULT_PEM_ENCRYPTION_ALGORITHM);

    EncryptionUtil.writePemStringToFile(file, pemEncodedPrivateKey);
}
 
Example #17
Source File: RootCertificateGenerator.java    From AndroidHttpCapture with MIT License 2 votes vote down vote up
/**
 * Saves the private key as PEM-encoded data to a file, using the specified password to encrypt the private key and
 * the {@link #DEFAULT_PEM_ENCRYPTION_ALGORITHM}. If the password is null, the private key will be stored unencrypted.
 * In general, private keys should not be stored unencrypted.
 *
 * @param file                  file to save the private key to
 * @param passwordForPrivateKey password to protect the private key
 */
public void savePrivateKeyAsPemFile(File file, String passwordForPrivateKey) {
    String pemEncodedPrivateKey = securityProviderTool.encodePrivateKeyAsPem(generatedCertificateAndKey.get().getPrivateKey(), passwordForPrivateKey, DEFAULT_PEM_ENCRYPTION_ALGORITHM);

    EncryptionUtil.writePemStringToFile(file, pemEncodedPrivateKey);
}
 
Example #18
Source File: RootCertificateGenerator.java    From CapturePacket with MIT License 2 votes vote down vote up
/**
 * Saves the private key as PEM-encoded data to a file, using the specified password to encrypt the private key and
 * the {@link #DEFAULT_PEM_ENCRYPTION_ALGORITHM}. If the password is null, the private key will be stored unencrypted.
 * In general, private keys should not be stored unencrypted.
 *
 * @param file                  file to save the private key to
 * @param passwordForPrivateKey password to protect the private key
 */
public void savePrivateKeyAsPemFile(File file, String passwordForPrivateKey) {
    String pemEncodedPrivateKey = securityProviderTool.encodePrivateKeyAsPem(generatedCertificateAndKey.get().getPrivateKey(), passwordForPrivateKey, DEFAULT_PEM_ENCRYPTION_ALGORITHM);

    EncryptionUtil.writePemStringToFile(file, pemEncodedPrivateKey);
}