org.bouncycastle.cert.X509CertificateHolder

Here are the examples of the java api org.bouncycastle.cert.X509CertificateHolder taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

184 Examples 7

19 Source : SM2CertUtil.java
with Apache License 2.0
from ZZMarquis

public static X509Certificate getX509CertificateFromPfx(byte[] pfxDER, String preplacedwd) throws Exception {
    InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build(preplacedwd.toCharArray());
    PKCS12PfxPdu pfx = new PKCS12PfxPdu(pfxDER);
    ContentInfo[] infos = pfx.getContentInfos();
    if (infos.length != 2) {
        throw new Exception("Only support one pair ContentInfo");
    }
    for (int i = 0; i != infos.length; i++) {
        if (infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) {
            PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i], inputDecryptorProvider);
            PKCS12SafeBag[] bags = dataFact.getSafeBags();
            X509CertificateHolder certHoler = (X509CertificateHolder) bags[0].getBagValue();
            return SM2CertUtil.getX509Certificate(certHoler.getEncoded());
        }
    }
    throw new Exception("Not found X509Certificate in this pfx");
}

19 Source : PivTestUtils.java
with Apache License 2.0
from Yubico

public static X509Certificate createCertificate(PivSession piv, PublicKey publicKey, Slot slot, KeyType keyType) throws IOException, CertificateException, NoSuchAlgorithmException {
    X500Name name = new X500Name("CN=Example");
    X509v3CertificateBuilder serverCertGen = new X509v3CertificateBuilder(name, new BigInteger("123456789"), new Date(), new Date(), name, SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(publicKey.getEncoded())));
    String algorithm;
    ASN1ObjectIdentifier algorithmId;
    switch(keyType.params.algorithm) {
        case EC:
            algorithm = "SHA256WithECDSA";
            algorithmId = X9ObjectIdentifiers.ecdsa_with_SHA256;
            break;
        case RSA:
            algorithm = "SHA256WithRSA";
            algorithmId = PKCSObjectIdentifiers.sha256WithRSAEncryption;
            break;
        default:
            throw new IllegalStateException();
    }
    Signature signature = Signature.getInstance(algorithm);
    X509CertificateHolder holder = serverCertGen.build(new ContentSigner() {

        ByteArrayOutputStream messageBuffer = new ByteArrayOutputStream();

        @Override
        public AlgorithmIdentifier getAlgorithmIdentifier() {
            return new AlgorithmIdentifier(algorithmId);
        }

        @Override
        public OutputStream getOutputStream() {
            return messageBuffer;
        }

        @Override
        public byte[] getSignature() {
            try {
                return piv.sign(slot, keyType, messageBuffer.toByteArray(), signature);
            } catch (IOException | ApduException | NoSuchAlgorithmException | BadResponseException e) {
                throw new RuntimeException(e);
            }
        }
    });
    InputStream stream = new ByteArrayInputStream(holder.getEncoded());
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    return (X509Certificate) cf.generateCertificate(stream);
/*
        KeyPair dummy = generateKey(keyType);
        serverCertGen.setSignatureAlgorithm(algorithm);
        X509Certificate cert = serverCertGen.generate(dummy.getPrivate());

        return signCertificate(piv, slot, keyType, cert.getTBSCertificate(), cert.getSigAlgName());

 */
}

19 Source : AttestationCertificateBuilder.java
with Apache License 2.0
from webauthn4j

public X509Certificate build(PrivateKey issuerPrivateKey) {
    try {
        ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withECDSA").build(issuerPrivateKey);
        X509CertificateHolder certificateHolder = certificateBuilder.build(contentSigner);
        return new JcaX509CertificateConverter().getCertificate(certificateHolder);
    } catch (CertificateException e) {
        throw new com.webauthn4j.validator.exception.CertificateException(e);
    } catch (OperatorCreationException e) {
        throw new UnexpectedCheckedException(e);
    }
}

19 Source : OcspCertificateValidatorTest.java
with Apache License 2.0
from wangrenlei

/**
 * Generates a certificate with a specific public key signed by the issuer key.
 *
 * @param dn        the subject DN
 * @param publicKey the subject public key
 * @param issuerDn  the issuer DN
 * @param issuerKey the issuer private key
 * @return the certificate
 * @throws IOException               if an exception occurs
 * @throws NoSuchAlgorithmException  if an exception occurs
 * @throws CertificateException      if an exception occurs
 * @throws NoSuchProviderException   if an exception occurs
 * @throws SignatureException        if an exception occurs
 * @throws InvalidKeyException       if an exception occurs
 * @throws OperatorCreationException if an exception occurs
 */
private static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, String issuerDn, PrivateKey issuerKey) throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, OperatorCreationException {
    ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER).build(issuerKey);
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
    Date startDate = new Date(YESTERDAY);
    Date endDate = new Date(ONE_YEAR_FROM_NOW);
    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(new X500Name(issuerDn), BigInteger.valueOf(System.currentTimeMillis()), startDate, endDate, new X500Name(dn), subPubKeyInfo);
    X509CertificateHolder certificateHolder = v3CertGen.build(sigGen);
    return new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certificateHolder);
}

19 Source : Deployer4IPhoneIPA.java
with GNU Lesser General Public License v2.1
from TotalCross

/**
 * Generates IPhone application packages.
 */
public clreplaced Deployer4IPhoneIPA {

    // iOS IPA required files
    public static boolean buildIPA;

    public static String certStorePath;

    public static java.io.File mobileProvision;

    public static java.io.File appleCertStore;

    public static KeyStore iosKeyStore;

    public static org.bouncycastle.cert.X509CertificateHolder iosDistributionCertificate;

    public static final String appleRootCA = Convert.appendPath(DeploySettings.etcDir, "tools/ipa/AppleRootCA.pem");

    public static final String appleWWDRCA = Convert.appendPath(DeploySettings.etcDir, "tools/ipa/AppleWWDRCA.pem");

    private Map<String, TFile> ipaContents = new HashMap<String, TFile>();

    static MobileProvision Provision;

    public static boolean isUsingMParam;

    public Deployer4IPhoneIPA() throws Exception {
        if (mobileProvision == null || appleCertStore == null || iosKeyStore == null || iosDistributionCertificate == null) {
            throw new DeployerException("Missing one of required files to build the IPA!");
        }
        // initialize bouncy castle
        Security.addProvider(new BouncyCastleProvider());
        // locate template and target
        File templateFile = new File(Convert.appendPath(DeploySettings.folderTotalCross3DistVM, "ios/TotalCross.ipa"));
        File targetFile = File.createTempFile(DeploySettings.appreplacedle, ".zip");
        targetFile.deleteOnExit();
        // create a copy of the original file
        FileUtils.copyFile(templateFile, targetFile);
        // open new file with truezip
        TFile targetZip = new TFile(targetFile);
        // get the payload folder from the zip
        targetZip.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                ipaContents.put(name, new TFile(dir, name));
                return false;
            }
        });
        TFile payload = (TFile) ipaContents.get("Payload");
        // get the template appFolder - TotalCross.app
        payload.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                ipaContents.put(name, new TFile(dir, name));
                return false;
            }
        });
        TFile appFolder = (TFile) ipaContents.get("TotalCross.app");
        // create new appFolder using the deployed tcz name
        TFile newAppFolder = new TFile(payload, DeploySettings.filePrefix + ".app");
        // rename the appFolder
        appFolder.mv(newAppFolder);
        appFolder = newAppFolder;
        // Add tcz
        for (int i = 0; i < DeploySettings.tczs.length; i++) {
            new TFile(DeploySettings.tczs[i]).cp(new TFile(appFolder, new File(DeploySettings.tczs[i]).getName()));
        }
        // TCBase & other default tczs
        List<File> defaultTczs = DeploySettings.getDefaultTczs();
        for (File file : defaultTczs) {
            new TFile(file).cp(new TFile(appFolder, file.getName()));
        }
        try {
            String google_services_json_path = Utils.findPath("GoogleService-Info.plist", true);
            if (google_services_json_path == null) {
                throw new FileNotFoundException("can't find GoogleService-Info.plist in TotalCross deploy path");
            }
            new TFile(google_services_json_path).cp(new TFile(appFolder, "GoogleService-Info.plist"));
        } catch (FileNotFoundException e) {
            System.out.println("Could not find 'GoogleService-Info.plist', thus Firebase will be ignored further on (iOS deploy)");
        }
        /**
         * Parameter /m deprecated
         */
        if (isUsingMParam) {
            System.out.println("####################################################################################################################");
            System.out.println("Parameter /m is deprecated! Now you can package an ipa file without using certificate. Certificates are required in \n" + "a next step for resigning your iOS app.\n" + "See: https://totalcross.gitbook.io/playbook/learn-totalcross/deploy-your-app-android-ios-and-windows/deploy-ios");
            System.out.println("####################################################################################################################");
        }
        Hashtable ht = new Hashtable(13);
        // guich@tc111_22
        Utils.processInstallFile("iphone.pkg", ht);
        String[] extras = Utils.joinGlobalWithLocals(ht, null, true);
        Vector v = new Vector(extras);
        Utils.preprocessPKG(v, true);
        if (extras.length > 0) {
            TFile pkgFolder = new TFile(appFolder, "pkg");
            pkgFolder.mkdir();
            for (int i = 0; i < extras.length; i++) {
                String fname = extras[i];
                File ff = new File(fname);
                if (!ff.exists()) {
                    ff = new File(Utils.findPath(fname, true));
                }
                // guich@tc310: keep all tczs at the same parent folder
                new TFile(ff.getPath()).cp(new TFile(fname.endsWith(".tcz") ? appFolder : pkgFolder, Utils.getFileName(fname)));
            }
        }
        // get references to the contents of the appFolder
        appFolder.list(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                ipaContents.put(name, new TFile(dir, name));
                return false;
            }
        });
        /**
         * PROCESS INFO.PLIST *
         */
        // read the info.plist from the zip file
        TFile infoPlist = (TFile) ipaContents.get("Info.plist");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        infoPlist.output(baos);
        NSDictionary rootDict = (NSDictionary) PropertyListParser.parse(baos.toByteArray());
        String executableName = rootDict.objectForKey("CFBundleExecutable").toString();
        // add all the iphone icons
        addIcons(appFolder, rootDict);
        // update the application name
        rootDict.put("CFBundleName", DeploySettings.filePrefix);
        rootDict.put("CFBundleDisplayName", DeploySettings.appreplacedle);
        if (DeploySettings.appVersion != null) {
            rootDict.put("CFBundleVersion", DeploySettings.appVersion);
            rootDict.put("CFBundleShortVersionString", DeploySettings.appVersion);
        }
        rootDict.put("UIStatusBarHidden", DeploySettings.isFullScreen);
        // rootDict.put("CFBundleSignature", DeploySettings.applicationId);
        String bundleIdentifier = Provision.bundleIdentifier;
        if (Settings.iosCFBundleIdentifier != null) {
            bundleIdentifier = Settings.iosCFBundleIdentifier;
        } else if (bundleIdentifier.equals("*")) {
            bundleIdentifier = "com." + DeploySettings.applicationId + "." + DeploySettings.appreplacedle.replace(" ", "").trim().toLowerCase();
        }
        Utils.println("Package suffix id (CFBundleIdentifier): " + bundleIdentifier);
        rootDict.put("CFBundleIdentifier", bundleIdentifier);
        // overwrite updated info.plist inside the zip file
        byte[] updatedInfoPlist = MyNSObjectSerializer.toXMLPropertyListBytesUTF8(rootDict);
        infoPlist.input(new ByteArrayInputStream(updatedInfoPlist));
        /**
         * PROCESS CERTIFICATE *
         */
        // install certificates
        CertificateFactory cf = CertificateFactory.getInstance("X509", "BC");
        X509CertificateHolder[] certs = new X509CertificateHolder[3];
        certs[0] = new X509CertificateHolder(cf.generateCertificate(new ByteArrayInputStream(FileUtils.readFileToByteArray(new File(appleRootCA)))).getEncoded());
        certs[1] = new X509CertificateHolder(cf.generateCertificate(new ByteArrayInputStream(FileUtils.readFileToByteArray(new File(appleWWDRCA)))).getEncoded());
        certs[2] = iosDistributionCertificate;
        X509Store certStore = X509Store.getInstance("CERTIFICATE/Collection", new X509CollectionStoreParameters(Arrays.asList(certs)), "BC");
        // provision
        TFile mobileProvision = (TFile) ipaContents.get("embedded.mobileprovision");
        mobileProvision.input(new ByteArrayInputStream(FileUtils.readFileToByteArray(Deployer4IPhoneIPA.mobileProvision)));
        /**
         * CREATE THE MACHOBJECTFILE *
         */
        TFile executable = (TFile) ipaContents.get(executableName);
        // String bundleResourceSpecification = rootDict.objectForKey("CFBundleResourceSpecification").toString();
        byte[] sourceData = this.CreateCodeResourcesDirectory(appFolder, null, executableName);
        ByteArrayOutputStream appStream = new ByteArrayOutputStream();
        executable.output(appStream);
        AppleBinary file = AppleBinary.create(appStream.toByteArray());
        // executable
        executable.input(new ByteArrayInputStream(file.resign(iosKeyStore, certStore, bundleIdentifier, Provision.GetEnreplacedlementsString().getBytes("UTF-8"), updatedInfoPlist, sourceData)));
        TVFS.umount(targetZip);
        FileUtils.copyFile(targetFile, new File(Convert.appendPath(DeploySettings.targetDir, "/ios/" + DeploySettings.filePrefix + ".ipa")));
        System.out.println("... Files written to folder " + Convert.appendPath(DeploySettings.targetDir, "/ios/"));
    }

    private void addIcons(TFile appFolder, NSDictionary rootDict) throws IOException {
        NSString[] icons = new NSString[Bitmaps.IOS_ICONS.length];
        for (int i = icons.length - 1; i >= 0; i--) {
            TFile icon = new TFile(appFolder, Bitmaps.IOS_ICONS[i].name);
            icon.input(new ByteArrayInputStream(Bitmaps.IOS_ICONS[i].getImage()));
            icons[i] = new NSString(Bitmaps.IOS_ICONS[i].name);
        }
        NSArray iconBundle = new NSArray(icons);
        rootDict.put("CFBundleIconFiles", iconBundle);
    }

    protected byte[] CreateCodeResourcesDirectory(TFile appFolder, final String bundleResourceSpecification, final String executableName) throws UnsupportedEncodingException, IOException {
        NSDictionary root = new NSDictionary();
        NSDictionary rules = new NSDictionary();
        rules.put(".*", true);
        rules.put("Info.plist", this.createOmitAndWeight(true, 10));
        // rules.put(bundleResourceSpecification, this.createOmitAndWeight(true, 100));
        root.put("rules", rules);
        // TFile bundleResourceSpecificationFile = (TFile) ipaContents.get(bundleResourceSpecification);
        // bundleResourceSpecificationFile.input(new ByteArrayInputStream(MyNSObjectSerializer.toXMLPropertyListBytesUTF8(root)));
        NSDictionary files = new NSDictionary();
        SHA1Digest digest = new SHA1Digest();
        ByteArrayOutputStream aux = new ByteArrayOutputStream();
        Set<String> ignoredFiles = new HashSet<String>();
        ignoredFiles.add("Info.plist");
        ignoredFiles.add("CodeResources");
        ignoredFiles.add("_CodeSignature/CodeResources");
        ignoredFiles.add("GoogleService-Info.plist");
        // ignoredFiles.add(bundleResourceSpecification);
        ignoredFiles.add(executableName);
        fillCodeResourcesFiles(appFolder, ignoredFiles, files, appFolder.getPath(), aux, digest);
        root = new NSDictionary();
        root.put("files", files);
        root.put("rules", rules);
        byte[] rootBytes = MyNSObjectSerializer.toXMLPropertyListBytesUTF8(root);
        TFile codeResources = new TFile((TFile) ipaContents.get("_CodeSignature"), "CodeResources");
        codeResources.input(new ByteArrayInputStream(rootBytes));
        return rootBytes;
    }

    private NSDictionary createOmitAndWeight(boolean omit, double weight) {
        NSDictionary dictionary = new NSDictionary();
        dictionary.put("omit", true);
        dictionary.put("weight", weight);
        return dictionary;
    }

    private void fillCodeResourcesFiles(TFile rootFile, final Set<String> ignoredFiles, final NSDictionary files, final String removePrefix, final ByteArrayOutputStream aux, final GeneralDigest digest) {
        rootFile.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File arg0, String arg1) {
                TFile parent = (TFile) arg0;
                TFile file = new TFile(parent, arg1);
                String realFilePath = file.getPath().substring(removePrefix.length() + 1).replace('\\', '/');
                if (!ignoredFiles.contains(realFilePath)) {
                    try {
                        if (file.isDirectory()) {
                            fillCodeResourcesFiles(file, ignoredFiles, files, removePrefix, aux, digest);
                        } else {
                            aux.reset();
                            digest.reset();
                            file.output(aux);
                            byte[] b = aux.toByteArray();
                            digest.update(b, 0, b.length);
                            b = new byte[digest.getDigestSize()];
                            digest.doFinal(b, 0);
                            files.put(realFilePath, new NSData(new String(org.bouncycastle.util.encoders.Base64.encode(b))));
                        }
                        return true;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return false;
            }
        });
    }

    public static void iosKeystoreInit() throws Exception {
        // initialize bouncy castle
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        if (appleCertStore != null) {
            CertificateFactory cf = CertificateFactory.getInstance("X509", "BC");
            KeyStore ks = java.security.KeyStore.getInstance("PKCS12", "BC");
            ks.load(new FileInputStream(appleCertStore), "".toCharArray());
            String keyAlias = (String) ks.aliases().nextElement();
            Certificate storecert = ks.getCertificate(keyAlias);
            if (storecert == null) {
                java.io.File[] certsInPath = appleCertStore.getParentFile().listFiles(new FilenameFilter() {

                    @Override
                    public boolean accept(java.io.File arg0, String arg1) {
                        return arg1.endsWith(".cer");
                    }
                });
                if (certsInPath.length == 0) {
                    throw new DeployerException("Distribution certificate was not found in " + appleCertStore.getParent());
                }
                storecert = cf.generateCertificate(new ByteArrayInputStream(FileUtils.readFileToByteArray(certsInPath[0])));
                PrivateKey pk = (PrivateKey) ks.getKey(keyAlias, "".toCharArray());
                ks.deleteEntry(keyAlias);
                ks.setEntry(keyAlias, new KeyStore.PrivateKeyEntry(pk, new Certificate[] { storecert }), new KeyStore.PreplacedwordProtection("".toCharArray()));
            }
            iosKeyStore = ks;
            iosDistributionCertificate = new org.bouncycastle.cert.X509CertificateHolder(storecert.getEncoded());
            Provision = MobileProvision.readFromFile(mobileProvision);
            Settings.iosCertDate = new Time(Provision.expirationDate.getDate().getTime(), false);
            Utils.println("iOS Certificate expiration date: " + Settings.iosCertDate.getSQLString());
        }
    }
}

19 Source : AttestorTest.java
with MIT License
from TokenScript

private byte[] getTBSCert(X509CertificateHolder cert) throws Exception {
    byte[] certBytes = cert.getEncoded();
    ASN1InputStream asnCertStream = new ASN1InputStream(certBytes);
    ASN1Sequence asnCertSeq = ASN1Sequence.getInstance(asnCertStream.readObject());
    // The first object is TBSCert
    return asnCertSeq.getObjectAt(0).toASN1Primitive().getEncoded();
}

19 Source : AttestorTest.java
with MIT License
from TokenScript

@Test
public void testSunshine() throws Exception {
    /* setting up user's key, to sign verifyRequest */
    userKeys = constructSecp256k1Keys(rand);
    SubjectPublicKeyInfo spki = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(userKeys.getPublic());
    byte[] userPK = spki.getPublicKeyData().getEncoded();
    // just to print newly generated public key here:
    // System.out.println(ASN1Util.printDER(userPK, "PUBLIC KEY"));
    /* signing verifyRequest */
    request = Files.readString(Path.of("src/test/data/verification_request.json"));
    Security.addProvider(new BouncyCastleProvider());
    byte[] signature = SignatureUtil.signSha256(request.getBytes(StandardCharsets.UTF_8), userKeys.getPrivate());
    /* build a JSON object for testing */
    HashMap<String, String> csr = new HashMap<>();
    csr.put("verifyRequest", request);
    csr.put("signature", Base64.getEncoder().encodeToString(signature));
    csr.put("publicKey", Base64.getEncoder().encodeToString(userPK));
    System.out.println((new JSONObject(csr)).toString());
    /* obtaining resulting attestations */
    List<X509CertificateHolder> certs = attestor.constructAttestations(request, record, signature, userKeys.getPublic());
    for (X509CertificateHolder cert : certs) {
        System.out.println(ASN1Util.printDER(cert.getEncoded(), "CERTIFICATE"));
        byte[] TBSCert = getTBSCert(cert);
        byte[] certSig = cert.getSignature();
        replacedertions.replacedertTrue(SignatureUtil.verifySha256(TBSCert, certSig, serverKeys.getPublic()));
        replacedertions.replacedertTrue(cert.isValidOn(new Date(System.currentTimeMillis())));
    }
// TODO the code below does not work since only named ECParameters are supported in X509CertImpl
// for (byte[] current : certs) {
// X509Certificate cert = new X509CertImpl(current);
// try {
// cert.verify(serverPK, new BouncyCastleProvider());
// cert.checkValidity();
// } catch (CertificateExpiredException | CertificateNotYetValidException e) {
// replacedert.fail();
// }
// }
}

19 Source : X509CertificateTestUtils.java
with Apache License 2.0
from spiffe

private static X509Certificate getSignedX509Certificate(PrivateKey issuerKey, JcaX509v3CertificateBuilder builder) throws OperatorCreationException, CertificateException {
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").build(issuerKey);
    X509CertificateHolder certHolder = builder.build(signer);
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}

19 Source : HttpVerificationService.java
with Apache License 2.0
from SmartThingsCommunity

private PublicKey parsePublicKey(String publicKeyString) {
    try (PEMParser parser = new PEMParser(new StringReader(publicKeyString))) {
        SubjectPublicKeyInfo info;
        Object object = parser.readObject();
        if (object instanceof X509CertificateHolder) {
            X509CertificateHolder cert = (X509CertificateHolder) object;
            info = cert.getSubjectPublicKeyInfo();
        } else if (object instanceof SubjectPublicKeyInfo) {
            info = (SubjectPublicKeyInfo) object;
        } else {
            throw new RuntimeException("Public key not found or unknown type");
        }
        RSAKeyParameters param = (RSAKeyParameters) PublicKeyFactory.createKey(info);
        RSAPublicKeySpec spec = new RSAPublicKeySpec(param.getModulus(), param.getExponent());
        return KeyFactory.getInstance("RSA").generatePublic(spec);
    } catch (IOException e) {
        throw new RuntimeException("IOException trying to create public key from PEM", e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("NoSuchAlgorithmException trying to create public key from PEM", e);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("InvalidKeySpecException trying to create public key from PEM", e);
    }
}

19 Source : SslUtil.java
with MIT License
from SDA-SE

private static X509Certificate parseCert(PEMParser parser) throws IOException, CertificateException {
    Object certificateObject = parser.readObject();
    if (certificateObject == null) {
        return null;
    }
    if (certificateObject instanceof X509CertificateHolder) {
        X509CertificateHolder certHolder = (X509CertificateHolder) certificateObject;
        return new JcaX509CertificateConverter().getCertificate(certHolder);
    }
    if (certificateObject instanceof X509TrustedCertificateBlock) {
        X509CertificateHolder certHolder = ((X509TrustedCertificateBlock) certificateObject).getCertificateHolder();
        return new JcaX509CertificateConverter().getCertificate(certHolder);
    }
    throw new CertificateException("Could not read certificate of type " + certificateObject.getClreplaced());
}

19 Source : RootCertificateImpl.java
with BSD 3-Clause "New" or "Revised" License
from salesforce

clreplaced RootCertificateImpl extends CertificateWithPrivateKeyImpl implements RootCertificate {

    private final X509CertificateHolder caCertificateHolder;

    RootCertificateImpl(final X509Certificate caCertificate, final PrivateKey caPrivateKey) {
        super(caCertificate, caPrivateKey);
        try {
            this.caCertificateHolder = new X509CertificateHolder(caCertificate.getEncoded());
        } catch (CertificateEncodingException | IOException e) {
            throw new CaException(e);
        }
    }

    @Override
    public Signer signCsr(final CSR request) {
        final KeyPair pair = new KeyPair(getX509Certificate().getPublicKey(), getPrivateKey());
        final DistinguishedName signerSubject = dn(caCertificateHolder.getSubject());
        return new SignerImpl(pair, signerSubject, request.getPublicKey(), request.getSubject());
    }
}

19 Source : KeyGenerator.java
with GNU Affero General Public License v3.0
from republique-et-canton-de-geneve

private java.security.cert.Certificate createCertificate(X509v3CertificateBuilder certificateBuilder, ContentSigner signer) throws CertificateException, IOException {
    X509CertificateHolder certificateHolder = certificateBuilder.build(signer);
    return CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded()));
}

19 Source : SignerCredential.java
with Apache License 2.0
from nsacyber

public clreplaced SignerCredential {

    private PrivateKeyInfo key;

    private X509CertificateHolder cert;

    private x509type privateKeyType;

    public static final SignerCredential createCredential(String alg) {
        x509type type = findType(alg);
        return new SignerCredential(type);
    }

    private SignerCredential(x509type type) {
        this.privateKeyType = type;
    }

    public final void loadCertificate(X509Certificate c) throws IOException {
        if (c == null) {
            throw new IllegalArgumentException("Input was null.");
        } else if (findType(c.getSigAlgOID()) != privateKeyType) {
            throw new IllegalArgumentException("Expected certificate key algorithm to be " + privateKeyType.getPemObjectType());
        }
        try {
            cert = new X509CertificateHolder(c.getEncoded());
        } catch (CertificateEncodingException e) {
            throw new IOException(e);
        }
    }

    public final void loadCertificate(X509CertificateHolder c) {
        if (c == null) {
            throw new IllegalArgumentException("Input was null.");
        } else if (findType(c.getSubjectPublicKeyInfo().getAlgorithm().getAlgorithm()) != privateKeyType) {
            throw new IllegalArgumentException("Expected certificate key algorithm to be " + privateKeyType.getPemObjectType());
        }
        cert = c;
    }

    public final void loadPrivateKey(PrivateKey pk) throws IOException {
        if (pk == null) {
            throw new IllegalArgumentException("Input was null.");
        } else if (findType(pk.getAlgorithm()) != privateKeyType) {
            throw new IllegalArgumentException("Expected private key algorithm to be " + privateKeyType.getPemObjectType());
        }
        AsymmetricKeyParameter param = null;
        try {
            switch(privateKeyType) {
                case // Copy of BouncyCastle RSAUtil#generatePrivateKeyParameter because it is protected whereas EC and DSA versions are public
                RSA_PRIVATE_KEY:
                    if (pk instanceof RSAPrivateCrtKey) {
                        RSAPrivateCrtKey k = (RSAPrivateCrtKey) pk;
                        param = new RSAPrivateCrtKeyParameters(k.getModulus(), k.getPublicExponent(), k.getPrivateExponent(), k.getPrimeP(), k.getPrimeQ(), k.getPrimeExponentP(), k.getPrimeExponentQ(), k.getCrtCoefficient());
                    } else if (pk instanceof RSAPrivateKey) {
                        RSAPrivateKey k = (RSAPrivateKey) pk;
                        param = new RSAKeyParameters(true, k.getModulus(), k.getPrivateExponent());
                    }
                    break;
                case EC_PRIVATE_KEY:
                    param = ECUtil.generatePrivateKeyParameter(pk);
                    break;
                case DSA_PRIVATE_KEY:
                    param = DSAUtil.generatePrivateKeyParameter(pk);
                    break;
                default:
            }
        } catch (ClreplacedCastException | InvalidKeyException e) {
            throw new IOException(e);
        }
        if (param == null) {
            throw new IOException("Private key type not supported.");
        }
        key = PrivateKeyInfoFactory.createPrivateKeyInfo(param);
    }

    public final void loadPrivateKey(PrivateKeyInfo pk) {
        if (pk == null) {
            throw new IllegalArgumentException("Input was null.");
        } else if (findType(pk.getPrivateKeyAlgorithm().getAlgorithm()) != privateKeyType) {
            throw new IllegalArgumentException("Expected private key algorithm to be " + privateKeyType.getPemObjectType());
        }
        key = pk;
    }

    public static final x509type findType(final String algStr) {
        x509type keyType = null;
        String keyAlg = algStr.toLowerCase();
        switch(keyAlg) {
            case "rsa":
                keyType = x509type.RSA_PRIVATE_KEY;
                break;
            case "dsa":
                keyType = x509type.DSA_PRIVATE_KEY;
                break;
            case "ec":
                keyType = x509type.EC_PRIVATE_KEY;
                break;
            default:
                try {
                    keyType = findType(new ASN1ObjectIdentifier(algStr));
                } catch (IllegalArgumentException e) {
                // null check will report error
                }
        }
        if (keyType == null) {
            throw new IllegalArgumentException("Unsupported key pair algorithm (" + keyType + ").  See the Supported Signing Algorithms section of the User Guide.");
        }
        return keyType;
    }

    public static final x509type findType(final ASN1ObjectIdentifier oid) {
        x509type keyType = null;
        if (SupportedAlgorithms.ECDSA_BASED_SIGALGS.contains(oid) || SupportedAlgorithms.EC.equals(oid)) {
            keyType = x509type.EC_PRIVATE_KEY;
        } else if (SupportedAlgorithms.DSA_BASED_SIGALGS.contains(oid) || SupportedAlgorithms.DSA.equals(oid)) {
            keyType = x509type.DSA_PRIVATE_KEY;
        } else if (SupportedAlgorithms.RSA_BASED_SIGALGS.contains(oid) || SupportedAlgorithms.RSA.equals(oid)) {
            keyType = x509type.RSA_PRIVATE_KEY;
        } else {
            throw new IllegalArgumentException("Unsupported algorithm");
        }
        return keyType;
    }

    public final PrivateKeyInfo getPrivateKey() {
        return key;
    }

    public final X509CertificateHolder getCertificate() {
        return cert;
    }

    public final x509type getKeyType() {
        return privateKeyType;
    }

    public final boolean hasKey() {
        return key != null;
    }

    public final boolean hasCertificate() {
        return cert != null;
    }
}

19 Source : SignerCredential.java
with Apache License 2.0
from nsacyber

public final void loadCertificate(X509CertificateHolder c) {
    if (c == null) {
        throw new IllegalArgumentException("Input was null.");
    } else if (findType(c.getSubjectPublicKeyInfo().getAlgorithm().getAlgorithm()) != privateKeyType) {
        throw new IllegalArgumentException("Expected certificate key algorithm to be " + privateKeyType.getPemObjectType());
    }
    cert = c;
}

19 Source : ValidatorCli.java
with Apache License 2.0
from nsacyber

public boolean handleCommandLine(String[] args) throws IOException {
    JCommander jCommanderBuild = JCommander.newBuilder().addObject(argList).build();
    jCommanderBuild.setProgramName("validator");
    jCommanderBuild.setAcceptUnknownOptions(true);
    jCommanderBuild.parse(args);
    if (argList.isHelp()) {
        jCommanderBuild.usage();
        System.exit(1);
    }
    // load the public certificate of the key that signed the attribute cert
    X509CertificateHolder signingKeyPublicCert = (X509CertificateHolder) CliHelper.loadCert(argList.getPublicKeyCert(), x509type.CERTIFICATE);
    // load the signed attribute certificate which requires signature verification
    X509AttributeCertificateHolder attributeCert = (X509AttributeCertificateHolder) CliHelper.loadCert(argList.getX509v2AttrCert(), x509type.ATTRIBUTE_CERTIFICATE);
    boolean valid = false;
    try {
        // Choose the verifier based on the public certificate signature algorithm
        ContentVerifierProvider cvp = new PcBcContentVerifierProviderBuilder(new DefaultDigestAlgorithmIdentifierFinder()).build(signingKeyPublicCert);
        // Verify the signature
        valid = attributeCert.isSignatureValid(cvp);
    } catch (OperatorCreationException | CertException e) {
        throw new IllegalArgumentException(e);
    }
    return valid;
}

19 Source : BouncyCastleSecurityProviderTool.java
with MIT License
from misakuo

/**
 * Converts a Bouncy Castle X509CertificateHolder into a JCA X590Certificate.
 *
 * @param bouncyCastleCertificate BC X509CertificateHolder
 * @return JCA X509Certificate
 */
private static X509Certificate convertToJcaCertificate(X509CertificateHolder bouncyCastleCertificate) {
    try {
        return new JcaX509CertificateConverter().getCertificate(bouncyCastleCertificate);
    } catch (CertificateException e) {
        throw new CertificateCreationException("Unable to convert X590CertificateHolder to JCA X590Certificate", e);
    }
}

19 Source : Crypto.java
with MIT License
from jenkinsci

public static X509Certificate newSelfSignedCertificate(String name, KeyPair keyPair) {
    try {
        final X500Name cn = new X500Name(name);
        final Date notBefore = new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 30));
        final Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 99));
        final BigInteger serial = BigInteger.valueOf(Math.abs(new SecureRandom().nextInt()));
        final X509v3CertificateBuilder b = new JcaX509v3CertificateBuilder(cn, serial, notBefore, notAfter, cn, keyPair.getPublic());
        final X509CertificateHolder holder = b.build(new JcaContentSignerBuilder("SHA1withRSA").build(keyPair.getPrivate()));
        return new JcaX509CertificateConverter().getCertificate(holder);
    } catch (CertificateException | OperatorCreationException e) {
        throw new RuntimeException(e);
    }
}

19 Source : Identities.java
with Apache License 2.0
from hyperledger

/**
 * Read a PEM format X.509 certificate.
 * @param pemReader Reader of PEM data.
 * @return An X.509 certificate.
 * @throws IOException if an error occurs reading data.
 * @throws CertificateException if the data is not valid X.509 certificate PEM.
 */
public static X509Certificate readX509Certificate(final Reader pemReader) throws IOException, CertificateException {
    try {
        Object pemObject = readPemObject(pemReader);
        X509CertificateHolder certificateHolder = asX509CertificateHolder(pemObject);
        return new JcaX509CertificateConverter().getCertificate(certificateHolder);
    } catch (PEMException e) {
        throw new CertificateException(e);
    }
}

19 Source : CaManagerImpl.java
with GNU Affero General Public License v3.0
from HermesGermany

private X509Certificate createSignedPemCertificate(PKCS10CertificationRequest csr, X500Name dn, StringBuilder pemDataHolder, long validityMs) throws CertificateException {
    try {
        X509CertificateHolder holder = signCertificateRequest(csr, dn, validityMs);
        StringWriter sw = new StringWriter();
        try (PemWriter writer = new PemWriter(sw)) {
            writer.writeObject(new MiscPEMGenerator(holder));
        }
        pemDataHolder.append(sw.toString());
        return new JcaX509CertificateConverter().getCertificate(holder);
    } catch (IOException e) {
        throw new CertificateException("Exception during reading certificate data", e);
    } catch (OperatorCreationException e) {
        throw new CertificateException("Could not sign certificate", e);
    } catch (CertificateParsingException e) {
        throw e;
    } catch (GeneralSecurityException e) {
        // intentional RuntimeException as this should fall through
        throw new RuntimeException("Missing algorithm or other configuration problem for certificate signing", e);
    }
}

19 Source : CertificateManager.java
with GNU General Public License v3.0
from GravitLauncher

public X509CertificateHolder readCertificate(Reader reader) throws IOException {
    X509CertificateHolder ret;
    try (PemReader reader1 = new PemReader(reader)) {
        byte[] bytes = reader1.readPemObject().getContent();
        ret = new X509CertificateHolder(bytes);
    }
    return ret;
}

19 Source : CertificateManager.java
with GNU General Public License v3.0
from GravitLauncher

public void writeCertificate(Writer writer, X509CertificateHolder holder) throws IOException {
    try (PemWriter writer1 = new PemWriter(writer)) {
        writer1.writeObject(new PemObject("CERTIFICATE", holder.toASN1Structure().getEncoded()));
    }
}

19 Source : CertificateUtils.java
with Apache License 2.0
from eu-federation-gateway-service

/**
 * Calculates the SHA-256 thumbprint of X509CertificateHolder.
 *
 * @param x509CertificateHolder the certificate the thumbprint should be calculated for.
 * @return 32-byte SHA-256 hash as hex encoded string
 */
public static String getCertThumbprint(X509CertificateHolder x509CertificateHolder) {
    try {
        return calculateHash(x509CertificateHolder.getEncoded());
    } catch (IOException | NoSuchAlgorithmException e) {
        log.error("Could not calculate thumbprint of certificate.");
        return null;
    }
}

19 Source : BatchSignatureVerifier.java
with Apache License 2.0
from eu-federation-gateway-service

private boolean verifySignerInfo(final SignerInformation signerInfo, final X509CertificateHolder signerCert) throws CertificateException, OperatorCreationException, CMSException {
    return signerInfo.verify(createSignerInfoVerifier(signerCert));
}

19 Source : BatchSignatureVerifier.java
with Apache License 2.0
from eu-federation-gateway-service

private SignerInformationVerifier createSignerInfoVerifier(final X509CertificateHolder signerCert) throws OperatorCreationException, CertificateException {
    return new JcaSimpleSignerInfoVerifierBuilder().build(signerCert);
}

19 Source : BatchSignatureVerifier.java
with Apache License 2.0
from eu-federation-gateway-service

private boolean allOriginsMatchingCertCountry(DiagnosisKeyBatch batch, X509CertificateHolder certificate) {
    String country = getCountryOfCertificate(certificate);
    if (country == null) {
        return false;
    } else {
        return batch.getKeysList().stream().allMatch(key -> key.getOrigin().equals(country));
    }
}

19 Source : BatchSignatureVerifier.java
with Apache License 2.0
from eu-federation-gateway-service

private String checkCertValidityAndReturnThumbprint(X509CertificateHolder certificate) {
    String certHash = CertificateUtils.getCertThumbprint(certificate);
    Optional<CertificateEnreplacedy> certificateEnreplacedy = certificateService.getCertificate(certHash, getCountryOfCertificate(certificate), CertificateEnreplacedy.CertificateType.SIGNING);
    EfgsMdc.put("certThumbprint", certHash);
    if (certificateEnreplacedy.isEmpty()) {
        log.error("unknown signing certificate");
        return null;
    }
    if (certificateEnreplacedy.get().getRevoked().equals(Boolean.TRUE)) {
        log.error("certificate is revoked");
        return null;
    }
    return certHash;
}

19 Source : BatchSignatureVerifier.java
with Apache License 2.0
from eu-federation-gateway-service

private String getCountryOfCertificate(X509CertificateHolder certificate) {
    RDN[] rdns = certificate.getSubject().getRDNs(BCStyle.C);
    if (rdns.length != 1) {
        log.info("Certificate has no valid country attribute");
        return null;
    } else {
        return rdns[0].getFirst().getValue().toString();
    }
}

19 Source : BatchSignatureVerifier.java
with Apache License 2.0
from eu-federation-gateway-service

private boolean isCertNotExpired(X509CertificateHolder certificate) {
    Date now = new Date();
    return certificate.getNotBefore().before(now) && certificate.getNotAfter().after(now);
}

19 Source : BatchSignatureVerifier.java
with Apache License 2.0
from eu-federation-gateway-service

/**
 * Verifies the signature of a batch. The signature is an PKCS#7 object encoded with base64.
 *
 * @param batch                the {@link DiagnosisKeyBatch} object that corresponds to the batch signature.
 * @param base64BatchSignature the base64-encoded batch signature to be verified.
 * @return true if the batch signature is correct. False otherwise.
 */
public String checkBatchSignature(final DiagnosisKeyBatch batch, final String base64BatchSignature) {
    final byte[] batchSignatureBytes = BatchSignatureUtils.b64ToBytes(base64BatchSignature);
    if (batchSignatureBytes.length > 0) {
        try {
            final CMSSignedData signedData = new CMSSignedData(getBatchBytes(batch), batchSignatureBytes);
            final SignerInformation signerInfo = getSignerInformation(signedData);
            if (signerInfo == null) {
                log.error("no signer information");
                return null;
            }
            final X509CertificateHolder signerCert = getSignerCert(signedData.getCertificates(), signerInfo.getSID());
            if (signerCert == null) {
                log.error("no signer certificate");
                return null;
            }
            EfgsMdc.put("certNotBefore", signerCert.getNotBefore());
            EfgsMdc.put("certNotAfter", signerCert.getNotAfter());
            if (!isCertNotExpired(signerCert)) {
                log.error("signing certificate expired");
                return null;
            }
            String signingCertThumbprint = checkCertValidityAndReturnThumbprint(signerCert);
            if (signingCertThumbprint == null) {
                log.error("invalid signing certificate signature");
                return null;
            }
            if (!allOriginsMatchingCertCountry(batch, signerCert)) {
                log.error("different origins");
                return null;
            }
            if (!verifySignerInfo(signerInfo, signerCert)) {
                return null;
            }
            return signingCertThumbprint;
        } catch (CertificateException | OperatorCreationException | CMSException | IllegalArgumentException e) {
            log.error("error verifying batch signature", e);
        }
    }
    return null;
}

19 Source : SigUtils.java
with MIT License
from ekojs

public static void validateTimestampToken(TimeStampToken timeStampToken) throws IOException, CertificateException, TSPException, OperatorCreationException {
    // https://stackoverflow.com/questions/42114742/
    // TimeStampToken.getSID() is untyped
    @SuppressWarnings("unchecked")
    Collection<X509CertificateHolder> tstMatches = timeStampToken.getCertificates().getMatches((Selector<X509CertificateHolder>) timeStampToken.getSID());
    X509CertificateHolder certificateHolder = tstMatches.iterator().next();
    SignerInformationVerifier siv = new JcaSimpleSignerInfoVerifierBuilder().setProvider(SecurityProvider.getProvider()).build(certificateHolder);
    timeStampToken.validate(siv);
}

19 Source : CertUtil.java
with Apache License 2.0
from dushitaoyuan

/**
 * 读取x509 证书
 *
 * @param pemPath
 * @return
 */
public static X509Certificate readX509Cert(String savePath) throws CertException {
    try {
        if (null == savePath) {
            throw new CertException("save path can't be null");
        }
        PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream(savePath)));
        Object readObject = pemParser.readObject();
        if (readObject instanceof X509CertificateHolder) {
            X509CertificateHolder holder = (X509CertificateHolder) readObject;
            return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(holder);
        }
        pemParser.close();
        throw new CertException(savePath + "file read format failed");
    } catch (Exception e) {
        throw new CertException("read x509 cert failed", e);
    }
}

19 Source : CertUtil.java
with Apache License 2.0
from dushitaoyuan

/**
 * 创建ca私钥签名证书
 *
 * @param publicKey
 * @param privateKey
 * @param issuerDN
 * @param userDN
 * @param notBefore
 * @param notAfter
 * @param serialNumber
 * @param signAlg
 * @return
 * @throws CertException
 */
public static X509Certificate makeUserCert(PublicKey publicKey, PublicKey caPublicKey, PrivateKey caPrivateKey, String issuerDN, String userDN, Date notBefore, Date notAfter, BigInteger serialNumber, String signAlg) throws CertException {
    try {
        if (null == signAlg) {
            throw new CertException(signAlg + " can't be null");
        }
        X500Name issuer = new X500Name(issuerDN);
        // 1. 创建签名
        ContentSigner signer = new JcaContentSignerBuilder(signAlg).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(caPrivateKey);
        // 2. 创建证书请求
        PKCS10CertificationRequestBuilder pkcs10CertificationRequestBuilder = new JcaPKCS10CertificationRequestBuilder(new X500Name(userDN), publicKey);
        PKCS10CertificationRequest pkcs10CertificationRequest = pkcs10CertificationRequestBuilder.build(signer);
        // 3. 创建证书
        // SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        SubjectPublicKeyInfo subPubKeyInfo = pkcs10CertificationRequest.getSubjectPublicKeyInfo();
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serialNumber, notBefore, notAfter, pkcs10CertificationRequest.getSubject(), subPubKeyInfo);
        // 添加扩展信息 见 X509CertExtensions
        X509CertExtensions.buildAllExtensions(certBuilder, publicKey, caPublicKey);
        X509CertificateHolder holder = certBuilder.build(signer);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(holder);
    } catch (Exception e) {
        throw new CertException("makeUserCert failed", e);
    }
}

19 Source : CertUtil.java
with Apache License 2.0
from dushitaoyuan

/**
 * 创建一个自签名的证书
 *
 * @param publicKey
 * @param privateKey
 * @param userDN
 * @param notBefore
 * @param notAfter
 * @param serialNumber
 * @param signAlg
 * @return
 * @throws CertException
 */
public static X509Certificate makeUserSelfSignCert(PublicKey publicKey, PrivateKey privateKey, String userDN, Date notBefore, Date notAfter, BigInteger serialNumber, String signAlg) throws CertException {
    try {
        if (null == signAlg) {
            throw new CertException(signAlg + " can't be null");
        }
        X500Name issuer = new X500Name(userDN);
        // 1. 创建签名
        ContentSigner signer = new JcaContentSignerBuilder(signAlg).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(privateKey);
        // 2. 创建证书请求
        PKCS10CertificationRequestBuilder pkcs10CertificationRequestBuilder = new JcaPKCS10CertificationRequestBuilder(issuer, publicKey);
        PKCS10CertificationRequest pkcs10CertificationRequest = pkcs10CertificationRequestBuilder.build(signer);
        // 3. 创建证书
        // SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serialNumber, notBefore, notAfter, pkcs10CertificationRequest.getSubject(), pkcs10CertificationRequest.getSubjectPublicKeyInfo());
        // 添加扩展信息 见 X509CertExtensions
        X509CertExtensions.buildAllExtensions(certBuilder, publicKey, publicKey);
        X509CertificateHolder holder = certBuilder.build(signer);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(holder);
    } catch (Exception e) {
        throw new CertException("makeUserSelfSignCert failed", e);
    }
}

19 Source : CA.java
with Apache License 2.0
from DeNA

public KeyStore createKeyStore(String commonName, String[] domainNames) throws Exception {
    /* シリアルナンバーの設定 */
    MessageDigest digest = MessageDigest.getInstance("MD5");
    byte[] hash = digest.digest(commonName.getBytes());
    BigInteger templateSerial = new BigInteger(hash);
    /* Subjectの設定 */
    X500Name templateSubject = new X500Name(createSubject(commonName));
    /* Builderの生成 */
    X509v3CertificateBuilder serverBuilder = new X509v3CertificateBuilder(templateIssuer, templateSerial, templateFrom, templateTo, templateSubject, templatePubKey);
    /* SANの設定 */
    ArrayList<ASN1Encodable> sans = new ArrayList<>();
    sans.add(new GeneralName(GeneralName.dNSName, createCNforSAN(commonName)));
    for (String domainName : domainNames) {
        // System.out.println(domainName);
        sans.add(new GeneralName(GeneralName.dNSName, domainName));
    }
    DERSequence subjectAlternativeNames = new DERSequence(sans.toArray(new ASN1Encodable[sans.size()]));
    serverBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAlternativeNames);
    // 署名
    X509CertificateHolder serverHolder = serverBuilder.build(createSigner());
    /* 新しいKeyStoreを作成 */
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, preplacedword);
    ks.setKeyEntry(alireplacederver, keyPair.getPrivate(), preplacedword, new java.security.cert.Certificate[] { certFactory.generateCertificate(new ByteArrayInputStream(serverHolder.getEncoded())), certFactory.generateCertificate(new ByteArrayInputStream(caRootHolder.getEncoded())) });
    return ks;
}

19 Source : CAdESSigner.java
with GNU Lesser General Public License v3.0
from demoiselle

private Collection<X509Certificate> getSignersCertificates(CMSSignedData previewSignerData) {
    Collection<X509Certificate> result = new HashSet<X509Certificate>();
    Store<?> certStore = previewSignerData.getCertificates();
    SignerInformationStore signers = previewSignerData.getSignerInfos();
    Iterator<?> it = signers.getSigners().iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        @SuppressWarnings("unchecked")
        Collection<?> certCollection = certStore.getMatches(signer.getSID());
        Iterator<?> cerreplaced = certCollection.iterator();
        X509CertificateHolder certificateHolder = (X509CertificateHolder) cerreplaced.next();
        try {
            result.add(new JcaX509CertificateConverter().getCertificate(certificateHolder));
        } catch (CertificateException error) {
        }
    }
    return result;
}

19 Source : PKCS7Manager.java
with GNU Affero General Public License v3.0
from damianofalcioni

public static boolean verifyAllSignatures(CMSSignedData cmsSignedData) {
    try {
        if (Security.getProvider("BC") == null)
            Security.addProvider(new BouncyCastleProvider());
        Collection<SignerInformation> signers = cmsSignedData.getSignerInfos().getSigners();
        for (SignerInformation si : signers) {
            @SuppressWarnings("unchecked")
            Collection<X509CertificateHolder> certList = cmsSignedData.getCertificates().getMatches(si.getSID());
            if (certList.size() == 0)
                throw new Exception("ERROR: Impossible to find a Certificate using the Signer ID: " + si.getSID());
            // Take only the first certificate of the chain
            X509CertificateHolder cert = certList.iterator().next();
            if (!si.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)))
                throw new Exception("ATTENTION: At least a signature is invalid!");
            boolean certOK = true;
            String msg = "";
            try {
                X509Utils.checkAllOnCertificate(X509Utils.getX509Certificate(cert.getEncoded()));
            } catch (Exception ex) {
                msg = ex.getMessage();
                certOK = false;
            }
            if (!certOK)
                throw new Exception("ATTENTION: The certificate is invalid:\n" + msg);
        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

19 Source : PKCS7Manager.java
with GNU Affero General Public License v3.0
from damianofalcioni

public static boolean verifySignatureOfUser(byte[] PKCS7Content, String userCF) {
    try {
        if (userCF == null || userCF.equals(""))
            throw new Exception("ERROR: userCF can not be null or empty");
        if (Security.getProvider("BC") == null)
            Security.addProvider(new BouncyCastleProvider());
        CMSSignedData cmsSignedData = new CMSSignedData(PKCS7Content);
        boolean findedCert = false;
        int invalidCerts = 0;
        Collection<SignerInformation> signers = cmsSignedData.getSignerInfos().getSigners();
        for (SignerInformation si : signers) {
            @SuppressWarnings("unchecked")
            Collection<X509CertificateHolder> certList = cmsSignedData.getCertificates().getMatches(si.getSID());
            X509CertificateHolder cert = certList.iterator().next();
            if (cert.getSubject().toString().toLowerCase().contains(userCF.toLowerCase())) {
                findedCert = true;
                if (si.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) {
                    boolean certOK = true;
                    try {
                        X509Utils.checkAllOnCertificate(X509Utils.getX509Certificate(cert.getEncoded()));
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        certOK = false;
                    }
                    if (certOK)
                        return true;
                    else
                        invalidCerts++;
                } else
                    invalidCerts++;
            }
        }
        if (!findedCert)
            throw new Exception("ATTENTION: No certificate found in the PKCS7 data that contain the CF " + userCF + " in its subjectDN");
        if (invalidCerts != 0)
            throw new Exception("ATTENTION: N. " + invalidCerts + " certificates replacedociated to the user " + userCF + " seems to be invalid. Please check them!");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

19 Source : CMSSignedDataWrapper.java
with GNU Affero General Public License v3.0
from damianofalcioni

public void addCert(Store<X509CertificateHolder> certStore) throws Exception {
    if (certStore == null)
        return;
    Collection<X509CertificateHolder> certStoreList = certStore.getMatches(null);
    for (X509CertificateHolder cert : certStoreList) addCert(cert.getEncoded());
}

19 Source : JwtServiceTest.java
with Apache License 2.0
from corona-warn-app

private String generateTestCertificate() throws Exception {
    // KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
    // KeyPair pair = kpGen.generateKeyPair();
    LocalDateTime startDate = LocalDate.now().atStartOfDay();
    X509v3CertificateBuilder builder = new X509v3CertificateBuilder(new X500Name("CN=ca"), new BigInteger("0"), Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant()), Date.from(startDate.plusDays(3650).atZone(ZoneId.systemDefault()).toInstant()), new X500Name("CN=ca"), SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()));
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA512WithRSAEncryption");
    ContentSigner signer = csBuilder.build(privateKey);
    X509CertificateHolder holder = builder.build(signer);
    StringWriter writer = new StringWriter();
    PemWriter pemWriter = new PemWriter(writer);
    try {
        pemWriter.writeObject(new PemObject("CERTIFICATE", holder.toASN1Structure().getEncoded()));
        pemWriter.flush();
        pemWriter.close();
    } catch (IOException ex) {
        log.warn("Error writeObject: {}.", ex.getMessage());
    }
    return writer.toString();
}

19 Source : SslServletContainerCustomizer.java
with Apache License 2.0
from codeabovelab

private KeystoreConfig configureKeystore() {
    Set<String> names = new HashSet<>();
    if (this.preconfiguredNames != null) {
        for (String name : this.preconfiguredNames) {
            if (StringUtils.hasText(name)) {
                names.add(name);
            }
        }
    }
    CertificateGenerator.gatherNames(names, this.resolve);
    X509CertificateHolder rootCert;
    PrivateKey rootKey;
    try {
        if (rootCertKeystore == null || rootCertKeystorePreplaced == null) {
            log.warn("Keystore {} or its preplacedword {} is null, skip.", rootCertKeystore, rootCertKeystorePreplaced);
            return null;
        }
        KeyStore ks = KeyStore.getInstance("JKS");
        Resource resource = resourceLoader.getResource(rootCertKeystore);
        if (!resource.exists()) {
            log.warn("Keystore {} is not an exists.", rootCertKeystore);
            return null;
        }
        try (InputStream is = resource.getInputStream()) {
            ks.load(is, rootCertKeystorePreplaced.toCharArray());
        }
        rootKey = (PrivateKey) ks.getKey(rootCertKeysoreAlias, rootCertKeystoreKeyPreplaced.toCharArray());
        replacedert.notNull(rootKey, "Can not find " + rootCertKeysoreAlias + " in " + rootCertKeystore);
        Certificate[] certs = ks.getCertificateChain(rootCertKeysoreAlias);
        replacedert.isTrue(certs != null && certs.length == 1, "Certificate chain of " + rootCertKeysoreAlias + " alias is null or has invalid count of certificates, wanted one.");
        rootCert = new X509CertificateHolder(certs[0].getEncoded());
    } catch (Exception e) {
        log.error("Can not load keystore with root certificate from {}", rootCertKeystore, e);
        return null;
    }
    try {
        File ksf = new File(keystore);
        ksf.getParentFile().mkdirs();
        return CertificateGenerator.constructCert(rootCert, rootKey, ksf, names);
    } catch (Exception e) {
        log.error("Can not generate cert.", e);
        return null;
    }
}

19 Source : CertificateGenerator.java
with Apache License 2.0
from codeabovelab

private static Certificate toJava(X509CertificateHolder certHolder) throws Exception {
    return new X509CertificateObject(certHolder.toASN1Structure());
}

19 Source : SamlKeyStoreProvider.java
with GNU General Public License v2.0
from CipherChina

public static X509CertificateHolder generateCertificate(PrivateKey privateKey, PublicKey publicKey, String issuer, int expireInDays) throws GeneralSecurityException, IOException {
    Date notBefore = new Date();
    Date notAfter = new Date(notBefore.getTime() + 86400000L * (long) expireInDays);
    X500Name issueDn = new X500Name(issuer);
    X500Name subjectDn = new X500Name(issuer);
    BigInteger serail = BigInteger.probablePrime(32, new Random());
    try {
        SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance((new ASN1InputStream(publicKey.getEncoded())).readObject());
        X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issueDn, serail, notBefore, notAfter, subjectDn, subjectPublicKeyInfo);
        ContentSigner sigGen = (new JcaContentSignerBuilder("SHA256withRSA")).build(privateKey);
        X509CertificateHolder holder = builder.build(sigGen);
        return holder;
    } catch (OperatorCreationException e) {
        e.printStackTrace();
    }
    return null;
}

19 Source : Test2Controller.java
with GNU General Public License v2.0
from CipherChina

public static X509CertificateHolder generateCertificate(KeyPair keyPair, String issuer, int expireInDays) throws GeneralSecurityException, IOException {
    Date notBefore = new Date();
    Date notAfter = new Date(notBefore.getTime() + 86400000L * (long) expireInDays);
    X500Name issueDn = new X500Name(issuer);
    X500Name subjectDn = new X500Name(issuer);
    BigInteger serail = BigInteger.probablePrime(32, new Random());
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();
    try {
        SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance((new ASN1InputStream(publicKey.getEncoded())).readObject());
        X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issueDn, serail, notBefore, notAfter, subjectDn, subjectPublicKeyInfo);
        ContentSigner sigGen = (new JcaContentSignerBuilder("SHA256withRSA")).build(privateKey);
        X509CertificateHolder holder = builder.build(sigGen);
        return holder;
    } catch (OperatorCreationException e) {
        e.printStackTrace();
    }
    return null;
}

19 Source : TestSignatures.java
with Apache License 2.0
from bft-smart

private static void parseCertificate(String filename) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(filename));
    PEMParser pp = new PEMParser(br);
    X509CertificateHolder certificate = (X509CertificateHolder) pp.readObject();
    PemObject pemObj = (new PemObject("", certificate.getEncoded()));
    StringWriter strWriter = new StringWriter();
    PemWriter writer = new PemWriter(strWriter);
    writer.writeObject(pemObj);
    writer.close();
    strWriter.close();
    TestSignatures.serializedCert = strWriter.toString().getBytes();
}

19 Source : OadrPKISecurity.java
with Apache License 2.0
from avob

public static X509Certificate parseCertificate(FileReader fileReader) throws OadrSecurityException {
    Object readObject;
    try {
        readObject = parsePem(fileReader);
        if (readObject instanceof X509CertificateHolder) {
            X509CertificateHolder certHolder = (X509CertificateHolder) readObject;
            return new JcaX509CertificateConverter().setProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()).getCertificate(certHolder);
        } else {
            throw new OadrSecurityException("certificate file does not have good format");
        }
    } catch (CertificateException e) {
        throw new OadrSecurityException(e);
    }
}

19 Source : CertificateGenerator.java
with Apache License 2.0
from apache

public static CertificateKeyPair generateCertificate() {
    KeyPairGenerator kpg = null;
    try {
        kpg = KeyPairGenerator.getInstance("RSA");
    } catch (NoSuchAlgorithmException e) {
        LOGGER.error("Security Algorithim is unsupported for certificate");
    }
    kpg.initialize(2048);
    KeyPair caKeys = kpg.generateKeyPair();
    KeyPair userKeys = kpg.generateKeyPair();
    X500NameBuilder nameBuilder = new X500NameBuilder();
    nameBuilder.addRDN(BCStyle.CN, "Apache PLC4X Driver Client");
    nameBuilder.addRDN(BCStyle.O, "Apache Software Foundation");
    nameBuilder.addRDN(BCStyle.OU, "dev");
    nameBuilder.addRDN(BCStyle.L, "");
    nameBuilder.addRDN(BCStyle.ST, "DE");
    nameBuilder.addRDN(BCStyle.C, "US");
    BigInteger serial = new BigInteger(RandomUtils.nextBytes(40));
    final Calendar calender = Calendar.getInstance();
    calender.add(Calendar.DATE, -1);
    Date startDate = calender.getTime();
    calender.add(Calendar.DATE, 365 * 25);
    Date expiryDate = calender.getTime();
    KeyPairGenerator generator = null;
    try {
        generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(2048, new SecureRandom());
        KeyPair keyPair = generator.generateKeyPair();
        SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(nameBuilder.build(), serial, startDate, expiryDate, Locale.ENGLISH, nameBuilder.build(), subjectPublicKeyInfo);
        GeneralName[] gnArray = new GeneralName[] { new GeneralName(GeneralName.dNSName, InetAddress.getLocalHost().getHostName()), new GeneralName(GeneralName.uniformResourceIdentifier, APPURI) };
        GeneralNames subjectAltNames = GeneralNames.getInstance(new DERSequence(gnArray));
        certificateBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
        ContentSigner sigGen = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(keyPair.getPrivate());
        X509CertificateHolder certificateHolder = certificateBuilder.build(sigGen);
        JcaX509CertificateConverter certificateConvertor = new JcaX509CertificateConverter();
        certificateConvertor.setProvider(new BouncyCastleProvider());
        CertificateKeyPair ckp = new CertificateKeyPair(keyPair, certificateConvertor.getCertificate(certificateHolder));
        return ckp;
    } catch (Exception e) {
        LOGGER.error("Security Algorithim is unsupported for certificate");
        return null;
    }
}

19 Source : TestSCMCertStore.java
with Apache License 2.0
from apache

@Test
public void testRevokeCertificatesForFutureTime() throws Exception {
    BigInteger serialID = x509Certificate.getSerialNumber();
    scmCertStore.storeValidCertificate(serialID, x509Certificate);
    Date now = new Date();
    // Set revocation time in the future
    Date revocationTime = new Date(now.getTime() + 500);
    X509CertificateHolder caCertificateHolder = new X509CertificateHolder(generateX509Cert().getEncoded());
    List<BigInteger> certs = new ArrayList<>();
    certs.add(x509Certificate.getSerialNumber());
    Optional<Long> sequenceId = scmCertStore.revokeCertificates(certs, caCertificateHolder, CRLReason.lookup(CRLReason.keyCompromise), revocationTime, crlApprover);
    replacedertTrue(sequenceId.isPresent());
    replacedertEquals(INITIAL_SEQUENCE_ID + 1L, (long) sequenceId.get());
    replacedertNotNull(scmCertStore.getCertificateByID(serialID, CertificateStore.CertType.VALID_CERTS));
    replacedertNull(scmCertStore.getCertificateByID(serialID, CertificateStore.CertType.REVOKED_CERTS));
}

19 Source : TestCRLCodec.java
with Apache License 2.0
from apache

private X509CertificateHolder readTempCert() throws IOException, CertificateException {
    CertificateCodec codec = new CertificateCodec(securityConfig, COMPONENT);
    X509CertificateHolder x509CertHolder = codec.readCertificate(basePath.toPath(), TMP_CERT_FILE_NAME);
    replacedertNotNull(x509CertHolder);
    return x509CertHolder;
}

19 Source : TestDefaultCAServer.java
with Apache License 2.0
from apache

@Test
public void testInit() throws SCMSecurityException, CertificateException, IOException {
    SecurityConfig securityConfig = new SecurityConfig(conf);
    CertificateServer testCA = new DefaultCAServer("testCA", RandomStringUtils.randomAlphabetic(4), RandomStringUtils.randomAlphabetic(4), caStore);
    testCA.init(securityConfig, CertificateServer.CAType.SELF_SIGNED_CA);
    X509CertificateHolder first = testCA.getCACertificate();
    replacedertNotNull(first);
    // Init is idempotent.
    testCA.init(securityConfig, CertificateServer.CAType.SELF_SIGNED_CA);
    X509CertificateHolder second = testCA.getCACertificate();
    replacedertEquals(first, second);
    // we only support Self Signed CA for now.
    try {
        testCA.init(securityConfig, CertificateServer.CAType.INTERMEDIARY_CA);
        fail("code should not reach here, exception should have been thrown.");
    } catch (IllegalStateException e) {
        // This is a run time exception, hence it is not caught by the junit
        // expected Exception.
        replacedertTrue(e.toString().contains("Not implemented"));
    }
}

19 Source : DefaultApprover.java
with Apache License 2.0
from apache

/**
 * Sign function signs a Certificate.
 * @param config - Security Config.
 * @param caPrivate - CAs private Key.
 * @param caCertificate - CA Certificate.
 * @param validFrom - Begin Da te
 * @param validTill - End Date
 * @param certificationRequest - Certification Request.
 * @param scmId - SCM id.
 * @param clusterId - Cluster id.
 * @return Signed Certificate.
 * @throws IOException - On Error
 * @throws OperatorCreationException - on Error.
 */
@SuppressWarnings("ParameterNumber")
@Override
public X509CertificateHolder sign(SecurityConfig config, PrivateKey caPrivate, X509CertificateHolder caCertificate, Date validFrom, Date validTill, PKCS10CertificationRequest certificationRequest, String scmId, String clusterId) throws IOException, OperatorCreationException {
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(config.getSignatureAlgo());
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter asymmetricKP = PrivateKeyFactory.createKey(caPrivate.getEncoded());
    SubjectPublicKeyInfo keyInfo = certificationRequest.getSubjectPublicKeyInfo();
    // Get scmId and cluster Id from subject name.
    X500Name x500Name = certificationRequest.getSubject();
    String csrScmId = x500Name.getRDNs(BCStyle.OU)[0].getFirst().getValue().toASN1Primitive().toString();
    String csrClusterId = x500Name.getRDNs(BCStyle.O)[0].getFirst().getValue().toASN1Primitive().toString();
    if (!scmId.equals(csrScmId) || !clusterId.equals(csrClusterId)) {
        if (csrScmId.equalsIgnoreCase("null") && csrClusterId.equalsIgnoreCase("null")) {
            // Special case to handle DN certificate generation as DN might not know
            // scmId and clusterId before registration. In secure mode registration
            // will succeed only after datanode has a valid certificate.
            String cn = x500Name.getRDNs(BCStyle.CN)[0].getFirst().getValue().toASN1Primitive().toString();
            x500Name = SecurityUtil.getDistinguishedName(cn, scmId, clusterId);
        } else {
            // Throw exception if scmId and clusterId doesn't match.
            throw new SCMSecurityException("ScmId and ClusterId in CSR subject" + " are incorrect.");
        }
    }
    RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(keyInfo);
    if (rsa.getModulus().bitLength() < config.getSize()) {
        throw new SCMSecurityException("Key size is too small in certificate " + "signing request");
    }
    X509v3CertificateBuilder certificateGenerator = new X509v3CertificateBuilder(caCertificate.getSubject(), // Serial is not sequential but it is monotonically increasing.
    BigInteger.valueOf(Time.monotonicNowNanos()), validFrom, validTill, x500Name, keyInfo);
    Extensions exts = SecurityUtil.getPkcs9Extensions(certificationRequest);
    for (ASN1ObjectIdentifier extId : getProfile().getSupportedExtensions()) {
        Extension ext = exts.getExtension(extId);
        if (ext != null) {
            certificateGenerator.addExtension(ext);
        }
    }
    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(asymmetricKP);
    return certificateGenerator.build(sigGen);
}

See More Examples