Example usage for java.security PublicKey getAlgorithm

List of usage examples for java.security PublicKey getAlgorithm

Introduction

In this page you can find the example usage for java.security PublicKey getAlgorithm.

Prototype

public String getAlgorithm();

Source Link

Document

Returns the standard algorithm name for this key.

Usage

From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

/**
 * Method that import CA token keys from a P12 file. Was originally used when upgrading from old EJBCA versions. Only supports SHA1 and SHA256
 * with RSA or ECDSA and SHA1 with DSA.//  w  w w.j  a  va 2 s  . co  m
 * @throws OperatorCreationException 
 * @throws AuthorizationDeniedException 
 */
private CAToken importKeysToCAToken(AuthenticationToken authenticationToken, String authenticationCode,
        Properties caTokenProperties, PrivateKey privatekey, PublicKey publickey,
        PrivateKey privateEncryptionKey, PublicKey publicEncryptionKey, Certificate[] caSignatureCertChain,
        int caId) throws CryptoTokenAuthenticationFailedException, IllegalCryptoTokenException,
        OperatorCreationException, AuthorizationDeniedException {
    // If we don't give an authentication code, perhaps we have autoactivation enabled
    if (StringUtils.isEmpty(authenticationCode)) {
        String msg = intres.getLocalizedMessage("token.authcodemissing", Integer.valueOf(caId));
        log.info(msg);
        throw new CryptoTokenAuthenticationFailedException(msg);
    }
    if (caTokenProperties == null) {
        caTokenProperties = new Properties();
    }

    try {
        // Currently only RSA keys are supported
        KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
        keystore.load(null, null);

        // The CAs certificate is first in chain
        Certificate cacert = caSignatureCertChain[0];
        // Assume that the same hash algorithm is used for signing that was used to sign this CA cert
        String signatureAlgorithm = AlgorithmTools.getSignatureAlgorithm(cacert);
        String keyAlg = AlgorithmTools.getKeyAlgorithm(publickey);
        if (keyAlg == null) {
            throw new IllegalCryptoTokenException(
                    "Unknown public key type: " + publickey.getAlgorithm() + " (" + publickey.getClass() + ")");
        }

        // import sign keys.
        final Certificate[] certchain = new Certificate[1];
        certchain[0] = CertTools.genSelfCert("CN=dummy", 36500, null, privatekey, publickey, signatureAlgorithm,
                true);

        keystore.setKeyEntry(CAToken.SOFTPRIVATESIGNKEYALIAS, privatekey, null, certchain);

        // generate enc keys.
        // Encryption keys must be RSA still
        final String encryptionAlgorithm = AlgorithmTools.getEncSigAlgFromSigAlg(signatureAlgorithm);
        keyAlg = AlgorithmTools.getKeyAlgorithmFromSigAlg(encryptionAlgorithm);
        final String enckeyspec = "2048";
        KeyPair enckeys = null;
        if (publicEncryptionKey == null || privateEncryptionKey == null) {
            enckeys = KeyTools.genKeys(enckeyspec, keyAlg);
        } else {
            enckeys = new KeyPair(publicEncryptionKey, privateEncryptionKey);
        }
        // generate dummy certificate
        certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, enckeys.getPrivate(),
                enckeys.getPublic(), encryptionAlgorithm, true);
        keystore.setKeyEntry(CAToken.SOFTPRIVATEDECKEYALIAS, enckeys.getPrivate(), null, certchain);

        // Set the token properties
        caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING,
                CAToken.SOFTPRIVATESIGNKEYALIAS);
        caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING,
                CAToken.SOFTPRIVATESIGNKEYALIAS);
        caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING,
                CAToken.SOFTPRIVATEDECKEYALIAS);

        // Write the keystore to byte[] that we can feed to crypto token factory
        final char[] authCode = authenticationCode.toCharArray();
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        keystore.store(baos, authCode);

        // Now we have the PKCS12 keystore, from this we can create the CAToken
        final Properties cryptoTokenProperties = new Properties();
        int cryptoTokenId;
        try {
            cryptoTokenId = createCryptoTokenWithUniqueName(authenticationToken, "ImportedCryptoToken" + caId,
                    SoftCryptoToken.class.getName(), cryptoTokenProperties, baos.toByteArray(), authCode);
        } catch (NoSuchSlotException e1) {
            throw new RuntimeException(
                    "Attempte to define a slot for a soft crypto token. This should not happen.");
        }
        final CAToken catoken = new CAToken(cryptoTokenId, caTokenProperties);
        // If this is a CVC CA we need to find out the sequence
        String sequence = CAToken.DEFAULT_KEYSEQUENCE;
        if (cacert instanceof CardVerifiableCertificate) {
            CardVerifiableCertificate cvccacert = (CardVerifiableCertificate) cacert;
            log.debug("Getting sequence from holderRef in CV certificate.");
            try {
                sequence = cvccacert.getCVCertificate().getCertificateBody().getHolderReference().getSequence();
            } catch (NoSuchFieldException e) {
                log.error("Can not get sequence from holderRef in CV certificate, using default sequence.");
            }
        }
        log.debug("Setting sequence " + sequence);
        catoken.setKeySequence(sequence);
        log.debug("Setting default sequence format " + StringTools.KEY_SEQUENCE_FORMAT_NUMERIC);
        catoken.setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC);
        catoken.setSignatureAlgorithm(signatureAlgorithm);
        catoken.setEncryptionAlgorithm(encryptionAlgorithm);
        return catoken;
    } catch (KeyStoreException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (NoSuchProviderException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (CertificateException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (IOException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (IllegalStateException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new IllegalCryptoTokenException(e);
    } catch (CryptoTokenOfflineException e) {
        throw new IllegalCryptoTokenException(e);
    }
}

From source file:org.ejbca.core.model.ca.catoken.CATokenContainerImpl.java

/**
 * Method that generates the keys that will be used by the CAToken.
 * The method can be used to generate keys for an initial CA token or to renew Certificate signing keys. 
 * If setstatustowaiting is true and you generate new keys, the new keys will be available as SecConst.CAKEYPURPOSE_CERTSIGN.
 * If setstatustowaiting is false and you generate new keys, the new keys will be available as SecConst.CAKEYPURPOSE_CERTSIGN_NEXT.
 * /*from   w  ww . java2s.c  om*/
 * @param authenticationCode the password used to encrypt the keystore, later needed to activate CA Token
 * @param renew flag indicating if the keys are renewed instead of created fresh. Renewing keys does not 
 * create new encryption keys, since this would make it impossible to decrypt old stuff.
 * @param activate flag indicating if the new keys should be activated immediately or or they should be added as "next" signing key. 
 * Using true here makes it possible to generate certificate renewal requests for external CAs still using the old keys until the response is received. 
 */
public void generateKeys(final String authenticationCode, final boolean renew, final boolean activate)
        throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">generateKeys: " + (authenticationCode == null ? "null" : "hidden") + ", renew=" + renew
                + ", activate=" + activate);
    }
    CATokenInfo catokeninfo = getCATokenInfo();

    // First we start by setting a new sequence for our new keys
    String oldSequence = getKeySequence();
    log.debug("Current sequence: " + oldSequence);
    String newSequence = StringTools.incrementKeySequence(getCATokenInfo().getKeySequenceFormat(), oldSequence);
    // We store the sequence permanently in the object last, when we know everything went well

    // If we don't give an authentication code, perhaps we have autoactivation enabled
    char[] authCode = getAuthCodeOrAutoactivationPin(authenticationCode);

    String tokentype = null;

    // Then we can move on to actually generating the keys
    if (catokeninfo instanceof SoftCATokenInfo) {
        // If we have an existing soft keystore verify that the password is correct
        checkSoftKeystorePassword(authenticationCode);

        SoftCATokenInfo info = (SoftCATokenInfo) catokeninfo;

        Properties properties = getProperties();

        PublicKey pubEnc = null;
        PrivateKey privEnc = null;
        PublicKey previousPubSign = null;
        PrivateKey previousPrivSign = null;
        PublicKey oldPreviousPubSign = null;
        PrivateKey oldPreviousPrivSign = null;
        if (!renew) {
            log.debug("We are generating initial keys.");
            // Generate encryption keys.  
            // Encryption keys must be RSA still
            KeyPair enckeys = KeyTools.genKeys(info.getEncKeySpec(), info.getEncKeyAlgorithm());
            pubEnc = enckeys.getPublic();
            privEnc = enckeys.getPrivate();
        } else {
            log.debug("We are renewing keys.");
            // Get the already existing encryption and signature keys
            ICAToken token = getCAToken();
            pubEnc = token.getPublicKey(SecConst.CAKEYPURPOSE_KEYENCRYPT);
            privEnc = token.getPrivateKey(SecConst.CAKEYPURPOSE_KEYENCRYPT);
            previousPubSign = token.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN);
            previousPrivSign = token.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN);
            oldPreviousPubSign = token.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
            oldPreviousPrivSign = token.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
        }
        // As first choice we check if the used have specified which type of key should be generated, this can be different from the currently used key
        // If the user did not specify this, we try to generate a key with the same specification as the currently used key.
        String keyspec = info.getSignKeySpec(); // can be "unknown"
        if (StringUtils.equals(keyspec, AlgorithmTools.KEYSPEC_UNKNOWN)) {
            keyspec = null;
        }
        AlgorithmParameterSpec paramspec = KeyTools.getKeyGenSpec(previousPubSign);
        if (log.isDebugEnabled()) {
            if (keyspec != null) {
                log.debug("Generating new Soft key with specified spec " + keyspec + " with label "
                        + SoftCAToken.PRIVATESIGNKEYALIAS);
            } else {
                int keySize = KeyTools.getKeyLength(previousPubSign);
                String alg = previousPubSign.getAlgorithm();
                log.debug("Generating new Soft " + alg + " key with spec " + paramspec + " (size=" + keySize
                        + ") with label " + SoftCAToken.PRIVATESIGNKEYALIAS);
            }
        }
        // Generate signature keys.
        KeyPair newsignkeys = KeyTools.genKeys(keyspec, paramspec, info.getSignKeyAlgorithm());

        // Create the new keystore and add the new signature keys
        KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
        keystore.load(null, null);

        // PLay with aliases depending on if we activate the new key or not
        String newSignKeyAlias = SoftCAToken.PRIVATESIGNKEYALIAS;
        String previousSignKeyAlias = SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS;
        if (!activate) {
            // If the new keys are not activated we must still use the old key as active signing key (PRIVATESIGNKEYALIAS)
            newSignKeyAlias = SoftCAToken.NEXTPRIVATESIGNKEYALIAS;
            previousSignKeyAlias = SoftCAToken.PRIVATESIGNKEYALIAS;
        }
        log.debug("Setting newsignkeys as " + newSignKeyAlias + " in soft CA token.");
        Certificate[] certchain = new Certificate[1]; // generate dummy certificate
        String sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(newsignkeys.getPublic()).iterator()
                .next();
        certchain[0] = CertTools.genSelfCert("CN=dummy", 36500, null, newsignkeys.getPrivate(),
                newsignkeys.getPublic(), sigAlg, true);
        keystore.setKeyEntry(newSignKeyAlias, newsignkeys.getPrivate(), null, certchain);
        if (!activate) {
            log.debug("Set next sequence: " + newSequence);
            properties.setProperty(ICAToken.NEXT_SEQUENCE_PROPERTY, newSequence);
            log.debug("Set nextCertSignKey: " + newSignKeyAlias);
            properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_NEXT, newSignKeyAlias);
        }

        // If we have an old key (i.e. generating new keys), we will store the old one as "previous"
        if (previousPrivSign != null) {
            log.debug("Setting previousPrivSign as " + previousSignKeyAlias + " in soft CA token.");
            sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(previousPubSign).iterator().next();
            certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, previousPrivSign, previousPubSign,
                    sigAlg, true);
            keystore.setKeyEntry(previousSignKeyAlias, previousPrivSign, null, certchain);
            // Now this keystore should have this previous key
            if (activate) {
                // This key pair is now moved down to previous sign key
                properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS, previousSignKeyAlias);
                // Set previous sequence so we can create link certificates
                log.debug("Set previous sequence : " + oldSequence);
                properties.setProperty(ICAToken.PREVIOUS_SEQUENCE_PROPERTY, oldSequence);
            } else {
                // If we have an old previous key and we are not activating the new key, we will keep this one as "previous"
                // If the new keys are activate the old previous keys are trashed and replaced by the old active signature key
                String prevProp = properties.getProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS); // If we don't have a previous key don't try to add it
                if ((oldPreviousPrivSign != null) && (prevProp != null)) {
                    log.debug("Setting old previousprivatesignkeyalias as "
                            + SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS + " in soft CA token.");
                    sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(oldPreviousPubSign).iterator()
                            .next();
                    certchain[0] = CertTools.genSelfCert("CN=dummy3", 36500, null, oldPreviousPrivSign,
                            oldPreviousPubSign, sigAlg, true);
                    keystore.setKeyEntry(SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS, oldPreviousPrivSign, null,
                            certchain);
                    properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS,
                            SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS);
                } else {
                    log.debug("No previousprivatesignkeyalias exists, not setting any previous key.");
                }
            }
        }

        // Finally install the old encryption/decryption keys as well
        sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(pubEnc).iterator().next();
        certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, privEnc, pubEnc, sigAlg, true);
        keystore.setKeyEntry(SoftCAToken.PRIVATEDECKEYALIAS, privEnc, null, certchain);

        storeSoftKeyStore(authCode, info, properties, keystore);
        tokentype = "Soft"; // for logging
    } else if (catokeninfo instanceof HardCATokenInfo) {
        ICAToken token = getCAToken();
        if (token instanceof PKCS11CAToken) {
            Properties properties = getProperties();
            PublicKey pubK = token.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN);
            String keyLabel = token.getKeyLabel(SecConst.CAKEYPURPOSE_CERTSIGN);
            log.debug("Old key label is: " + keyLabel);
            String crlKeyLabel = token.getKeyLabel(SecConst.CAKEYPURPOSE_CRLSIGN);
            // The key label to use for the new key
            // Remove the old sequence from the end of the key label and replace it with the
            // new label. If no label was present just concatenate the new label
            String newKeyLabel = StringUtils.removeEnd(keyLabel, oldSequence) + newSequence;
            log.debug("New key label is: " + newKeyLabel);

            final KeyStore.PasswordProtection pwp = new KeyStore.PasswordProtection(authCode);

            // As first choice we check if the used have specified which type of key should be generated, this can be different from the currently used key
            // If the user did not specify this, we try to generate a key with the same specification as the currently used key.
            String keyspec = properties.getProperty(ICAToken.KEYSPEC_PROPERTY); // can be null, and that is ok
            AlgorithmParameterSpec paramspec = KeyTools.getKeyGenSpec(pubK);
            if (log.isDebugEnabled()) {
                String sharedLibrary = properties.getProperty(PKCS11CAToken.SHLIB_LABEL_KEY);
                String slot = properties.getProperty(PKCS11CAToken.SLOT_LABEL_KEY);
                String attributesFile = properties.getProperty(PKCS11CAToken.ATTRIB_LABEL_KEY);
                if (keyspec != null) {
                    log.debug("Generating new PKCS#11 key with specified spec " + keyspec + " with label "
                            + newKeyLabel + ", on slot " + slot + ", using sharedLibrary " + sharedLibrary
                            + ", and attributesFile " + attributesFile);
                } else {
                    int keySize = KeyTools.getKeyLength(pubK);
                    String alg = pubK.getAlgorithm();
                    log.debug("Generating new PKCS#11 " + alg + " key with spec " + paramspec + " (size="
                            + keySize + ") with label " + newKeyLabel + ", on slot " + slot
                            + ", using sharedLibrary " + sharedLibrary + ", and attributesFile "
                            + attributesFile);
                }
            }
            KeyStoreContainer cont = KeyStoreContainerFactory
                    .getInstance(KeyStoreContainer.KEYSTORE_TYPE_PKCS11, token.getProvider(), pwp);
            cont.setPassPhraseLoadSave(authCode);
            if (keyspec != null) {
                log.debug("Generating from string keyspec: " + keyspec);
                cont.generate(keyspec, newKeyLabel);
            } else {
                log.debug("Generating from AlgorithmParameterSpec: " + paramspec);
                cont.generate(paramspec, newKeyLabel);
            }
            // Set properties so that we will start using the new key, or not, depending on the activate argument
            KeyStrings kstr = new KeyStrings(properties);
            String certsignkeystr = kstr.getKey(SecConst.CAKEYPURPOSE_CERTSIGN);
            log.debug("CAKEYPURPOSE_CERTSIGN keystring is: " + certsignkeystr);
            String crlsignkeystr = kstr.getKey(SecConst.CAKEYPURPOSE_CRLSIGN);
            log.debug("CAKEYPURPOSE_CRLSIGN keystring is: " + crlsignkeystr);
            if (!activate) {
                // If the new keys are not activated we must still use the old key as active signing key (PRIVATESIGNKEYALIAS)
                log.debug("Set nextCertSignKey: " + newKeyLabel);
                properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_NEXT, newKeyLabel);
                log.debug("Set next sequence: " + newSequence);
                properties.setProperty(ICAToken.NEXT_SEQUENCE_PROPERTY, newSequence);
            } else {
                properties.setProperty(certsignkeystr, newKeyLabel);
                properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS, keyLabel);
                // If the key strings are not equal, i.e. crtSignKey and crlSignKey was used instead of just defaultKey
                // and the keys are the same. Then we need to set both keys to use the new key label
                if (!StringUtils.equals(certsignkeystr, crlsignkeystr)
                        && StringUtils.equals(keyLabel, crlKeyLabel)) {
                    log.debug("Also setting crlsignkeystr to " + newKeyLabel);
                    properties.setProperty(crlsignkeystr, newKeyLabel);
                }
                // Also set the previous sequence
                properties.setProperty(ICAToken.PREVIOUS_SEQUENCE_PROPERTY, oldSequence);
            }
            setProperties(properties);
            tokentype = "PKCS#11"; // for logging
        }
    } else {
        String msg = intres.getLocalizedMessage("catoken.genkeysnotavail");
        log.error(msg);
        return;
    }
    // Store the new sequence permanently. We should not do this earlier, because if an error is thrown generating keys we should not have updated the CA token object
    if (activate) {
        log.debug("Setting new sequence: " + newSequence);
        setKeySequence(newSequence);
    }
    // Finally reset the token so it will be re-read when we want to use it
    this.catoken = null;
    String msg = intres.getLocalizedMessage("catoken.generatedkeys", tokentype);
    log.info(msg);
    if (log.isTraceEnabled()) {
        log.trace("<generateKeys");
    }
}

From source file:org.ejbca.core.model.ca.catoken.CATokenContainerImpl.java

/**
 * Method that import CA token keys from a P12 file. Was originally used when upgrading from 
 * old EJBCA versions. Only supports SHA1 and SHA256 with RSA or ECDSA and SHA1 with DSA.
 */// w ww  .j  ava2 s. c o  m
public void importKeys(String authenticationCode, PrivateKey privatekey, PublicKey publickey,
        PrivateKey privateEncryptionKey, PublicKey publicEncryptionKey, Certificate[] caSignatureCertChain)
        throws Exception {

    // If we don't give an authentication code, perhaps we have autoactivation enabled
    char[] authCode = getAuthCodeOrAutoactivationPin(authenticationCode);

    // Currently only RSA keys are supported
    KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
    keystore.load(null, null);

    // The CAs certificate is first in chain
    Certificate cacert = caSignatureCertChain[0];
    // Assume that the same hash algorithm is used for signing that was used to sign this CA cert
    String signatureAlgorithm = CertTools.getSignatureAlgorithm(cacert);
    String keyAlg = AlgorithmTools.getKeyAlgorithm(publickey);
    if (keyAlg == null) {
        throw new Exception(
                "Unknown public key type: " + publickey.getAlgorithm() + " (" + publickey.getClass() + ")");
    }

    // If this is a CVC CA we need to find out the sequence
    if (cacert instanceof CardVerifiableCertificate) {
        CardVerifiableCertificate cvccacert = (CardVerifiableCertificate) cacert;
        log.debug("Getting sequence from holderRef in CV certificate.");
        String sequence = cvccacert.getCVCertificate().getCertificateBody().getHolderReference().getSequence();
        log.debug("Setting sequence " + sequence);
        setKeySequence(sequence);
        log.debug("Setting default sequence format " + StringTools.KEY_SEQUENCE_FORMAT_NUMERIC);
        setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC);
    } else {
        log.debug("Setting default sequence " + CATokenConstants.DEFAULT_KEYSEQUENCE);
        setKeySequence(CATokenConstants.DEFAULT_KEYSEQUENCE);
        log.debug("Setting default sequence format " + StringTools.KEY_SEQUENCE_FORMAT_NUMERIC);
        setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC);
    }

    // import sign keys.
    String keyspec = AlgorithmTools.getKeySpecification(publickey);
    Certificate[] certchain = new Certificate[1];
    certchain[0] = CertTools.genSelfCert("CN=dummy", 36500, null, privatekey, publickey, signatureAlgorithm,
            true);

    keystore.setKeyEntry(SoftCAToken.PRIVATESIGNKEYALIAS, privatekey, null, certchain);

    // generate enc keys.  
    // Encryption keys must be RSA still
    String encryptionSignatureAlgorithm = AlgorithmTools.getEncSigAlgFromSigAlg(signatureAlgorithm);
    keyAlg = AlgorithmTools.getKeyAlgorithmFromSigAlg(encryptionSignatureAlgorithm);
    keyspec = "2048";
    KeyPair enckeys = null;
    if (publicEncryptionKey == null || privateEncryptionKey == null) {
        enckeys = KeyTools.genKeys(keyspec, keyAlg);
    } else {
        enckeys = new KeyPair(publicEncryptionKey, privateEncryptionKey);
    }
    // generate dummy certificate
    certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, enckeys.getPrivate(), enckeys.getPublic(),
            encryptionSignatureAlgorithm, true);
    keystore.setKeyEntry(SoftCAToken.PRIVATEDECKEYALIAS, enckeys.getPrivate(), null, certchain);

    // Store keystore
    SoftCATokenInfo info = new SoftCATokenInfo();
    info.setEncKeyAlgorithm(keyAlg);
    info.setEncKeySpec(keyspec);
    info.setEncryptionAlgorithm(encryptionSignatureAlgorithm);
    info.setSignKeyAlgorithm(keyAlg);
    info.setSignKeySpec(keyspec);
    info.setSignatureAlgorithm(signatureAlgorithm);
    storeSoftKeyStore(authCode, info, null, keystore);

    // Finally reset the token so it will be re-read when we want to use it
    this.catoken = null;
}

From source file:org.ejbca.ui.cli.ca.CaImportCVCCACommand.java

public void execute(String[] args) throws ErrorAdminCommandException {
    if (args.length < 4) {
        getLogger().info("Description: " + getDescription());
        getLogger().info(/*w w  w .jav a2s.c  o m*/
                "Usage 1: " + getCommand() + " <CA name> <pkcs8 RSA private key file> <certificate file>");
        getLogger().info(" Imports a private key and a self signed CVCA certificate and creates a CVCA.");
        getLogger().info("Usage 2: " + getCommand()
                + " <CA name> <pkcs8 private key file> <certificate file> <DN of form C=country,CN=mnemonic,SERIALNUMBER=sequence> <signatureAlgorithm> <validity days>");
        getLogger().info(
                " Imports a private key and generates a new self signed CVCA certificate with the given DN and creates a CVCA.");
        getLogger().info(
                " Signature algorithm can be SHA1WithRSA, SHA256WithRSA, SHA1WithECDSA, SHA224WithECDSA, SHA256WithECDSA, etc.");
        getLogger().info(
                " SERIALNUMBER will not be a part of the CAs DN, it is only used to set a specified sequence (should be of form 00001). Can be left out, and a random sequence is then generated.");
        return;
    }
    try {
        String caName = args[1];
        String pkFile = args[2];
        String certFile = args[3];

        // Import key and certificate
        CryptoProviderTools.installBCProvider();
        byte[] pkbytes = FileTools.readFiletoBuffer(pkFile);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pkbytes);
        KeyFactory keyfact = KeyFactory.getInstance("RSA", "BC"); // Doesn't matter if we say RSA here, it will fix an EC key as well
        PrivateKey privKey = keyfact.generatePrivate(spec);

        byte[] certbytes = FileTools.readFiletoBuffer(certFile);
        Certificate cert = null;
        try {
            // First check if it was a PEM formatted certificate
            Collection<Certificate> certs = CertTools.getCertsFromPEM(new ByteArrayInputStream(certbytes));
            cert = certs.iterator().next();
        } catch (IOException e) {
            // This was not a PEM certificate, I hope it's binary...
            cert = CertTools.getCertfromByteArray(certbytes);
        }
        PublicKey pubKey = cert.getPublicKey();
        // Verify that the public and private key belongs together
        getLogger().info("Testing keys with algorithm: " + pubKey.getAlgorithm());
        KeyTools.testKey(privKey, pubKey, null);

        Certificate cacert = null;
        if (args.length > 6) {
            // Create a self signed CVCA cert from the DN
            getLogger().info("Generating new self signed certificate.");
            String dn = args[4];
            String sigAlg = args[5];
            Integer valdays = Integer.parseInt(args[6]);

            String country = CertTools.getPartFromDN(dn, "C");
            String mnemonic = CertTools.getPartFromDN(dn, "CN");
            String seq = CertTools.getPartFromDN(dn, "SERIALNUMBER");
            if (StringUtils.isEmpty(seq)) {
                seq = RandomStringUtils.randomNumeric(5);
                getLogger().info("No sequence given, using random 5 number sequence: " + seq);
            }
            HolderReferenceField holderRef = new HolderReferenceField(country, mnemonic, seq);
            CAReferenceField caRef = new CAReferenceField(holderRef.getCountry(), holderRef.getMnemonic(),
                    holderRef.getSequence());
            AuthorizationRoleEnum authRole = AuthorizationRoleEnum.CVCA;
            Date notBefore = new Date();
            Calendar notAfter = Calendar.getInstance();
            notAfter.add(Calendar.DAY_OF_MONTH, valdays);
            CVCertificate cvc = CertificateGenerator.createCertificate(pubKey, privKey, sigAlg, caRef,
                    holderRef, authRole, AccessRightEnum.READ_ACCESS_DG3_AND_DG4, notBefore, notAfter.getTime(),
                    "BC");
            cacert = new CardVerifiableCertificate(cvc);
        } else {
            getLogger().info("Using passed in self signed certificate.");
            cacert = cert;
        }
        try {
            cacert.verify(pubKey);
        } catch (SignatureException e) {
            getLogger().info("Can not verify self signed certificate: " + e.getMessage());
            System.exit(3); // NOPMD
        }

        Certificate[] chain = new Certificate[1];
        chain[0] = cacert;
        ejb.getCAAdminSession().importCAFromKeys(getAdmin(), caName, "foo123", chain, pubKey, privKey, null,
                null);
    } catch (ErrorAdminCommandException e) {
        throw e;
    } catch (Exception e) {
        throw new ErrorAdminCommandException(e);
    }
}

From source file:org.ejbca.util.keystore.KeyTools.java

/**
 * create the subject key identifier.//  w w  w.  j a  v a2  s . c o m
 *
 * @param pubKey the public key
 *
 * @return SubjectKeyIdentifer asn.1 structure
 */
public static SubjectKeyIdentifier createSubjectKeyId(final PublicKey pubKey) {
    try {
        final ASN1Sequence keyASN1Sequence;
        final Object keyObject = new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded()))
                .readObject();
        if (keyObject instanceof ASN1Sequence) {
            keyASN1Sequence = (ASN1Sequence) keyObject;
        } else {
            // PublicKey key that don't encode to a ASN1Sequence. Fix this by creating a BC object instead.
            final PublicKey altKey = (PublicKey) KeyFactory.getInstance(pubKey.getAlgorithm(), "BC")
                    .translateKey(pubKey);
            keyASN1Sequence = (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(altKey.getEncoded()))
                    .readObject();
        }
        return new SubjectKeyIdentifier(new SubjectPublicKeyInfo(keyASN1Sequence));
    } catch (Exception e) {
        final RuntimeException e2 = new RuntimeException("error creating key"); // NOPMD
        e2.initCause(e);
        throw e2;
    }
}

From source file:org.ejbca.util.keystore.KeyTools.java

/** Testing a key pair to verify that it is possible to first sign and then verify with it.
 * /*  www .  jav a 2  s  .co m*/
 * @param priv private key to sign a string with
 * @param pub public key to verify the signature with
 * @param provider A provider used for signing with the private key, or null if "BC" should be used.
 * 
 * @throws InvalidKeyException if the public key can not be used to verify a string signed by the private key, because the key is wrong or the signature operation fails for other reasons such as a NoSuchAlgorithmException or SignatureException.
 * @throws NoSuchProviderException if the provider is not installed.
 */
public static void testKey(final PrivateKey priv, final PublicKey pub, final String provider)
        throws InvalidKeyException, NoSuchProviderException {
    final byte input[] = "Lillan gick pa vagen ut, motte dar en katt...".getBytes();
    final byte signBV[];
    final String testSigAlg;
    {
        final Iterator<String> i = AlgorithmTools.getSignatureAlgorithms(pub).iterator();
        final String tmp = i.hasNext() ? i.next() : null;
        testSigAlg = tmp != null ? tmp : "SHA1WithRSA";
    }
    if (log.isDebugEnabled()) {
        log.debug("Testing keys with algorithm: " + pub.getAlgorithm());
        log.debug("testSigAlg: " + testSigAlg);
        log.debug("provider: " + provider);
        log.trace("privateKey: " + priv);
        log.trace("privateKey class: " + priv.getClass().getName());
        log.trace("publicKey: " + pub);
        log.trace("publicKey class: " + pub.getClass().getName());
    }
    try {
        {
            final Provider prov = Security.getProvider(provider != null ? provider : "BC");
            final Signature signature = Signature.getInstance(testSigAlg, prov);
            signature.initSign(priv);
            signature.update(input);
            signBV = signature.sign();
            if (signBV == null) {
                throw new InvalidKeyException("Result from signing is null.");
            }
            if (log.isDebugEnabled()) {
                log.trace("Created signature of size: " + signBV.length);
                log.trace("Created signature: " + new String(Hex.encode(signBV)));
            }
        }
        {
            final Signature signature = Signature.getInstance(testSigAlg, "BC");
            signature.initVerify(pub);
            signature.update(input);
            if (!signature.verify(signBV)) {
                throw new InvalidKeyException("Not possible to sign and then verify with key pair.");
            }
        }
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidKeyException("Exception testing key: " + e.getMessage(), e);
    } catch (SignatureException e) {
        throw new InvalidKeyException("Exception testing key: " + e.getMessage(), e);
    }
}

From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java

/**
 * Verifies that the supplied private key and signed certificate match by signing/verifying some test data.
 * //w  ww .  j a  va2  s . c  o  m
 * @param privateKey A private key
 * @param cert the certificate
 * @throws ResourceException if the verification fails, or an error is encountered.
 */
protected void verify(PrivateKey privateKey, Certificate cert) throws ResourceException {
    PublicKey publicKey = cert.getPublicKey();
    byte[] data = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 };
    boolean verified;
    try {
        Signature signer = Signature.getInstance(privateKey.getAlgorithm());
        signer.initSign(privateKey);
        signer.update(data);
        byte[] signed = signer.sign();
        Signature verifier = Signature.getInstance(publicKey.getAlgorithm());
        verifier.initVerify(publicKey);
        verifier.update(data);
        verified = verifier.verify(signed);
    } catch (Exception e) {
        throw new InternalServerErrorException("Error verifying private key and signed certificate", e);
    }
    if (!verified) {
        throw new BadRequestException("Private key does not match signed certificate");
    }
}

From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.DocumentFactory.java

public KeySelectorResult select(KeyInfo keyInfo, KeySelector.Purpose purpose, AlgorithmMethod method,
        XMLCryptoContext context) throws KeySelectorException {
    Iterator ki = keyInfo.getContent().iterator();
    while (ki.hasNext()) {
        XMLStructure info = (XMLStructure) ki.next();
        if (!(info instanceof X509Data))
            continue;
        X509Data x509Data = (X509Data) info;
        Iterator xi = x509Data.getContent().iterator();
        while (xi.hasNext()) {
            Object o = xi.next();
            if (!(o instanceof X509Certificate))
                continue;
            final PublicKey key = ((X509Certificate) o).getPublicKey();
            // Make sure the algorithm is compatible
            // with the method.
            if (algEquals(method.getAlgorithm(), key.getAlgorithm())) {
                return new KeySelectorResult() {
                    public Key getKey() {
                        return key;
                    }/*from  w  ww.  j a va2s  .  c o m*/
                };
            }
        }
    }
    Logger.getLogger(this.getClass()).error("No Key found");
    throw new KeySelectorException("No key found!");
}

From source file:org.opensaml.security.crypto.SigningUtil.java

/**
 * Verify the signature value computed over the supplied input against the supplied signature value.
 * // w w  w  .j av a  2 s .c  om
 * It is up to the caller to ensure that the specified algorithm ID is consistent with the type of verification key
 * supplied.
 * 
 * @param verificationKey the key with which to compute and verify the signature
 * @param jcaAlgorithmID the Java JCA algorithm ID to use
 * @param signature the computed signature value received from the signer
 * @param input the input over which the signature is computed and verified
 * @return true if the signature value computed over the input using the supplied key and algorithm ID is identical
 *         to the supplied signature value
 * @throws SecurityException thrown if the signature computation or verification process results in an error
 */
public static boolean verify(@Nonnull final PublicKey verificationKey, @Nonnull final String jcaAlgorithmID,
        @Nonnull final byte[] signature, @Nonnull final byte[] input) throws SecurityException {
    Constraint.isNotNull(verificationKey, "Public key cannot be null");
    Constraint.isNotNull(jcaAlgorithmID, "JCA algorithm ID cannot be null");
    Constraint.isNotNull(signature, "Signature data to verify cannot be null");
    Constraint.isNotNull(input, "Input data to verify cannot be null");

    Logger log = getLogger();
    log.debug("Verifying signature over input using public key of type {} and JCA algorithm ID {}",
            verificationKey.getAlgorithm(), jcaAlgorithmID);

    try {
        Signature sig = Signature.getInstance(jcaAlgorithmID);
        sig.initVerify(verificationKey);
        sig.update(input);
        return sig.verify(signature);
    } catch (GeneralSecurityException e) {
        log.error("Error during signature verification", e);
        throw new SecurityException("Error during signature verification", e);
    }
}

From source file:org.ow2.proactive.authentication.crypto.Credentials.java

/**
 * Creates new encrypted credentials//from ww w . ja  v  a2s. co  m
 * <p>
 * Encrypts the message '<code>credData</code>' using the
 * public key <code>pubKey</code> and <code>cipher</code>
 * and store it in a new Credentials object.
 *
 * @see KeyPairUtil#encrypt(PublicKey, String, byte[])
 * @param cc, the class containing the data to be crypted
 * @param pubKey public key used for encryption
 * @param cipher cipher parameters: combination of transformations
 * @return the Credentials object containing the encrypted data
 * @throws KeyException key generation or encryption failed
 */
public static Credentials createCredentials(final CredData cc, final PublicKey pubKey, final String cipher)
        throws KeyException {
    // serialize clear credentials to byte array
    byte[] clearCred;
    try {
        clearCred = ObjectToByteConverter.ObjectStream.convert(cc);
    } catch (IOException e1) {
        throw new KeyException(e1.getMessage());
    }

    HybridEncryptionUtil.HybridEncryptedData encryptedData = HybridEncryptionUtil.encrypt(pubKey, cipher,
            clearCred);
    byte[] encAes = encryptedData.getEncryptedSymmetricKey();
    byte[] encData = encryptedData.getEncryptedData();

    int size = keySize(pubKey);
    return new Credentials(pubKey.getAlgorithm(), size, cipher, encAes, encData);
}