Example usage for java.security Security addProvider

List of usage examples for java.security Security addProvider

Introduction

In this page you can find the example usage for java.security Security addProvider.

Prototype

public static int addProvider(Provider provider) 

Source Link

Document

Adds a provider to the next position available.

Usage

From source file:test.integ.be.fedict.commons.eid.client.SSLTest.java

@Test
public void testKeyManagerFactory() throws Exception {
    Security.addProvider(new BeIDProvider());
    final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("BeID");
    assertNotNull(keyManagerFactory);/*from w  ww.j  a va2s . c om*/

    final String algo = keyManagerFactory.getAlgorithm();
    LOG.debug("key manager factory algo: " + algo);
    assertEquals("BeID", algo);

    final KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
    assertNotNull(keyManagers);
}

From source file:org.ejbca.ui.cli.HSMKeyTool.java

private static boolean doIt(final String[] orgArgs) throws Exception {
    // Get and remove optional switches
    final List<String> argsList = CliTools.getAsModifyableList(orgArgs);
    final KeyStore.ProtectionParameter protectionParameter;
    final String password = CliTools.getAndRemoveParameter("-password", argsList);
    if (password != null) {
        protectionParameter = new KeyStore.PasswordProtection(password.toCharArray());
    } else {/*  w w  w .j  a  v  a 2 s.  c o m*/
        protectionParameter = null;
    }
    final String[] args = CliTools.getAsArgs(argsList);
    if (args[1].toLowerCase().trim().contains(GENERATE_BATCH_SWITCH)) {
        if (args.length < 4) {
            printCommandString(args, "<name of batch file> [", TOKEN_ID_PARAM, "]");
            printTokenIdDescription();
            sunConfigFileUseDescription();
            System.err.println(
                    "The batch file is a file which specifies alias and key specification for each key to be generated.");
            System.err
                    .println("Each row is starting with a key alias then the key specification is following.");
            System.err.println("The specification of the key is done like this: " + KEY_SPEC_DESC);
            tooFewArguments(args);
        }
        final String storeId;
        final Pkcs11SlotLabelType slotType;
        if (args.length > 4) {
            storeId = trimStoreId(args[4]);
            slotType = getTokenLabelType(args[4]);
        } else {
            storeId = null;
            slotType = Pkcs11SlotLabelType.SUN_FILE;
        }
        final KeyStoreTools store = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null,
                protectionParameter, "batch-" + new Date().getTime());
        generateBatch(args[3], store);
        return true;
    }
    if (args[1].toLowerCase().trim().contains(GENERATE_SWITCH)) {
        if (args.length < 4) {
            printCommandString(args, Character.valueOf('<'), KEY_SPEC_DESC, "> <key entry name> [",
                    TOKEN_ID_PARAM, "]");
            printTokenIdDescription();
            sunConfigFileUseDescription();
            tooFewArguments(args);
        }
        final String keyEntryName = args.length > 4 ? args[4] : "myKey";
        final String storeId;
        final Pkcs11SlotLabelType slotType;
        if (args.length > 5) {
            storeId = trimStoreId(args[5]);
            slotType = getTokenLabelType(args[5]);
        } else {
            storeId = null;
            slotType = Pkcs11SlotLabelType.SUN_FILE;
        }
        System.out.println("Using Slot Reference Type: " + slotType + '.');
        final KeyStoreTools store = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null,
                protectionParameter, "priv-" + keyEntryName);
        store.generateKeyPair(args[3], keyEntryName);
        System.out.println("Created certificate with entry " + keyEntryName + '.');
        return true;
    }
    if (args[1].toLowerCase().trim().equals(DELETE_SWITCH)) {
        if (args.length < 4) {
            printCommandString(args, TOKEN_ID_PARAM, " [<key entry name>]");
            printTokenIdDescription();
            tooFewArguments(args);
        }
        final String alias = args.length > 4 ? args[4] : null;
        System.out.println("Deleting certificate with alias " + alias + '.');
        final String storeId = trimStoreId(args[3]);
        final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);

        KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null, protectionParameter)
                .deleteEntry(alias);
        return true;
    }
    if (args[1].toLowerCase().trim().equals(CERT_REQ)) {
        // First we check if we have a switch for "-explicitecc" for explicit ecc parameters used in ICAO epassports.
        final List<String> argsListLocal = CliTools.getAsModifyableList(args);
        final boolean explicitEccParameters = argsListLocal.remove("-explicitecc");
        final boolean forAllKeys = argsListLocal.remove("-all");
        final String modArgs[] = argsListLocal.toArray(new String[argsListLocal.size()]);
        if (modArgs.length < 4 || (modArgs.length < 5 && !forAllKeys)) {
            printCommandString(args, TOKEN_ID_PARAM, " <key entry name> [<CN>] [-explicitecc]");
            printCommandString(args, TOKEN_ID_PARAM, " [-all] [-explicitecc]");
            printTokenIdDescription();
            tooFewArguments(modArgs);
        }
        final String storeId = trimStoreId(modArgs[3]);
        final Pkcs11SlotLabelType slotType = getTokenLabelType(modArgs[3]);
        final KeyStoreTools container = KeyStoreToolsFactory.getInstance(modArgs[2], storeId, slotType, null,
                protectionParameter);
        final List<String> entries;
        if (forAllKeys) {
            entries = new LinkedList<>();
            final CachingKeyStoreWrapper ks = container.getKeyStore();
            final Enumeration<String> aliases = ks.aliases();
            while (aliases.hasMoreElements()) {
                final String alias = aliases.nextElement();
                if (ks.isKeyEntry(alias)) {
                    entries.add(alias);
                }
            }
        } else {
            entries = Collections.singletonList(modArgs[4]);
        }

        for (String entry : entries) {
            container.generateCertReq(entry, modArgs.length > 5 ? modArgs[5] : null, explicitEccParameters);
        }
        return true;
    }
    if (args[1].toLowerCase().trim().equals(INSTALL_CERT)) {
        if (args.length < 5) {
            printCommandString(args, TOKEN_ID_PARAM,
                    " <certificate chain files in PEM format (one chain per file)>");
            printTokenIdDescription();
            tooFewArguments(args);
        }
        final String storeId = trimStoreId(args[3]);
        final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);
        final KeyStoreTools container = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null,
                protectionParameter);
        boolean failure = false;
        for (int i = 4; i < args.length; i++) {
            try {
                container.installCertificate(args[i]);
            } catch (Exception ex) {
                failure = true;
                log.error("File " + args[i] + " failed.", ex);
            }
        }
        if (failure) {
            throw new Exception("At least one certificate could not be installed. See the log for more info.");
        }
        return true;
    }
    if (args[1].toLowerCase().trim().equals(INSTALL_TRUSTED_ROOT)) {
        if (args.length < 5) {
            printCommandString(args, TOKEN_ID_PARAM, " <trusted root certificate in PEM format>");
            printTokenIdDescription();
            tooFewArguments(args);
        }
        final String storeId = trimStoreId(args[3]);
        final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);
        KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null, protectionParameter)
                .installTrustedRoot(args[4]);
        return true;
    }
    if (args[1].toLowerCase().trim().equals(ENCRYPT_SWITCH)) {
        String symmAlgOid = CMSEnvelopedGenerator.AES128_CBC;
        if (args.length < 5) {
            System.err.println("There are two ways of doing the encryption:");
            printCommandString(args, TOKEN_ID_PARAM,
                    " <input file> <output file> <key alias> [optional symm algorithm oid]");
            printCommandStringNoSharedLib(args,
                    "<input file> <output file> <file with certificate with public key to use> [optional symm algorithm oid]");
            printTokenIdDescription();
            System.err.println(
                    "Optional symmetric encryption algorithm OID can be for example 2.16.840.1.101.3.4.1.42 (AES256_CBC) or 1.2.392.200011.61.1.1.1.4 (CAMELLIA256_CBC). Default is to use AES256_CBC.");
            tooFewArguments(args);
        }
        if (args.length < 7) {
            Security.addProvider(new BouncyCastleProvider());
            if (args.length > 5) {
                // We have a symmAlg as last parameter
                symmAlgOid = args[5];
            }
            System.out.println("Using symmetric encryption algorithm: " + symmAlgOid);
            try (final InputStream certIS = new FileInputStream(args[4]);
                    final InputStream is = new FileInputStream(args[2]);
                    final OutputStream os = new FileOutputStream(args[3])) {
                final X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509")
                        .generateCertificate(new BufferedInputStream(certIS));
                CMS.encrypt(is, os, cert, symmAlgOid);
            }
        } else {
            if (args.length > 7) {
                // We have a symmAlg as last parameter
                symmAlgOid = args[7];
            }
            System.out.println("Using symmstric encryption algorithm: " + symmAlgOid);
            final String storeId = trimStoreId(args[3]);
            final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);
            try (final InputStream is = new FileInputStream(args[4]);
                    final OutputStream os = new FileOutputStream(args[5]);) {
                final Certificate cert = KeyStoreToolsFactory
                        .getInstance(args[2], storeId, slotType, null, protectionParameter).getKeyStore()
                        .getCertificate(args[6]);
                CMS.encrypt(is, os, (X509Certificate) cert, symmAlgOid);
            }
        }
        return true;
    }
    if (args[1].toLowerCase().trim().equals(DECRYPT_SWITCH)) {
        if (args.length < 7) {
            printCommandString(args, TOKEN_ID_PARAM, " <input file> <output file> <key alias>");
            printTokenIdDescription();
            tooFewArguments(args);
        }
        final String storeId = trimStoreId(args[3]);
        final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);
        try (final InputStream is = new FileInputStream(args[4]);
                final OutputStream os = new FileOutputStream(args[5])) {
            final KeyStoreTools keyStore = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null,
                    protectionParameter);
            CMS.decrypt(is, os, (PrivateKey) keyStore.getKeyStore().getKey(args[6], null),
                    keyStore.getProviderName());
        }
        return true;
    }
    if (args[1].toLowerCase().trim().equals(SIGN_SWITCH)) {
        if (args.length < 7) {
            printCommandString(args, TOKEN_ID_PARAM, " <input file> <output file> <key alias>");
            printTokenIdDescription();
            tooFewArguments(args);
        }
        final String storeId = trimStoreId(args[3]);
        final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);
        final KeyStoreTools keyStore = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null,
                protectionParameter);
        final String alias = args[6];
        final PrivateKey key = (PrivateKey) keyStore.getKeyStore().getKey(alias, null);
        final X509Certificate cert = (X509Certificate) keyStore.getKeyStore().getCertificate(alias);
        try (final InputStream is = new FileInputStream(args[4]);
                final OutputStream os = new FileOutputStream(args[5]);) {
            CMS.sign(is, os, key, keyStore.getProviderName(), cert);
        }
        return true;
    }
    if (args[1].toLowerCase().trim().equals(LINKCERT_SWITCH)) {
        if (args.length < 8) {
            printCommandString(args, TOKEN_ID_PARAM,
                    " <old ca-cert> <new ca-cert> <output link-cert> <key alias> [<sig alg override>]");
            printTokenIdDescription();
            System.err.println();
            System.err.println("Creates a link certificate that links the old and new certificate files.");
            System.err.println("You should use this command with the old HSM key. It does not need any");
            System.err.println("access to the new key.");
            System.err.println();
            tooFewArguments(args);
        }
        final String storeId = trimStoreId(args[3]);
        final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);
        final KeyStoreTools ksc = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null,
                protectionParameter);
        final String alias = args[7];
        final String oldCertPath = args[4];
        final String newCertPath = args[5];
        final String outputPath = args[6];
        final String signProviderName = ksc.getProviderName();
        final String sigAlgOverride = (args.length > 8 ? args[8] : "null");

        // Parse certificates
        final byte[] oldCertBytes;
        try (final InputStream is = new FileInputStream(oldCertPath)) {
            oldCertBytes = IOUtils.toByteArray(is);
        }
        final byte[] newCertBytes;
        try (final InputStream is = new FileInputStream(newCertPath)) {
            newCertBytes = IOUtils.toByteArray(is);
        }
        final Certificate oldCert = CertTools.getCertfromByteArray(oldCertBytes,
                BouncyCastleProvider.PROVIDER_NAME, Certificate.class);
        final Certificate newCert = CertTools.getCertfromByteArray(newCertBytes,
                BouncyCastleProvider.PROVIDER_NAME, Certificate.class);
        final boolean isCVCA = (oldCert instanceof CardVerifiableCertificate);
        if (isCVCA != (newCert instanceof CardVerifiableCertificate)) {
            log.error("Error: Old and new certificates are not of the same type (X509 / CVC)");
            return true; // = valid command-line syntax
        }
        System.out.println("Type of certificates: " + (isCVCA ? "CVC" : "X509"));

        // Detect name change
        final String oldDN = CertTools.getSubjectDN(oldCert);
        final String newDN = CertTools.getSubjectDN(newCert);
        System.out.println("Old DN: " + oldDN);
        System.out.println("New DN: " + newDN);
        final boolean nameChange;
        if (!oldDN.equals(newDN)) {
            if (isCVCA) {
                System.out.println("Name change detected.");
            } else {
                System.out.println("Name change detected. Will add Name Change extension.");
            }
            nameChange = true;
        } else {
            System.out.println("No name change detected.");
            nameChange = false;
        }

        final ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // Get new and old key
        final PublicKey newPubKey = newCert.getPublicKey();
        if (newPubKey == null) {
            System.err.println("Error: Failed to extract public key from new certificate");
            return true;
        }
        final Key oldKey = ksc.getKeyStore().getKey(alias, null);
        if (oldKey == null) {
            System.err.println("Error: Could not find the key named " + alias);
            return true;
        }
        final PrivateKey oldPrivKey = (PrivateKey) oldKey;

        if (isCVCA) {
            final CVCertificate oldCertCVC = ((CardVerifiableCertificate) oldCert).getCVCertificate();
            final CVCertificate newCertCVC = ((CardVerifiableCertificate) newCert).getCVCertificate();

            final String linkSigAlg;
            if (sigAlgOverride.equalsIgnoreCase("null")) {
                final OIDField oldKeyTypeOid = oldCertCVC.getCertificateBody().getPublicKey()
                        .getObjectIdentifier();
                linkSigAlg = AlgorithmUtil.getAlgorithmName(oldKeyTypeOid);
            } else {
                System.err.println("Error: Overriding the signature algorithm is not supported for CVC");
                return true;
            }
            System.out.println("Using signature algorithm " + linkSigAlg);

            final HolderReferenceField caHolder = oldCertCVC.getCertificateBody().getHolderReference();
            final CAReferenceField caRef = new CAReferenceField(caHolder.getCountry(), caHolder.getMnemonic(),
                    caHolder.getSequence());
            final HolderReferenceField certHolder = newCertCVC.getCertificateBody().getHolderReference();
            final AuthorizationRole authRole = newCertCVC.getCertificateBody().getAuthorizationTemplate()
                    .getAuthorizationField().getAuthRole();
            final AccessRights rights = newCertCVC.getCertificateBody().getAuthorizationTemplate()
                    .getAuthorizationField().getAccessRights();
            final Date validFrom = new Date(new Date().getTime() - 60L * 15L * 1000L); // back date by 15 minutes to allow for clock skew
            final Date validTo = oldCertCVC.getCertificateBody().getValidTo();

            final CVCertificate linkCert = CertificateGenerator.createCertificate(newPubKey, oldPrivKey,
                    linkSigAlg, caRef, certHolder, authRole, rights, validFrom, validTo, signProviderName);
            try (final DataOutputStream dos = new DataOutputStream(baos)) {
                linkCert.encode(dos);
            }
        } else {
            // X509 CA
            final X509Certificate oldCertX509 = (X509Certificate) oldCert;
            final X509Certificate newCertX509 = (X509Certificate) newCert;

            final String linkSigAlg;
            if (sigAlgOverride.equalsIgnoreCase("null")) {
                // Actually, we should use signature algorithm of new cert if the old key allows that.
                // Instead of doing that we allow the user to manually override the signature algorithm if needed.
                linkSigAlg = oldCertX509.getSigAlgName();
            } else {
                System.err.println("Warning: Signature algorithm manually overridden!");
                linkSigAlg = sigAlgOverride;
            }
            System.out.println("Using signature algorithm " + linkSigAlg);

            final BigInteger serno = SernoGeneratorRandom.instance().getSerno();
            final SubjectPublicKeyInfo pkinfo = SubjectPublicKeyInfo.getInstance(newPubKey.getEncoded());
            final Date validFrom = new Date(new Date().getTime() - 60L * 15L * 1000L); // back date by 15 minutes to allow for clock skew
            final Date validTo = oldCertX509.getNotAfter();

            final X500Name oldDNName = X500Name.getInstance(oldCertX509.getSubjectX500Principal().getEncoded());
            final X500Name newDNName = X500Name.getInstance(newCertX509.getSubjectX500Principal().getEncoded());

            final X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(oldDNName, serno,
                    validFrom, validTo, newDNName, pkinfo);

            // Copy all extensions except AKID
            final ExtensionsGenerator extgen = new ExtensionsGenerator();
            final Set<String> oids = new LinkedHashSet<>();
            final Set<String> criticalOids = newCertX509.getCriticalExtensionOIDs();
            oids.addAll(criticalOids);
            oids.addAll(newCertX509.getNonCriticalExtensionOIDs());
            for (final String extOidStr : oids) {
                final ASN1ObjectIdentifier extoid = new ASN1ObjectIdentifier(extOidStr);
                if (!extoid.equals(Extension.authorityKeyIdentifier)) {
                    final byte[] extbytes = newCertX509.getExtensionValue(extOidStr);
                    final ASN1OctetString str = (ASN1OctetString) ASN1Primitive.fromByteArray(extbytes);
                    extgen.addExtension(extoid, criticalOids.contains(extOidStr),
                            ASN1Primitive.fromByteArray(str.getOctets()));
                }
            }

            if (nameChange) {
                // id-icao-mrtd-security-extensions-nameChange = 2.23.136.1.1.6.1
                extgen.addExtension(ICAOObjectIdentifiers.id_icao_extensions_namechangekeyrollover, false,
                        DERNull.INSTANCE);
            }

            // Some checks
            if (newCertX509.getExtensionValue(Extension.subjectKeyIdentifier.getId()) == null) {
                System.err.println(
                        "Warning: Certificate of new CSCA is missing the Subject Key Identifier extension, which is mandatory.");
            }
            if (newCertX509.getExtensionValue(Extension.authorityKeyIdentifier.getId()) == null) {
                System.err.println(
                        "Warning: Certificate of new CSCA is missing the Authority Key Identifier extension, which is mandatory.");
            }

            // If the new cert has an AKID, then add that extension but with the key id value of the old cert
            final byte[] oldSKIDBytes = oldCertX509.getExtensionValue(Extension.subjectKeyIdentifier.getId());
            if (oldSKIDBytes != null) {
                final ASN1OctetString str = (ASN1OctetString) ASN1Primitive.fromByteArray(oldSKIDBytes);
                final ASN1OctetString innerStr = (ASN1OctetString) ASN1Primitive.fromByteArray(str.getOctets());
                final AuthorityKeyIdentifier akidExt = new AuthorityKeyIdentifier(innerStr.getOctets());
                extgen.addExtension(Extension.authorityKeyIdentifier, false, akidExt);
            } else {
                System.err.println(
                        "Warning: The old certificate doesn't have any SubjectKeyIdentifier. The link certificate will not have any AuthorityKeyIdentifier.");
            }

            // Add extensions to the certificate
            final Extensions exts = extgen.generate();
            for (final ASN1ObjectIdentifier extoid : exts.getExtensionOIDs()) {
                final Extension ext = exts.getExtension(extoid);
                certbuilder.addExtension(extoid, ext.isCritical(), ext.getParsedValue());
            }

            // Sign the certificate
            final ContentSigner signer = new BufferingContentSigner(
                    new JcaContentSignerBuilder(linkSigAlg).setProvider(signProviderName).build(oldPrivKey),
                    20480);
            final X509CertificateHolder certHolder = certbuilder.build(signer);
            baos.write(certHolder.getEncoded());

            // Save to output file
            try (final FileOutputStream fos = new FileOutputStream(outputPath)) {
                baos.writeTo(fos);
            }
        }
        return true;
    }
    if (args[1].toLowerCase().trim().equals(VERIFY_SWITCH)) {
        final CMS.VerifyResult verifyResult;
        if (args.length < 5) {
            System.err.println("There are two ways of doing the encryption:");
            printCommandString(args, TOKEN_ID_PARAM, " <input file> <output file> <key alias>");
            printTokenIdDescription();
            printCommandStringNoSharedLib(args,
                    "<input file> <output file> <file with certificate with public key to use>");
            tooFewArguments(args);
        }
        if (args.length < 7) {
            Security.addProvider(new BouncyCastleProvider());
            try (final InputStream certIS = new FileInputStream(args[4]);
                    final InputStream is = new FileInputStream(args[2]);
                    final OutputStream os = new FileOutputStream(args[3]);) {
                final X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509")
                        .generateCertificate(new BufferedInputStream(certIS));
                verifyResult = CMS.verify(is, os, cert);
            }
        } else {
            final String storeId = trimStoreId(args[3]);
            final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);
            final KeyStoreTools keyStore = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null,
                    protectionParameter);
            final X509Certificate cert = (X509Certificate) keyStore.getKeyStore().getCertificate(args[6]);
            try (final InputStream is = new FileInputStream(args[4]);
                    final OutputStream os = new FileOutputStream(args[5])) {
                verifyResult = CMS.verify(is, os, cert);
            }
        }
        if (verifyResult == null) {
            System.err.println("Not possible to parse signed file.");
            System.exit(4); // Not verifying // NOPMD, it's not a JEE app
            return false;//will never be executes. just to avoid warning.
        }
        System.out.println(
                "The signature of the input " + (verifyResult.isVerifying ? "has been" : "could not be")
                        + " verified. The file was signed on '" + verifyResult.signDate
                        + "'. The public part of the signing key is in a certificate with serial number "
                        + verifyResult.signerId.getSerialNumber() + " issued by '"
                        + verifyResult.signerId.getIssuer() + "'.");
        if (!verifyResult.isVerifying) {
            System.exit(4); // Not verifying // NOPMD, it's not a JEE app
        }
        return true;
    }
    if (args[1].toLowerCase().trim().equals(TEST_SWITCH)) {
        if (args.length < 4) {
            printCommandString(args, TOKEN_ID_PARAM,
                    " [<'m:n' m # of threads, n # of tests>] [<alias for stress test>] [<type of stress test>]");
            printTokenIdDescription();
            System.err.println(
                    "    If a file named \"./testData\" exists then the data that is signed, is read from this file.");
            tooFewArguments(args);
        }
        final String storeId = trimStoreId(args[3]);
        final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);
        final NrOfThreadsAndNrOfTests notanot = new NrOfThreadsAndNrOfTests(args.length > 4 ? args[4] : null);
        KeyStoreContainerTest.test(args[2], storeId, slotType, notanot.threads, notanot.tests,
                args.length > 5 ? args[5].trim() : null, args.length > 6 ? args[6].trim() : null,
                protectionParameter);
        return true;
    }
    if (args[1].toLowerCase().trim().equals(RENAME)) {
        if (args.length < 6) {
            printCommandString(args, TOKEN_ID_PARAM, " <old key alias> <new key alias>");
            printTokenIdDescription();
            tooFewArguments(args);
        }
        final String storeId = trimStoreId(args[3]);
        final Pkcs11SlotLabelType slotType = getTokenLabelType(args[3]);
        final KeyStoreTools keyStore = KeyStoreToolsFactory.getInstance(args[2], storeId, slotType, null,
                protectionParameter);

        keyStore.renameEntry(args[4], args[5]);
        return true;
    }
    if (args[1].toLowerCase().trim().equals(MOVE_SWITCH)) {
        if (args.length < 5) {
            printCommandString(args, "<from PKCS#11 token identifier> <to PKCS#11 token identifier>");
            printTokenIdDescription();
            tooFewArguments(args);
        }
        final KeyStoreTools fromKS = KeyStoreToolsFactory.getInstance(args[2], trimStoreId(args[3]),
                getTokenLabelType(args[3]), null, protectionParameter);
        final KeyStoreTools toKS = KeyStoreToolsFactory.getInstance(args[2], trimStoreId(args[4]),
                getTokenLabelType(args[4]), null, protectionParameter);
        System.out.println("Moving entry with alias '" + args[3] + "' to alias '" + args[4] + '.');
        final Enumeration<String> e = fromKS.getKeyStore().aliases();
        while (e.hasMoreElements()) {
            final String alias = e.nextElement();
            if (fromKS.getKeyStore().isKeyEntry(alias)) {
                final Key key = fromKS.getKeyStore().getKey(alias, null);
                final Certificate chain[] = fromKS.getKeyStore().getCertificateChain(alias);
                toKS.setKeyEntry(alias, key, chain);
            }
            fromKS.getKeyStore().deleteEntry(alias);
        }
        fromKS.getKeyStore().store(null, null);
        toKS.getKeyStore().store(null, null);
        return true;
    }
    return false;
}

From source file:org.gluu.oxtrust.action.UpdateTrustRelationshipAction.java

/**
 * If there is no certificate selected, or certificate is invalid -
 * generates one./*from w ww .  ja va 2  s  . c  o  m*/
 * 
 * @author Oleksiy Tataryn
 * @return certificate for generated SP
 * @throws CertificateEncodingException
 */
private String getCertForGeneratedSP() {
    X509Certificate cert = SSLService.instance().getCertificate(certWrapper.getStream());
    if (cert == null) {
        facesMessages.add(Severity.INFO,
                "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
        try {
            JDKKeyPairGenerator.RSA keyPairGen = new JDKKeyPairGenerator.RSA();
            keyPairGen.initialize(2048);
            KeyPair pair = keyPairGen.generateKeyPair();
            StringWriter keyWriter = new StringWriter();
            PEMWriter pemFormatWriter = new PEMWriter(keyWriter);
            pemFormatWriter.writeObject(pair.getPrivate());
            pemFormatWriter.close();

            String url = trustRelationship.getUrl().replaceFirst(".*//", "");

            X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(
                    new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"),
                    BigInteger.valueOf(new SecureRandom().nextInt()),
                    new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
                    new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)),
                    new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), pair.getPublic());
            cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(v3CertGen.build(
                    new JcaContentSignerBuilder("MD5withRSA").setProvider("BC").build(pair.getPrivate())));
            org.apache.commons.codec.binary.Base64 encoder = new org.apache.commons.codec.binary.Base64(64);
            byte[] derCert = cert.getEncoded();
            String pemCertPre = new String(encoder.encode(derCert));
            log.debug(Shibboleth2ConfService.PUBLIC_CERTIFICATE_START_LINE);
            log.debug(pemCertPre);
            log.debug(Shibboleth2ConfService.PUBLIC_CERTIFICATE_END_LINE);

            saveCert(trustRelationship, pemCertPre);
            saveKey(trustRelationship, keyWriter.toString());

        } catch (Exception e) {

            e.printStackTrace();
        }

        //         String certName = applicationConfiguration.getCertDir() + File.separator + StringHelper.removePunctuation(applicationConfiguration.getOrgInum())
        //               + "-shib.crt";
        //         File certFile = new File(certName);
        //         if (certFile.exists()) {
        //            cert = SSLService.instance().getCertificate(certName);
        //         }
    }
    String certificate = null;
    if (cert != null) {
        try {
            certificate = new String(Base64.encode(cert.getEncoded()));
        } catch (CertificateEncodingException e) {
            certificate = null;
            facesMessages.add(Severity.ERROR,
                    "Failed to encode provided certificate. Please notify Gluu support about this.");
            log.error("Failed to encode certificate to DER", e);
        }
    } else {
        facesMessages.add(Severity.INFO,
                "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
    }

    return certificate;
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testPSS256() throws Exception {
    Security.addProvider(new BeIDProvider());
    Security.addProvider(new BouncyCastleProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);//w w  w.  jav a 2s .com
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    PublicKey authnPublicKey = authnCertificate.getPublicKey();

    Signature signature = Signature.getInstance("SHA256withRSAandMGF1");
    signature.initSign(authnPrivateKey);

    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    signature.initVerify(authnPublicKey);
    signature.update(toBeSigned);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);
}

From source file:edu.nyupoly.cs6903.ag3671.FTPClientExample.java

public static boolean crypto(List<String> args) {
    Security.addProvider(new BouncyCastleProvider());
    keyStorage = new KeyStorage();
    boolean terminate = false;
    if (args.contains("--keygen")) {
        terminate = true;/*from   w  ww .j  ava  2 s  .  c o m*/
        try {
            System.out.println("Keys saved into:\n" + keyStorage.genKeys());
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        try {
            keyChain = keyStorage.readKeys();
            cryptor = new Cryptor(keyChain);
        } catch (Exception e) {
            System.out.println("Cannot read keys. Generate new keys with --keygen option");
            terminate = true;
        }
    }

    return terminate;
}

From source file:test.integ.be.e_contract.mycarenet.ehbox.EHealthBoxClientTest.java

@Test
public void testGetBoxInfoViaString() throws Exception {
    // STS//from  w  w w .  j  av  a 2  s.  c o  m
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String request = "<ehbox:GetBoxInfoRequest xmlns:ehbox=\"urn:be:fgov:ehealth:ehbox:consultation:protocol:v3\"/>";

    // eHealthBox
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, toString(assertion));
    String result = eHealthBoxClient.invoke(request);
    LOG.debug("result: " + result);
}

From source file:org.cesecore.keys.token.BaseCryptoToken.java

private void setProvider(Provider prov) {
    if (prov != null) {
        String pName = prov.getName();
        if (pName.startsWith("LunaJCA")) {
            // Luna Java provider does not contain support for RSA/ECB/PKCS1Padding but this is
            // the same as the alias below on small amounts of data
            prov.put("Alg.Alias.Cipher.RSA/NONE/NoPadding", "RSA//NoPadding");
            prov.put("Alg.Alias.Cipher.1.2.840.113549.1.1.1", "RSA//NoPadding");
            prov.put("Alg.Alias.Cipher.RSA/ECB/PKCS1Padding", "RSA//PKCS1v1_5");
            prov.put("Alg.Alias.Cipher.1.2.840.113549.3.7", "DES3/CBC/PKCS5Padding");
        }/*ww w  . j a  va  2s .c o  m*/
        if (Security.getProvider(pName) == null) {
            Security.addProvider(prov);
        }
        if (Security.getProvider(pName) == null) {
            throw new ProviderException("Not possible to install provider: " + pName);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("No provider passed to setProvider()");
        }
    }
}

From source file:test.integ.be.agiv.security.IPSTSTest.java

@Test
public void testSTS_JAXWS_Client() throws Exception {
    ServletTester servletTester = new ServletTester();
    servletTester.addServlet(MyTestServlet.class, "/");

    Security.addProvider(new BouncyCastleProvider());

    KeyPair keyPair = generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);
    X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=localhost", notBefore, notAfter);
    File tmpP12File = File.createTempFile("ssl-", ".p12");
    LOG.debug("p12 file: " + tmpP12File.getAbsolutePath());
    persistKey(tmpP12File, keyPair.getPrivate(), certificate, "secret".toCharArray(), "secret".toCharArray());

    SslSocketConnector sslSocketConnector = new SslSocketConnector();
    sslSocketConnector.setKeystore(tmpP12File.getAbsolutePath());
    sslSocketConnector.setTruststore(tmpP12File.getAbsolutePath());
    sslSocketConnector.setTruststoreType("pkcs12");
    sslSocketConnector.setKeystoreType("pkcs12");
    sslSocketConnector.setPassword("secret");
    sslSocketConnector.setKeyPassword("secret");
    sslSocketConnector.setTrustPassword("secret");
    sslSocketConnector.setMaxIdleTime(30000);
    int sslPort = getFreePort();
    sslSocketConnector.setPort(sslPort);

    servletTester.getContext().getServer().addConnector(sslSocketConnector);
    String sslLocation = "https://localhost:" + sslPort + "/";

    servletTester.start();//from  w ww .j a v a2  s .  c om
    String location = servletTester.createSocketConnector(true);

    SSLContext sslContext = SSLContext.getInstance("TLS");
    TrustManager trustManager = new TestTrustManager(certificate);
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    SSLContext.setDefault(sslContext);

    try {
        LOG.debug("running IP-STS test...");
        IPSTSClient client = new IPSTSClient(sslLocation, AGIVSecurity.BETA_REALM);
        client.getSecurityToken("username", "password");
    } finally {
        servletTester.stop();
    }
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testAutoFindCard() throws Exception {
    Security.addProvider(new BeIDProvider());

    final KeyStore keyStore = KeyStore.getInstance("BeID");
    BeIDKeyStoreParameter beIDKeyStoreParameter = new BeIDKeyStoreParameter();
    beIDKeyStoreParameter.setLocale(new Locale("fr"));
    keyStore.load(beIDKeyStoreParameter);

    final Enumeration<String> aliases = keyStore.aliases();
    assertNotNull(aliases);//w ww.  j av a 2 s  .c  om
    while (aliases.hasMoreElements()) {
        final String alias = aliases.nextElement();
        LOG.debug("alias: " + alias);
    }

    final X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    assertNotNull(authnCertificate);
}

From source file:test.integ.be.e_contract.mycarenet.ehbox.ScenarioTest.java

/**
 * First we clean the eHealthBox. Then we publish to ourself. Next we
 * download this message./*w w w .  ja  v a  2  s  . c om*/
 * 
 * @throws Exception
 */
@Test
public void testScenarioInvokePlainText() throws Exception {
    // STS
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // eHealthBox: remove all messages.
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString);

    GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        eHealthBoxClient.deleteMessage(messageId);
    }

    // eHealthBox: publish
    EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3");

    ObjectFactory objectFactory = new ObjectFactory();
    PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType();
    String publicationId = UUID.randomUUID().toString().substring(1, 13);
    LOG.debug("publication id: " + publicationId);
    publicationMessage.setPublicationId(publicationId);

    DestinationContextType destinationContext = objectFactory.createDestinationContextType();
    publicationMessage.getDestinationContext().add(destinationContext);
    destinationContext.setQuality("NURSE");
    destinationContext.setType("INSS");
    destinationContext.setId(getUserIdentifier(authnCertificate));

    ContentContextType contentContext = objectFactory.createContentContextType();
    publicationMessage.setContentContext(contentContext);

    PublicationContentType publicationContent = objectFactory.createPublicationContentType();
    contentContext.setContent(publicationContent);
    PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType();
    publicationContent.setDocument(publicationDocument);
    publicationDocument.setTitle("test");
    publicationDocument.setMimeType("text/plain");
    publicationDocument.setDownloadFileName("test.txt");
    byte[] data = "hello world".getBytes();
    publicationDocument.setEncryptableTextContent(data);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digest = messageDigest.digest(data);
    publicationDocument.setDigest(Base64.encodeBase64String(digest));

    ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType();
    contentContext.setContentSpecification(contentSpecification);
    contentSpecification.setContentType("DOCUMENT");

    publicationClient.setCredentials(eHealthPrivateKey, assertionString);
    publicationClient.publish(publicationMessage);

    // give eHealthBox some time.
    Thread.sleep(1000 * 5);

    LOG.debug("GET MESSAGES LIST");
    messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        LOG.debug("GET FULL MESSAGE");
        String request = "<ehbox:GetFullMessageRequest xmlns:ehbox=\"urn:be:fgov:ehealth:ehbox:consultation:protocol:v3\">"
                + "<Source>INBOX</Source>" + "<MessageId>" + messageId + "</MessageId>"
                + "</ehbox:GetFullMessageRequest>";
        String response = eHealthBoxClient.invoke(request);
        LOG.debug("RESPONSE: " + response);
        JAXBContext consultationContext = JAXBContext
                .newInstance(be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ObjectFactory.class);
        Unmarshaller consultationUnmarshaller = consultationContext.createUnmarshaller();
        Map<String, DataHandler> messageAttachments = eHealthBoxClient.getMessageAttachments();
        for (Map.Entry<String, DataHandler> messageAttachment : messageAttachments.entrySet()) {
            LOG.debug("message attachment id: " + messageAttachment.getKey());
            LOG.debug("message data handler: " + messageAttachment.getValue());
            DataHandler resultDataHandler = messageAttachment.getValue();
            DataSource resultDataSource = resultDataHandler.getDataSource();
            byte[] attachmentData = IOUtils.toByteArray(resultDataSource.getInputStream());
            LOG.debug("DataHandler.DataSource.getInputStream length: " + attachmentData.length);
        }
        consultationUnmarshaller.setAttachmentUnmarshaller(new SOAPAttachmentUnmarshaller(messageAttachments));
        JAXBElement<GetFullMessageResponseType> jaxbElement = (JAXBElement<GetFullMessageResponseType>) consultationUnmarshaller
                .unmarshal(new StringReader(response));
        GetFullMessageResponseType getFullMessageResponse = jaxbElement.getValue();
        ConsultationMessageType consultationMessage = getFullMessageResponse.getMessage();
        be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ContentContextType consultationContentContext = consultationMessage
                .getContentContext();
        ConsultationContentType consultationContent = consultationContentContext.getContent();
        ConsultationDocumentType consultationDocument = consultationContent.getDocument();
        byte[] encryptableTextContent = consultationDocument.getEncryptableTextContent();
        if (null != encryptableTextContent) {
            LOG.debug("result EncryptableTextContent: " + encryptableTextContent.length);
        } else {
            LOG.debug("no EncryptableTextContent");
        }
        DataHandler resultDataHandler = consultationDocument.getEncryptableBinaryContent();
        if (null != resultDataHandler) {
            LOG.debug("result EncryptableBinaryContent");
            byte[] resultData = IOUtils.toByteArray(resultDataHandler.getInputStream());
            LOG.debug("result data size: " + resultData.length);
        }
        LOG.debug("DELETE MESSAGE");
        eHealthBoxClient.deleteMessage(messageId);
    }
}