Example usage for java.security PublicKey toString

List of usage examples for java.security PublicKey toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:com.aqnote.shared.cryptology.cert.util.X509CertFileUtil.java

/**
 * ???//from  w  ww  .  j av  a2s . c om
 * 
 * @param crtPath
 * @return
 * @throws CertificateException
 * @throws IOException
 */
public static String readX509CertificatePublicKey(String crtPath) throws CertificateException, IOException {

    X509Certificate x509Certificate = readX509Certificate(crtPath);

    PublicKey publicKey = x509Certificate.getPublicKey();

    return publicKey.toString().replace(" ", "");

}

From source file:dk.itst.oiosaml.sp.service.util.Utils.java

/**
 * Check if a SAML HTTP Redirect has been signed by the expected certificate
 * /*from w ww  .  j av a  2  s.  c  o m*/
 * @param data
 *            The query parameters in the HTTP Redirect, which has been
 *            signed
 * @param key
 *            The public key of the certificate from the expected sender
 * @param sig
 *            The signature generated by the sender after it has been base64
 *            decoded
 * @return true, if the signature is valid, otherwise false
 */
public static boolean verifySignature(byte[] data, PublicKey key, byte[] sig) {

    if (log.isDebugEnabled())
        log.debug("data...:" + new String(data));
    if (log.isDebugEnabled())
        log.debug("sig....:" + new String(sig));
    if (log.isDebugEnabled())
        log.debug("key....:" + key.toString());

    try {
        Signature signer = Signature.getInstance(OIOSAMLConstants.SHA1_WITH_RSA);
        signer.initVerify(key);
        signer.update(data);
        return signer.verify(sig);
    } catch (InvalidKeyException e) {
        throw new WrappedException(Layer.CLIENT, e);
    } catch (NoSuchAlgorithmException e) {
        throw new WrappedException(Layer.CLIENT, e);
    } catch (SignatureException e) {
        throw new WrappedException(Layer.CLIENT, e);
    }
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * An ECDSA key can be stripped of the curve parameters so it only contains the public point, and this is not enough to use the key for
 * verification. However, if we know the curve name we can fill in the curve parameters and get a usable EC public key
 * /*from  w w w. j  av a 2  s  .c  o  m*/
 * @param pk
 *            PublicKey, org.ejbca.cvc.PublicKeyEC, that might miss parameters, if parameters are there we do not touch the public key just return it unchanged
 * @param pkwithparams
 *            PublicKey, org.ejbca.cvc.PublicKeyEC, that contains all parameters.
 * @return PublicKey with parameters from the named curve
 *
 * @throws InvalidKeySpecException if the key specification in pkwithparams was invalid
 */
public static PublicKey getECPublicKeyWithParams(final PublicKey pk, final PublicKey pkwithparams)
        throws InvalidKeySpecException {
    PublicKey ret = pk;
    if ((pk instanceof PublicKeyEC) && (pkwithparams instanceof PublicKeyEC)) {
        final PublicKeyEC pkec = (PublicKeyEC) pk;
        // The public key of IS and DV certificate do not have any parameters so we have to do some magic to get a complete EC public key
        final ECParameterSpec spec = pkec.getParams();
        if (spec == null) {
            final PublicKeyEC pkecp = (PublicKeyEC) pkwithparams;
            final ECParameterSpec pkspec = pkecp.getParams();
            if (pkspec != null) {
                final org.bouncycastle.jce.spec.ECParameterSpec bcspec = EC5Util.convertSpec(pkspec, false);
                final java.security.spec.ECPoint p = pkec.getW();
                final org.bouncycastle.math.ec.ECPoint ecp = EC5Util.convertPoint(pkspec, p, false);
                final ECPublicKeySpec pubKey = new ECPublicKeySpec(ecp, bcspec);
                KeyFactory keyfact;
                try {
                    keyfact = KeyFactory.getInstance("ECDSA", BouncyCastleProvider.PROVIDER_NAME);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("ECDSA was an unknown algorithm", e);
                } catch (NoSuchProviderException e) {
                    throw new IllegalStateException("BouncyCastle was not found as a provider.", e);
                }
                ret = keyfact.generatePublic(pubKey);
            } else {
                log.info("pkwithparams does not have any params.");
            }
        }
    } else {
        log.info("Either pk or pkwithparams is not a PublicKeyEC: " + pk.toString() + ", "
                + pkwithparams.toString());
    }
    return ret;
}

From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateHandler.java

@Override
/*//from  w  w w  .ja  v a 2  s . c o m
 * Handles the CMP message
 * 
 * Expects the CMP message to be a CrmfRequestMessage. The message is authenticated using 
 * EndEntityCertificateAuthenticationModule in client mode. It used the attached certificate 
 * to find then End Entity which this certificate belongs to and requesting for a new certificate 
 * to be generated. 
 * 
 * If automatic update of the key (same as certificate renewal), the end entity's status is set to 
 * 'NEW' before processing the request. If using the same old keys in the new certificate is not allowed, 
 * a check is made to insure the the key specified in the request is not the same as the key of the attached 
 * certificate.
 * 
 * The KeyUpdateRequet is processed only in client mode.
 */
public ResponseMessage handleMessage(final BaseCmpMessage msg, boolean authenticated) {
    if (LOG.isTraceEnabled()) {
        LOG.trace(">handleMessage");
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("CMP running on RA mode: " + this.cmpConfiguration.getRAMode(this.confAlias));
    }

    ResponseMessage resp = null;
    try {

        CrmfRequestMessage crmfreq = null;
        if (msg instanceof CrmfRequestMessage) {
            crmfreq = (CrmfRequestMessage) msg;
            crmfreq.getMessage();

            EndEntityCertificateAuthenticationModule eecmodule = null;
            X509Certificate oldCert = null;

            // Find the subjectDN to look for
            String subjectDN = null;
            String issuerDN = null;
            if (this.cmpConfiguration.getRAMode(this.confAlias)) {

                // Check that EndEntityCertificate authentication module is set
                if (!cmpConfiguration.isInAuthModule(confAlias,
                        CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE)) {
                    String errmsg = "EndEnityCertificate authentication module is not configured. For a KeyUpdate request to be authentication in RA mode, EndEntityCertificate "
                            + "authentication module has to be set and configured";
                    LOG.info(errmsg);
                    return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                            FailInfo.BAD_REQUEST, errmsg);
                }

                // Check PKIMessage authentication
                String authparameter = cmpConfiguration.getAuthenticationParameter(
                        CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE, confAlias);
                eecmodule = new EndEntityCertificateAuthenticationModule(admin, authparameter, confAlias,
                        cmpConfiguration, authenticated, caSession, certStoreSession, authorizationSession,
                        endEntityProfileSession, endEntityAccessSession, authenticationProviderSession,
                        endEntityManagementSession);
                if (!eecmodule.verifyOrExtract(crmfreq.getPKIMessage(), null)) {
                    LOG.info(eecmodule.getErrorMessage());
                    return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                            FailInfo.BAD_REQUEST, eecmodule.getErrorMessage());
                } else {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("The CMP KeyUpdate request for SubjectDN '" + crmfreq.getSubjectDN()
                                + "' was verified successfully");
                    }
                }
                oldCert = (X509Certificate) eecmodule.getExtraCert();

                CertReqMessages kur = (CertReqMessages) crmfreq.getPKIMessage().getBody().getContent();
                CertReqMsg certmsg;
                try {
                    certmsg = kur.toCertReqMsgArray()[0];
                } catch (Exception e) {
                    LOG.debug(
                            "Could not parse the revocation request. Trying to parse it as novosec generated message.");
                    certmsg = CmpMessageHelper.getNovosecCertReqMsg(kur);
                    LOG.debug("Succeeded in parsing the novosec generated request.");
                }
                X500Name dn = certmsg.getCertReq().getCertTemplate().getSubject();
                if (dn != null) {
                    subjectDN = dn.toString();
                }
                dn = certmsg.getCertReq().getCertTemplate().getIssuer();
                if (dn != null) {
                    issuerDN = dn.toString();
                }
            } else { // client mode

                eecmodule = new EndEntityCertificateAuthenticationModule(admin, null, confAlias,
                        cmpConfiguration, authenticated, caSession, certStoreSession, authorizationSession,
                        endEntityProfileSession, endEntityAccessSession, authenticationProviderSession,
                        endEntityManagementSession);
                if (!eecmodule.verifyOrExtract(crmfreq.getPKIMessage(), null)) {
                    LOG.info(eecmodule.getErrorMessage());
                    return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                            FailInfo.BAD_REQUEST, eecmodule.getErrorMessage());
                }
                oldCert = (X509Certificate) eecmodule.getExtraCert();

                subjectDN = oldCert.getSubjectDN().toString();
                issuerDN = oldCert.getIssuerDN().toString();
            }

            if (subjectDN == null) {
                final String errMsg = "Cannot find a SubjectDN in the request";
                LOG.info(errMsg);
                return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                        FailInfo.BAD_REQUEST, errMsg);
            }

            // Find the end entity that the certificate belongs to                
            if (LOG.isDebugEnabled()) {
                LOG.debug("Looking for an end entity with subjectDN: " + subjectDN);
            }
            EndEntityInformation userdata = null;
            if (issuerDN == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("The CMP KeyUpdateRequest did not specify an issuer");
                }
                List<EndEntityInformation> userdataList = endEntityAccessSession.findUserBySubjectDN(admin,
                        subjectDN);
                if (userdataList.size() > 0) {
                    userdata = userdataList.get(0);
                }
                if (userdataList.size() > 1) {
                    LOG.warn("Multiple end entities with subject DN " + subjectDN
                            + " were found. This may lead to unexpected behavior.");
                }
            } else {
                List<EndEntityInformation> userdataList = endEntityAccessSession
                        .findUserBySubjectAndIssuerDN(admin, subjectDN, issuerDN);
                if (userdataList.size() > 0) {
                    userdata = userdataList.get(0);
                }
                if (userdataList.size() > 1) {
                    LOG.warn("Multiple end entities with subject DN " + subjectDN + " and issuer DN" + issuerDN
                            + " were found. This may lead to unexpected behavior.");
                }
            }

            if (userdata == null) {
                final String errMsg = INTRES.getLocalizedMessage("cmp.infonouserfordn", subjectDN);
                LOG.info(errMsg);
                return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                        FailInfo.BAD_MESSAGE_CHECK, errMsg);
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("Found user '" + userdata.getUsername() + "'");
            }

            // The password that should be used to obtain the new certificate
            String password = StringUtils.isNotEmpty(userdata.getPassword()) ? userdata.getPassword()
                    : eecmodule.getAuthenticationString();

            // Set the appropriate parameters in the end entity
            userdata.setPassword(password);
            endEntityManagementSession.changeUser(admin, userdata, true);
            if (this.cmpConfiguration.getKurAllowAutomaticUpdate(this.confAlias)) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Setting the end entity status to 'NEW'. Username: " + userdata.getUsername());
                }

                endEntityManagementSession.setUserStatus(admin, userdata.getUsername(),
                        EndEntityConstants.STATUS_NEW);
            }

            // Set the appropriate parameters in the request
            crmfreq.setUsername(userdata.getUsername());
            crmfreq.setPassword(password);
            if (crmfreq.getHeader().getProtectionAlg() != null) {
                crmfreq.setPreferredDigestAlg(AlgorithmTools
                        .getDigestFromSigAlg(crmfreq.getHeader().getProtectionAlg().getAlgorithm().getId()));
            }

            // Check the public key, whether it is allowed to use the old keys or not.
            if (!this.cmpConfiguration.getKurAllowSameKey(this.confAlias)) {
                PublicKey certPublicKey = oldCert.getPublicKey();
                PublicKey requestPublicKey = crmfreq.getRequestPublicKey();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Not allowing update with same key, comparing keys.");
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("OldKey: " + certPublicKey.toString());
                        LOG.trace("NewKey: " + requestPublicKey.toString());
                    }
                }
                if (certPublicKey.equals(requestPublicKey)) {
                    final String errMsg = "Invalid key. The public key in the KeyUpdateRequest is the same as the public key in the existing end entity certificate";
                    LOG.info(errMsg);
                    return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                            FailInfo.BAD_MESSAGE_CHECK, errMsg);
                }
            }

            // Process the request
            resp = signSession.createCertificate(admin, crmfreq,
                    org.ejbca.core.protocol.cmp.CmpResponseMessage.class, userdata);

            if (resp == null) {
                final String errMsg = INTRES.getLocalizedMessage("cmp.errornullresp");
                LOG.info(errMsg);
                resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                        FailInfo.BAD_MESSAGE_CHECK, errMsg);
            }
        } else {
            final String errMsg = INTRES.getLocalizedMessage("cmp.errornocmrfreq");
            LOG.info(errMsg);
            resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                    FailInfo.BAD_MESSAGE_CHECK, errMsg);
        }

    } catch (AuthorizationDeniedException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (CADoesntExistsException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (UserDoesntFullfillEndEntityProfile e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (WaitingForApprovalException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (EjbcaException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (FinderException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (CesecoreException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (InvalidKeyException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info("Error while reading the public key of the extraCert attached to the CMP request");
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info("Error while reading the public key of the extraCert attached to the CMP request");
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (NoSuchProviderException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info("Error while reading the public key of the extraCert attached to the CMP request");
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (CertificateExtensionException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("<handleMessage");
    }
    return resp;
}

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

public static PublicKey getECPublicKeyWithParams(final PublicKey pk, final PublicKey pkwithparams)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
    PublicKey ret = pk;/*from   w ww.j a  v  a  2 s. c  o m*/
    if ((pk instanceof PublicKeyEC) && (pkwithparams instanceof PublicKeyEC)) {
        final PublicKeyEC pkec = (PublicKeyEC) pk;
        // The public key of IS and DV certificate do not have any parameters so we have to do some magic to get a complete EC public key
        final ECParameterSpec spec = pkec.getParams();
        if (spec == null) {
            final PublicKeyEC pkecp = (PublicKeyEC) pkwithparams;
            final ECParameterSpec pkspec = pkecp.getParams();
            if (pkspec != null) {
                final org.bouncycastle.jce.spec.ECParameterSpec bcspec = EC5Util.convertSpec(pkspec, false);
                final java.security.spec.ECPoint p = pkec.getW();
                final org.bouncycastle.math.ec.ECPoint ecp = EC5Util.convertPoint(pkspec, p, false);
                final ECPublicKeySpec pubKey = new ECPublicKeySpec(ecp, bcspec);
                final KeyFactory keyfact = KeyFactory.getInstance("ECDSA", "BC");
                ret = keyfact.generatePublic(pubKey);
            } else {
                log.info("pkwithparams does not have any params.");
            }
        }
    } else {
        log.info("Either pk or pkwithparams is not a PublicKeyEC: " + pk.toString() + ", "
                + pkwithparams.toString());
    }
    return ret;
}