Search in sources :

Example 71 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project athenz by yahoo.

the class Crypto method validatePKCS7Signature.

// /CLOVER:OFF
public static boolean validatePKCS7Signature(String data, String signature, PublicKey publicKey) {
    try {
        SignerInformationStore signerStore;
        try (InputStream sigIs = new ByteArrayInputStream(Base64.decode(signature.getBytes(StandardCharsets.UTF_8)))) {
            CMSProcessable content = new CMSProcessableByteArray(data.getBytes(StandardCharsets.UTF_8));
            CMSSignedData signedData = new CMSSignedData(content, sigIs);
            signerStore = signedData.getSignerInfos();
        }
        Collection<SignerInformation> signers = signerStore.getSigners();
        Iterator<SignerInformation> it = signers.iterator();
        SignerInformationVerifier infoVerifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC_PROVIDER).build(publicKey);
        while (it.hasNext()) {
            SignerInformation signerInfo = it.next();
            if (signerInfo.verify(infoVerifier)) {
                return true;
            }
        }
    } catch (CMSException ex) {
        LOG.error("validatePKCS7Signature: unable to initialize CMSSignedData object: {}", ex.getMessage());
        throw new CryptoException(ex);
    } catch (OperatorCreationException ex) {
        LOG.error("validatePKCS7Signature: Caught OperatorCreationException when creating JcaSimpleSignerInfoVerifierBuilder: {}", ex.getMessage());
        throw new CryptoException(ex);
    } catch (IOException ex) {
        LOG.error("validatePKCS7Signature: Caught IOException when closing InputStream: {}", ex.getMessage());
        throw new CryptoException(ex);
    } catch (Exception ex) {
        LOG.error("validatePKCS7Signature: unable to validate signature: {}", ex.getMessage());
        throw new CryptoException(ex.getMessage());
    }
    return false;
}
Also used : CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) SignerInformation(org.bouncycastle.cms.SignerInformation) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CMSProcessable(org.bouncycastle.cms.CMSProcessable) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) CMSException(org.bouncycastle.cms.CMSException) PKCSException(org.bouncycastle.pkcs.PKCSException) PEMException(org.bouncycastle.openssl.PEMException) UnknownHostException(java.net.UnknownHostException) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) SignerInformationVerifier(org.bouncycastle.cms.SignerInformationVerifier) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CMSException(org.bouncycastle.cms.CMSException)

Example 72 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project java by kubernetes-client.

the class CSRUtils method sign.

/**
 * Sign CSR from the key-pair.
 *
 * @param keyPair the key pair
 * @param csrAlgo the csr algo
 * @param subjects the subjects
 * @return the byte [ ]
 * @throws CSRSigningException the csr signing exception
 */
public static byte[] sign(KeyPair keyPair, String csrAlgo, String subjects) throws CSRSigningException {
    try {
        PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(new X500Principal(subjects), keyPair.getPublic());
        JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(csrAlgo);
        ContentSigner signer = csBuilder.build(keyPair.getPrivate());
        PKCS10CertificationRequest csr = p10Builder.build(signer);
        // NOTE: a work-around for https://github.com/kubernetes/kubernetes/pull/96747
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bs);
        byte[] CRLF = new byte[] { '\r', '\n' };
        ps.println("-----BEGIN CERTIFICATE REQUEST-----");
        ps.println(Base64.getMimeEncoder(64, CRLF).encodeToString(csr.getEncoded()));
        ps.println("-----END CERTIFICATE REQUEST-----");
        return bs.toByteArray();
    } catch (IOException | OperatorCreationException e) {
        throw new CSRSigningException(e);
    }
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) PrintStream(java.io.PrintStream) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) CSRSigningException(io.kubernetes.client.util.exception.CSRSigningException) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) X500Principal(javax.security.auth.x500.X500Principal) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Example 73 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project athenz by yahoo.

the class ZTSClient method generateRoleCertificateRequest.

/**
 * Generate a Role Certificate request that could be sent to ZTS
 * to obtain a X509 Certificate for the requested role.
 * @param principalDomain name of the principal's domain
 * @param principalService name of the principal's service
 * @param roleDomainName name of the domain where role is defined
 * @param roleName name of the role to get a certificate request for
 * @param privateKey private key for the service identity for the caller
 * @param csrDn string identifying the dn for the csr without the cn component
 * @param csrDomain string identifying the dns domain for generating SAN fields
 * @param expiryTime number of minutes to request certificate to be valid for
 * @return RoleCertificateRequest object
 */
public static RoleCertificateRequest generateRoleCertificateRequest(final String principalDomain, final String principalService, final String roleDomainName, final String roleName, PrivateKey privateKey, final String csrDn, final String csrDomain, int expiryTime) {
    if (principalDomain == null || principalService == null) {
        throw new IllegalArgumentException("Principal's Domain and Service must be specified");
    }
    if (roleDomainName == null || roleName == null) {
        throw new IllegalArgumentException("Role DomainName and Name must be specified");
    }
    if (csrDomain == null) {
        throw new IllegalArgumentException("X509 CSR Domain must be specified");
    }
    // Athenz uses lower case for all elements, so let's
    // generate our dn which will be our role resource value
    final String domain = principalDomain.toLowerCase();
    final String service = principalService.toLowerCase();
    final String rnDomain = roleDomainName.toLowerCase();
    final String rnName = roleName.toLowerCase();
    String dn = "cn=" + rnDomain + AuthorityConsts.ROLE_SEP + rnName;
    if (csrDn != null) {
        dn = dn.concat(",").concat(csrDn);
    }
    // now let's generate our dsnName and email fields which will based on
    // our principal's details
    final String hostName = service + '.' + domain.replace('.', '-') + '.' + csrDomain;
    final String email = domain + "." + service + "@" + csrDomain;
    GeneralName[] sanArray = new GeneralName[4];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostName));
    sanArray[1] = new GeneralName(GeneralName.rfc822Name, new DERIA5String(email));
    final String spiffeUri = SPIFFE_URI + rnDomain + SPIFFE_COMP_ROLE + rnName;
    sanArray[2] = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(spiffeUri));
    final String principalUri = AuthorityConsts.ZTS_CERT_PRINCIPAL_URI + domain + "." + service;
    sanArray[3] = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(principalUri));
    String csr;
    try {
        csr = Crypto.generateX509CSR(privateKey, dn, sanArray);
    } catch (OperatorCreationException | IOException ex) {
        throw new ZTSClientException(ResourceException.BAD_REQUEST, ex.getMessage());
    }
    return new RoleCertificateRequest().setCsr(csr).setExpiryTime(expiryTime);
}
Also used : DERIA5String(org.bouncycastle.asn1.DERIA5String) DERIA5String(org.bouncycastle.asn1.DERIA5String) GeneralName(org.bouncycastle.asn1.x509.GeneralName) IOException(java.io.IOException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Example 74 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project athenz by yahoo.

the class ZTSInstanceRegister method generateInstanceRegisterInfo.

private static InstanceRegisterInformation generateInstanceRegisterInfo(final String domainName, final String serviceName, PrivateKey privateKey, final String serviceToken, final String csrDn, final String csrDomain) {
    if (domainName == null || serviceName == null) {
        throw new IllegalArgumentException("Principal's Domain and Service must be specified");
    }
    if (csrDomain == null) {
        throw new IllegalArgumentException("X509 CSR Domain must be specified");
    }
    // Athenz uses lower case for all elements, so let's
    // generate our dn which will be based on our service name
    final String domain = domainName.toLowerCase();
    final String service = serviceName.toLowerCase();
    final String cn = domain + "." + service;
    String dn = "cn=" + cn;
    if (csrDn != null) {
        dn = dn.concat(",").concat(csrDn);
    }
    // now let's generate our dsnName field based on our principal's details
    final String hostName = service + '.' + domain.replace('.', '-') + '.' + csrDomain;
    final String instanceUri = "athenz://instanceid/" + domain + "/" + service;
    GeneralName[] sanArray = new GeneralName[2];
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostName));
    sanArray[1] = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(instanceUri));
    String csr;
    try {
        csr = Crypto.generateX509CSR(privateKey, dn, sanArray);
    } catch (OperatorCreationException | IOException ex) {
        throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
    }
    return new InstanceRegisterInformation().setCsr(csr).setProvider("sys.auth.zts").setDomain(domain).setService(service).setAttestationData(serviceToken);
}
Also used : DERIA5String(org.bouncycastle.asn1.DERIA5String) DERIA5String(org.bouncycastle.asn1.DERIA5String) GeneralName(org.bouncycastle.asn1.x509.GeneralName) IOException(java.io.IOException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Example 75 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project athenz by yahoo.

the class ZTSClient method generateInstanceRefreshRequest.

/**
 * Generate a Instance Refresh request that could be sent to ZTS to
 * request a TLS certificate for a service.
 * @param principalDomain name of the principal's domain
 * @param principalService name of the principal's service
 * @param privateKey private key for the service identity for the caller
 * @param csrDn string identifying the dn for the csr without the cn component
 * @param csrDomain string identifying the dns domain for generating SAN fields
 * @param expiryTime number of seconds to request certificate to be valid for
 * @return InstanceRefreshRequest object
 */
public static InstanceRefreshRequest generateInstanceRefreshRequest(final String principalDomain, final String principalService, PrivateKey privateKey, final String csrDn, final String csrDomain, int expiryTime) {
    if (principalDomain == null || principalService == null) {
        throw new IllegalArgumentException("Principal's Domain and Service must be specified");
    }
    if (csrDomain == null) {
        throw new IllegalArgumentException("X509 CSR Domain must be specified");
    }
    // Athenz uses lower case for all elements, so let's
    // generate our dn which will be based on our service name
    final String domain = principalDomain.toLowerCase();
    final String service = principalService.toLowerCase();
    final String cn = domain + "." + service;
    String dn = "cn=" + cn;
    if (csrDn != null) {
        dn = dn.concat(",").concat(csrDn);
    }
    // now let's generate our dsnName field based on our principal's details
    GeneralName[] sanArray = new GeneralName[2];
    final String hostName = service + '.' + domain.replace('.', '-') + '.' + csrDomain;
    sanArray[0] = new GeneralName(GeneralName.dNSName, new DERIA5String(hostName));
    final String spiffeUri = SPIFFE_URI + domain + SPIFFE_COMP_SERVICE + service;
    sanArray[1] = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(spiffeUri));
    String csr;
    try {
        csr = Crypto.generateX509CSR(privateKey, dn, sanArray);
    } catch (OperatorCreationException | IOException ex) {
        throw new ZTSClientException(ResourceException.BAD_REQUEST, ex.getMessage());
    }
    return new InstanceRefreshRequest().setCsr(csr).setExpiryTime(expiryTime);
}
Also used : DERIA5String(org.bouncycastle.asn1.DERIA5String) DERIA5String(org.bouncycastle.asn1.DERIA5String) GeneralName(org.bouncycastle.asn1.x509.GeneralName) IOException(java.io.IOException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Aggregations

OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)93 IOException (java.io.IOException)52 ContentSigner (org.bouncycastle.operator.ContentSigner)40 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)38 CertificateException (java.security.cert.CertificateException)32 X509Certificate (java.security.cert.X509Certificate)31 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)23 Date (java.util.Date)21 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)20 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)17 CMSException (org.bouncycastle.cms.CMSException)17 X500Name (org.bouncycastle.asn1.x500.X500Name)16 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)16 GeneralName (org.bouncycastle.asn1.x509.GeneralName)15 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)14 CMSSignedData (org.bouncycastle.cms.CMSSignedData)12 GeneralSecurityException (java.security.GeneralSecurityException)11 BigInteger (java.math.BigInteger)10 NoSuchProviderException (java.security.NoSuchProviderException)10 CertificateEncodingException (java.security.cert.CertificateEncodingException)10