List of usage examples for java.security PublicKey getAlgorithm
public String getAlgorithm();
From source file:org.apache.ws.security.saml.SAMLIssuerImpl.java
/** * Creates a new <code>SAMLAssertion</code>. * <p/>/*from w ww . j a v a 2s . co m*/ * <p/> * A complete <code>SAMLAssertion</code> is constructed. * * @return SAMLAssertion */ public SAMLAssertion newAssertion() { // throws Exception { log.debug("Begin add SAMLAssertion token..."); /* * if (senderVouches == false && userCrypto == null) { throw * exception("need user crypto data to insert key") } */ // Issuer must enable crypto functions to get the issuer's certificate String issuer = properties.getProperty("org.apache.ws.security.saml.issuer"); String name = properties.getProperty("org.apache.ws.security.saml.subjectNameId.name"); String qualifier = properties.getProperty("org.apache.ws.security.saml.subjectNameId.qualifier"); try { SAMLNameIdentifier nameId = new SAMLNameIdentifier(name, qualifier, ""); String subjectIP = null; String authMethod = null; if ("password".equals(properties.getProperty("org.apache.ws.security.saml.authenticationMethod"))) { authMethod = SAMLAuthenticationStatement.AuthenticationMethod_Password; } Date authInstant = new Date(); Collection bindings = null; SAMLSubject subject = new SAMLSubject(nameId, Arrays.asList(confirmationMethods), null, null); SAMLStatement[] statements = { new SAMLAuthenticationStatement(subject, authMethod, authInstant, subjectIP, null, bindings) }; sa = new SAMLAssertion(issuer, null, null, null, null, Arrays.asList(statements)); if (!senderVouches) { KeyInfo ki = new KeyInfo(instanceDoc); try { X509Certificate[] certs = userCrypto.getCertificates(username); if (sendKeyValue) { PublicKey key = certs[0].getPublicKey(); String pubKeyAlgo = key.getAlgorithm(); if ("DSA".equalsIgnoreCase(pubKeyAlgo)) { DSAKeyValue dsaKeyValue = new DSAKeyValue(instanceDoc, key); ki.add(dsaKeyValue); } else if ("RSA".equalsIgnoreCase(pubKeyAlgo)) { RSAKeyValue rsaKeyValue = new RSAKeyValue(instanceDoc, key); ki.add(rsaKeyValue); } } else { X509Data certElem = new X509Data(instanceDoc); certElem.addCertificate(certs[0]); ki.add(certElem); } } catch (WSSecurityException ex) { if (log.isDebugEnabled()) { log.debug(ex.getMessage(), ex); } return null; } catch (XMLSecurityException ex) { if (log.isDebugEnabled()) { log.debug(ex.getMessage(), ex); } return null; } Element keyInfoElement = ki.getElement(); keyInfoElement.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS); subject.setKeyInfo(ki); // prepare to sign the SAML token try { X509Certificate[] issuerCerts = issuerCrypto.getCertificates(issuerKeyName); String sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_RSA; String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm(); log.debug("automatic sig algo detection: " + pubKeyAlgo); if (pubKeyAlgo.equalsIgnoreCase("DSA")) { sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_DSA; } java.security.Key issuerPK = issuerCrypto.getPrivateKey(issuerKeyName, issuerKeyPassword); sa.sign(sigAlgo, issuerPK, Arrays.asList(issuerCerts)); } catch (WSSecurityException ex) { if (log.isDebugEnabled()) { log.debug(ex.getMessage(), ex); } return null; } catch (Exception ex) { if (log.isDebugEnabled()) { log.debug(ex.getMessage(), ex); } return null; } } } catch (SAMLException ex) { if (log.isDebugEnabled()) { log.debug(ex.getMessage(), ex); } throw new RuntimeException(ex.toString(), ex); } return sa; }
From source file:org.apache.ws.security.saml.WSSecSignatureSAML.java
/** * Initialize a WSSec SAML Signature./*from ww w. ja v a 2s. c o m*/ * * The method sets up and initializes a WSSec SAML Signature structure after * the relevant information was set. After setup of the references to * elements to sign may be added. After all references are added they can be * signed. * * This method does not add the Signature element to the security header. * See <code>prependSignatureElementToHeader()</code> method. * * @param doc * The SOAP envelope as <code>Document</code> * @param uCrypto * The user's Crypto instance * @param assertion * the complete SAML assertion * @param iCrypto * An instance of the Crypto API to handle keystore SAML token * issuer and to generate certificates * @param iKeyName * Private key to use in case of "sender-Vouches" * @param iKeyPW * Password for issuer private key * @param secHeader * The Security header * @throws WSSecurityException */ public void prepare(Document doc, Crypto uCrypto, SAMLAssertion assertion, Crypto iCrypto, String iKeyName, String iKeyPW, WSSecHeader secHeader) throws WSSecurityException { if (doDebug) { log.debug("Beginning ST signing..."); } userCrypto = uCrypto; issuerCrypto = iCrypto; document = doc; issuerKeyName = iKeyName; issuerKeyPW = iKeyPW; // // Get some information about the SAML token content. This controls how // to deal with the whole stuff. First get the Authentication statement // (includes Subject), then get the _first_ confirmation method only // thats if "senderVouches" is true. // SAMLSubjectStatement samlSubjS = null; Iterator it = assertion.getStatements(); while (it.hasNext()) { SAMLObject so = (SAMLObject) it.next(); if (so instanceof SAMLSubjectStatement) { samlSubjS = (SAMLSubjectStatement) so; break; } } SAMLSubject samlSubj = null; if (samlSubjS != null) { samlSubj = samlSubjS.getSubject(); } if (samlSubj == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLToken", new Object[] { "for Signature" }); } String confirmMethod = null; it = samlSubj.getConfirmationMethods(); if (it.hasNext()) { confirmMethod = (String) it.next(); } if (SAMLSubject.CONF_SENDER_VOUCHES.equals(confirmMethod)) { senderVouches = true; } // // Gather some info about the document to process and store it for // retrieval // wsDocInfo = new WSDocInfo(doc); X509Certificate[] certs = null; PublicKey publicKey = null; if (senderVouches) { certs = issuerCrypto.getCertificates(issuerKeyName); wsDocInfo.setCrypto(issuerCrypto); } // // in case of key holder: - get the user's certificate that _must_ be // included in the SAML token. To ensure the cert integrity the SAML // token must be signed (by the issuer). Just check if its signed, but // don't verify this SAML token's signature here (maybe later). // else { if (userCrypto == null || !assertion.isSigned()) { throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLsecurity", new Object[] { "for SAML Signature (Key Holder)" }); } Element e = samlSubj.getKeyInfo(); try { KeyInfo ki = new KeyInfo(e, null); if (ki.containsX509Data()) { X509Data data = ki.itemX509Data(0); if (data != null && data.containsCertificate()) { XMLX509Certificate certElem = data.itemCertificate(0); if (certElem != null) { X509Certificate cert = certElem.getX509Certificate(); certs = new X509Certificate[1]; certs[0] = cert; } } else if (data != null && data.containsIssuerSerial()) { XMLX509IssuerSerial issuerSerial = data.itemIssuerSerial(0); String alias = userCrypto.getAliasForX509Cert(issuerSerial.getIssuerName(), issuerSerial.getSerialNumber()); certs = userCrypto.getCertificates(alias); } } else if (ki.containsKeyValue()) { publicKey = ki.getPublicKey(); } // TODO: get alias name for cert, check against username set by // caller } catch (XMLSecurityException e3) { throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLsecurity", new Object[] { "cannot get certificate (key holder)" }, e3); } wsDocInfo.setCrypto(userCrypto); } if ((certs == null || certs.length == 0 || certs[0] == null) && publicKey == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "noCertsFound", new Object[] { "SAML signature" }); } if (sigAlgo == null) { PublicKey key = null; if (certs != null && certs[0] != null) { key = certs[0].getPublicKey(); } else if (publicKey != null) { key = publicKey; } String pubKeyAlgo = key.getAlgorithm(); log.debug("automatic sig algo detection: " + pubKeyAlgo); if (pubKeyAlgo.equalsIgnoreCase("DSA")) { sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_DSA; } else if (pubKeyAlgo.equalsIgnoreCase("RSA")) { sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_RSA; } else { throw new WSSecurityException(WSSecurityException.FAILURE, "unknownSignatureAlgorithm", new Object[] { pubKeyAlgo }); } } sig = null; if (canonAlgo.equals(WSConstants.C14N_EXCL_OMIT_COMMENTS)) { Element canonElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_CANONICALIZATIONMETHOD); canonElem.setAttributeNS(null, Constants._ATT_ALGORITHM, canonAlgo); if (wssConfig.isWsiBSPCompliant()) { Set prefixes = getInclusivePrefixes(secHeader.getSecurityHeader(), false); InclusiveNamespaces inclusiveNamespaces = new InclusiveNamespaces(doc, prefixes); canonElem.appendChild(inclusiveNamespaces.getElement()); } try { SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc, sigAlgo); sig = new XMLSignature(doc, null, signatureAlgorithm.getElement(), canonElem); } catch (XMLSecurityException e) { log.error("", e); throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e); } } else { try { sig = new XMLSignature(doc, null, sigAlgo, canonAlgo); } catch (XMLSecurityException e) { log.error("", e); throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e); } } EnvelopeIdResolver resolver = (EnvelopeIdResolver) EnvelopeIdResolver.getInstance(); resolver.setWsDocInfo(wsDocInfo); sig.addResourceResolver(resolver); String sigUri = wssConfig.getIdAllocator().createId("Signature-", sig); sig.setId(sigUri); keyInfo = sig.getKeyInfo(); keyInfoUri = wssConfig.getIdAllocator().createSecureId("KeyId-", keyInfo); keyInfo.setId(keyInfoUri); secRef = new SecurityTokenReference(doc); strUri = wssConfig.getIdAllocator().createSecureId("STRId-", secRef); secRef.setID(strUri); if (certs != null && certs.length != 0) { certUri = wssConfig.getIdAllocator().createSecureId("CertId-", certs[0]); } // // If the sender vouches, then we must sign the SAML token _and_ at // least one part of the message (usually the SOAP body). To do so we // need to - put in a reference to the SAML token. Thus we create a STR // and insert it into the wsse:Security header - set a reference of the // created STR to the signature and use STR Transform during the // signature // Transforms transforms = null; try { if (senderVouches) { secRefSaml = new SecurityTokenReference(doc); String strSamlUri = wssConfig.getIdAllocator().createSecureId("STRSAMLId-", secRefSaml); secRefSaml.setID(strSamlUri); if (WSConstants.X509_KEY_IDENTIFIER == keyIdentifierType) { Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier"); keyId.setAttributeNS(null, "ValueType", WSConstants.WSS_SAML_KI_VALUE_TYPE); keyId.appendChild(doc.createTextNode(assertion.getId())); Element elem = secRefSaml.getElement(); elem.appendChild(keyId); } else { Reference ref = new Reference(doc); ref.setURI("#" + assertion.getId()); ref.setValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); secRefSaml.setReference(ref); } Element ctx = createSTRParameter(doc); transforms = new Transforms(doc); transforms.addTransform(STRTransform.implementedTransformURI, ctx); sig.addDocument("#" + strSamlUri, transforms); wsDocInfo.setSecurityTokenReference(secRefSaml.getElement()); } } catch (TransformationException e1) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e1); } catch (XMLSignatureException e1) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e1); } if (senderVouches) { switch (keyIdentifierType) { case WSConstants.BST_DIRECT_REFERENCE: Reference ref = new Reference(doc); ref.setURI("#" + certUri); bstToken = new X509Security(doc); ((X509Security) bstToken).setX509Certificate(certs[0]); bstToken.setID(certUri); wsDocInfo.setBst(bstToken.getElement()); ref.setValueType(bstToken.getValueType()); secRef.setReference(ref); break; case WSConstants.X509_KEY_IDENTIFIER: secRef.setKeyIdentifier(certs[0]); break; default: throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId"); } } else { switch (keyIdentifierType) { case WSConstants.BST_DIRECT_REFERENCE: Reference ref = new Reference(doc); ref.setURI("#" + assertion.getId()); ref.setValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); secRef.setReference(ref); break; case WSConstants.X509_KEY_IDENTIFIER: Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier"); keyId.setAttributeNS(null, "ValueType", WSConstants.WSS_SAML_KI_VALUE_TYPE); keyId.appendChild(doc.createTextNode(assertion.getId())); Element elem = secRef.getElement(); elem.appendChild(keyId); break; default: throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId"); } } keyInfo.addUnknownElement(secRef.getElement()); wsDocInfo.setSecurityTokenReference(secRef.getElement()); Element keyInfoElement = keyInfo.getElement(); keyInfoElement.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS); try { samlToken = (Element) assertion.toDOM(doc); } catch (SAMLException e2) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noSAMLdoc", null, e2); } wsDocInfo.setAssertion(samlToken); }
From source file:org.apache.xml.security.stax.ext.XMLSecurityUtils.java
public static void createKeyValueTokenStructure(AbstractOutputProcessor abstractOutputProcessor, OutputProcessorChain outputProcessorChain, PublicKey publicKey) throws XMLStreamException, XMLSecurityException { if (publicKey == null) { throw new XMLSecurityException("stax.signature.publicKeyOrCertificateMissing"); }/*ww w . ja va 2 s . c om*/ String algorithm = publicKey.getAlgorithm(); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyValue, true, null); if ("RSA".equals(algorithm)) { RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_RSAKeyValue, false, null); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_Modulus, false, null); abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain, new Base64(76, new byte[] { '\n' }).encodeToString(rsaPublicKey.getModulus().toByteArray())); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_Modulus); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_Exponent, false, null); abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain, new Base64(76, new byte[] { '\n' }) .encodeToString(rsaPublicKey.getPublicExponent().toByteArray())); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_Exponent); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_RSAKeyValue); } else if ("DSA".equals(algorithm)) { DSAPublicKey dsaPublicKey = (DSAPublicKey) publicKey; BigInteger j = dsaPublicKey.getParams().getP().subtract(BigInteger.ONE) .divide(dsaPublicKey.getParams().getQ()); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_DSAKeyValue, false, null); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_P, false, null); abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain, new Base64(76, new byte[] { '\n' }) .encodeToString(dsaPublicKey.getParams().getP().toByteArray())); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_P); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_Q, false, null); abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain, new Base64(76, new byte[] { '\n' }) .encodeToString(dsaPublicKey.getParams().getQ().toByteArray())); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_Q); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_G, false, null); abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain, new Base64(76, new byte[] { '\n' }) .encodeToString(dsaPublicKey.getParams().getG().toByteArray())); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_G); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_Y, false, null); abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain, new Base64(76, new byte[] { '\n' }).encodeToString(dsaPublicKey.getY().toByteArray())); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_Y); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_J, false, null); abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain, new Base64(76, new byte[] { '\n' }).encodeToString(j.toByteArray())); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_J); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_DSAKeyValue); } else if ("EC".equals(algorithm)) { ECPublicKey ecPublicKey = (ECPublicKey) publicKey; List<XMLSecAttribute> attributes = new ArrayList<XMLSecAttribute>(1); attributes.add(abstractOutputProcessor.createAttribute(XMLSecurityConstants.ATT_NULL_URI, "urn:oid:" + ECDSAUtils.getOIDFromPublicKey(ecPublicKey))); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig11_ECKeyValue, true, null); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig11_NamedCurve, false, attributes); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig11_NamedCurve); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig11_PublicKey, false, null); abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain, new Base64(76, new byte[] { '\n' }).encodeToString( ECDSAUtils.encodePoint(ecPublicKey.getW(), ecPublicKey.getParams().getCurve()))); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig11_PublicKey); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig11_ECKeyValue); } abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyValue); }
From source file:org.cesecore.certificates.util.AlgorithmTools.java
/** * Gets the name of matching key algorithm from a public key as defined by * <i>AlgorithmConstants</i>. * @param publickey Public key to find matching key algorithm for. * @return Name of the matching key algorithm or null if no match. * @see AlgorithmConstants#KEYALGORITHM_RSA * @see AlgorithmConstants#KEYALGORITHM_DSA * @see AlgorithmConstants#KEYALGORITHM_ECDSA *///w w w . j a va 2s . c o m public static String getKeyAlgorithm(final PublicKey publickey) { String keyAlg = null; if (publickey instanceof RSAPublicKey) { keyAlg = AlgorithmConstants.KEYALGORITHM_RSA; } else if (publickey instanceof DSAPublicKey) { keyAlg = AlgorithmConstants.KEYALGORITHM_DSA; } else if (publickey instanceof ECPublicKey) { final String algo = publickey.getAlgorithm(); if (StringUtils.equals(algo, AlgorithmConstants.KEYALGORITHM_ECGOST3410)) { keyAlg = AlgorithmConstants.KEYALGORITHM_ECGOST3410; } else if (StringUtils.equals(algo, AlgorithmConstants.KEYALGORITHM_DSTU4145)) { keyAlg = AlgorithmConstants.KEYALGORITHM_DSTU4145; } else { keyAlg = AlgorithmConstants.KEYALGORITHM_ECDSA; } } return keyAlg; }
From source file:org.cesecore.certificates.util.AlgorithmTools.java
/** * Gets a collection of signature algorithm names supported by the given * key./* w ww. j av a 2 s. c om*/ * @param publickey key to find supported algorithms for. * @return Collection of zero or more signature algorithm names * @see AlgorithmConstants */ public static Collection<String> getSignatureAlgorithms(final PublicKey publickey) { final Collection<String> ret; if (publickey instanceof RSAPublicKey) { ret = SIG_ALGS_RSA; } else if (publickey instanceof DSAPublicKey) { ret = SIG_ALGS_DSA; } else if (publickey instanceof ECPublicKey) { final String algo = publickey.getAlgorithm(); if (StringUtils.equals(algo, AlgorithmConstants.KEYALGORITHM_ECGOST3410)) { ret = SIG_ALGS_ECGOST3410; } else if (StringUtils.equals(algo, AlgorithmConstants.KEYALGORITHM_DSTU4145)) { ret = SIG_ALGS_DSTU4145; } else { ret = SIG_ALGS_ECDSA; } } else { ret = Collections.emptyList(); } return ret; }
From source file:org.cesecore.certificates.util.AlgorithmTools.java
/** * Answers if the key can be used together with the given signature algorithm. * @param publicKey public key to use//from www . j a v a 2 s.c om * @param signatureAlgorithm algorithm to test * @return true if signature algorithm can be used with the public key algorithm */ public static boolean isCompatibleSigAlg(final PublicKey publicKey, final String signatureAlgorithm) { String algname = publicKey.getAlgorithm(); if (algname == null) algname = ""; boolean isGost3410 = algname.contains("GOST3410"); boolean isDstu4145 = algname.contains("DSTU4145"); boolean isSpecialECC = isGost3410 || isDstu4145; boolean ret = false; if (StringUtils.contains(signatureAlgorithm, AlgorithmConstants.KEYALGORITHM_RSA)) { if (publicKey instanceof RSAPublicKey) { ret = true; } } else if (StringUtils.contains(signatureAlgorithm, AlgorithmConstants.KEYALGORITHM_ECDSA)) { if (publicKey instanceof ECPublicKey && !isSpecialECC) { ret = true; } } else if (StringUtils.contains(signatureAlgorithm, AlgorithmConstants.KEYALGORITHM_DSA)) { if (publicKey instanceof DSAPublicKey) { ret = true; } } else if (StringUtils.contains(signatureAlgorithm, AlgorithmConstants.KEYALGORITHM_ECGOST3410)) { if (publicKey instanceof ECPublicKey && isGost3410) { ret = true; } } else if (StringUtils.contains(signatureAlgorithm, AlgorithmConstants.KEYALGORITHM_DSTU4145)) { if (publicKey instanceof ECPublicKey && isDstu4145) { ret = true; } } return ret; }
From source file:org.cesecore.keys.token.BaseCryptoToken.java
/** @see #getPublicKey(String) * @param warn if we should log a warning if the key does not exist *//*from w ww. j a va 2s . c o m*/ private PublicKey getPublicKey(final String alias, boolean warn) throws CryptoTokenOfflineException { // Auto activate is done in the call to getKeyStore below (from readPublicKey) try { PublicKey publicK = readPublicKey(alias, warn); if (publicK == null) { final String msg = intres.getLocalizedMessage("token.errornosuchkey", alias); throw new CryptoTokenOfflineException(msg); } final String str = getProperties().getProperty(CryptoToken.EXPLICIT_ECC_PUBLICKEY_PARAMETERS); final boolean explicitEccParameters = Boolean.parseBoolean(str); if (explicitEccParameters && publicK.getAlgorithm().equals("EC")) { if (log.isDebugEnabled()) { log.debug("Using explicit parameter encoding for ECC key."); } publicK = ECKeyUtil.publicToExplicitParameters(publicK, "BC"); } return publicK; } catch (KeyStoreException e) { throw new CryptoTokenOfflineException(e); } catch (NoSuchProviderException e) { throw new CryptoTokenOfflineException(e); } catch (IllegalArgumentException e) { throw new CryptoTokenOfflineException(e); } catch (NoSuchAlgorithmException e) { throw new CryptoTokenOfflineException(e); } }
From source file:org.cesecore.keys.util.KeyTools.java
/** * create the subject key identifier.//w w w. j a va 2 s . com * * @param pubKey * the public key * * @return SubjectKeyIdentifer asn.1 structure */ public static SubjectKeyIdentifier createSubjectKeyId(final PublicKey pubKey) { try { final ASN1Sequence keyASN1Sequence; ASN1InputStream pubKeyAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(pubKey.getEncoded())); try { final Object keyObject = pubKeyAsn1InputStream.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); ASN1InputStream altKeyAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(altKey.getEncoded())); try { keyASN1Sequence = (ASN1Sequence) altKeyAsn1InputStream.readObject(); } finally { altKeyAsn1InputStream.close(); } } X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils(); return x509ExtensionUtils.createSubjectKeyIdentifier(new SubjectPublicKeyInfo(keyASN1Sequence)); } finally { pubKeyAsn1InputStream.close(); } } catch (Exception e) { final RuntimeException e2 = new RuntimeException("error creating key"); // NOPMD e2.initCause(e); throw e2; } }
From source file:org.cesecore.keys.util.KeyTools.java
/** * Testing a key pair to verify that it is possible to first sign and then verify with it. * // w w w . j a va 2s . 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 { // NOPMD:this is not a junit test 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))); } } { Signature signature; try { signature = Signature.getInstance(testSigAlg, "BC"); } catch (NoSuchProviderException e) { throw new IllegalStateException("BouncyCastle was not found as a provider.", e); } 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.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
@Override public void receiveResponse(AuthenticationToken authenticationToken, int caid, ResponseMessage responsemessage, Collection<?> cachain, String nextKeyAlias) throws AuthorizationDeniedException, CertPathValidatorException, EjbcaException, CesecoreException { if (log.isTraceEnabled()) { log.trace(">receiveResponse: " + caid); }/* ww w. j av a 2 s .com*/ if (!accessSession.isAuthorizedNoLogging(authenticationToken, AccessRulesConstants.REGULAR_RENEWCA)) { final String detailsMsg = intres.getLocalizedMessage("caadmin.notauthorizedtocertresp", Integer.valueOf(caid)); auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg); } try { final CA ca = caSession.getCAForEdit(authenticationToken, caid); if (!(responsemessage instanceof X509ResponseMessage)) { String msg = intres.getLocalizedMessage("caadmin.errorcertrespillegalmsg", responsemessage != null ? responsemessage.getClass().getName() : "null"); log.info(msg); throw new EjbcaException(msg); } final Certificate cacert = ((X509ResponseMessage) responsemessage).getCertificate(); // Receiving a certificate for an internal CA will transform it into an externally signed CA if (ca.getSignedBy() != CAInfo.SIGNEDBYEXTERNALCA) { ca.setSignedBy(CAInfo.SIGNEDBYEXTERNALCA); } // Check that CA DN is equal to the certificate response. if (!CertTools.getSubjectDN(cacert).equals(CertTools.stringToBCDNString(ca.getSubjectDN()))) { String msg = intres.getLocalizedMessage("caadmin.errorcertrespwrongdn", CertTools.getSubjectDN(cacert), ca.getSubjectDN()); log.info(msg); throw new EjbcaException(msg); } List<Certificate> tmpchain = new ArrayList<Certificate>(); tmpchain.add(cacert); Collection<Certificate> reqchain = null; if (cachain != null && cachain.size() > 0) { // 1. If we have a chain given as parameter, we will use that. reqchain = CertTools.createCertChain(cachain); log.debug("Using CA certificate chain from parameter of size: " + reqchain.size()); } else { // 2. If no parameter is given we assume that the request chain was stored when the request was created. reqchain = ca.getRequestCertificateChain(); if (reqchain == null) { // 3. Lastly, if that failed we'll check if the certificate chain in it's entirety already exists in the database. reqchain = new ArrayList<Certificate>(); Certificate issuer = certificateStoreSession .findLatestX509CertificateBySubject(CertTools.getIssuerDN(cacert)); if (issuer != null) { reqchain.add(issuer); while (!CertTools.isSelfSigned(issuer)) { issuer = certificateStoreSession .findLatestX509CertificateBySubject(CertTools.getIssuerDN(issuer)); if (issuer != null) { reqchain.add(issuer); } else { String msg = intres.getLocalizedMessage("caadmin.errorincompleterequestchain", caid, ca.getSubjectDN()); log.info(msg); throw new CertPathValidatorException(msg); } } } if (reqchain.size() == 0) { String msg = intres.getLocalizedMessage("caadmin.errornorequestchain", caid, ca.getSubjectDN()); log.info(msg); throw new CertPathValidatorException(msg); } } else { if (log.isDebugEnabled()) { log.debug("Using pre-stored CA certificate chain."); } } } log.debug("Picked up request certificate chain of size: " + reqchain.size()); tmpchain.addAll(reqchain); final List<Certificate> chain = CertTools.createCertChain(tmpchain); log.debug("Storing certificate chain of size: " + chain.size()); // Before importing the certificate we want to make sure that the public key matches the CAs private key PublicKey caCertPublicKey = cacert.getPublicKey(); // If it is a DV certificate signed by a CVCA, enrich the public key for EC parameters from the CVCA's certificate if (StringUtils.equals(cacert.getType(), "CVC")) { if (caCertPublicKey.getAlgorithm().equals("ECDSA")) { CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cacert; try { if (cvccert.getCVCertificate().getCertificateBody().getAuthorizationTemplate() .getAuthorizationField().getAuthRole().isDV()) { log.debug("Enriching DV public key with EC parameters from CVCA"); Certificate cvcacert = (Certificate) reqchain.iterator().next(); caCertPublicKey = KeyTools.getECPublicKeyWithParams(caCertPublicKey, cvcacert.getPublicKey()); } } catch (InvalidKeySpecException e) { log.debug("Strange CVCA certificate that we can't get the key from, continuing anyway...", e); } catch (NoSuchFieldException e) { log.debug("Strange DV certificate with no AutheorizationRole, continuing anyway...", e); } } else { log.debug("Key is not ECDSA, don't try to enrich with EC parameters."); } } else { log.debug("Cert is not CVC, no need to enrich with EC parameters."); } final CAToken catoken = ca.getCAToken(); final CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(catoken.getCryptoTokenId()); boolean activatedNextSignKey = false; if (nextKeyAlias != null) { try { if (log.isDebugEnabled()) { log.debug("SubjectKeyId for CA cert public key: " + new String( Hex.encode(KeyTools.createSubjectKeyId(caCertPublicKey).getKeyIdentifier()))); log.debug("SubjectKeyId for CA next public key: " + new String(Hex.encode(KeyTools .createSubjectKeyId(cryptoToken.getPublicKey(nextKeyAlias)).getKeyIdentifier()))); } KeyTools.testKey(cryptoToken.getPrivateKey(nextKeyAlias), caCertPublicKey, cryptoToken.getSignProviderName()); } catch (InvalidKeyException e) { throw new EjbcaException(ErrorCode.INVALID_KEY, e); } catoken.setNextCertSignKey(nextKeyAlias); catoken.activateNextSignKey(); activatedNextSignKey = true; } else { // Since we don't specified the nextSignKey, we will just try the current or next CA sign key try { KeyTools.testKey( cryptoToken.getPrivateKey( catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)), caCertPublicKey, cryptoToken.getSignProviderName()); } catch (Exception e1) { log.debug( "The received certificate response does not match the CAs private signing key for purpose CAKEYPURPOSE_CERTSIGN, trying CAKEYPURPOSE_CERTSIGN_NEXT..."); if (e1 instanceof InvalidKeyException) { log.trace(e1); } else { // If it's not invalid key, we want to see more of the error log.debug("Error: ", e1); } try { KeyTools.testKey( cryptoToken.getPrivateKey( catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN_NEXT)), caCertPublicKey, cryptoToken.getSignProviderName()); // This was OK, so we must also activate the next signing key when importing this certificate catoken.activateNextSignKey(); activatedNextSignKey = true; } catch (Exception e2) { log.debug( "The received certificate response does not match the CAs private signing key for purpose CAKEYPURPOSE_CERTSIGN_NEXT either, giving up."); if ((e2 instanceof InvalidKeyException) || (e2 instanceof IllegalArgumentException)) { log.trace(e2); } else { // If it's not invalid key or missing authentication code, we want to see more of the error log.debug("Error: ", e2); } throw new EjbcaException(ErrorCode.INVALID_KEY, e2); } } } if (activatedNextSignKey) { // Activated the next signing key(s) so generate audit log final Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", intres.getLocalizedMessage("catoken.activatednextkey", caid)); details.put("certSignKey", catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); details.put("crlSignKey", catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN)); details.put("sequence", catoken.getKeySequence()); auditSession.log(EventTypes.CA_KEYACTIVATE, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(caid), null, null, details); } ca.setCAToken(catoken); ca.setCertificateChain(chain); // Set status to active, so we can sign certificates for the external services below. ca.setStatus(CAConstants.CA_ACTIVE); // activate External CA Services for (int type : ca.getExternalCAServiceTypes()) { try { ca.initExtendedService(cryptoToken, type, ca); final ExtendedCAServiceInfo info = ca.getExtendedCAServiceInfo(type); if (info instanceof BaseSigningCAServiceInfo) { // Publish the extended service certificate, but only for active services if (info.getStatus() == ExtendedCAServiceInfo.STATUS_ACTIVE) { final List<Certificate> extcacertificate = new ArrayList<Certificate>(); extcacertificate.add(((BaseSigningCAServiceInfo) info).getCertificatePath().get(0)); publishCACertificate(authenticationToken, extcacertificate, ca.getCRLPublishers(), ca.getSubjectDN()); } } } catch (Exception fe) { final String detailsMsg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", Integer.valueOf(caid)); auditSession.log(EventTypes.CA_EDITING, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg); throw new EJBException(fe); } } // Set expire time ca.setExpireTime(CertTools.getNotAfter(cacert)); // Save CA caSession.editCA(authenticationToken, ca, true); // Publish CA Certificate publishCACertificate(authenticationToken, chain, ca.getCRLPublishers(), ca.getSubjectDN()); // Create initial CRL publishingCrlSession.forceCRL(authenticationToken, caid); publishingCrlSession.forceDeltaCRL(authenticationToken, caid); // All OK String detailsMsg = intres.getLocalizedMessage("caadmin.certrespreceived", Integer.valueOf(caid)); auditSession.log(EventTypes.CA_EDITING, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg); } catch (CryptoTokenOfflineException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (CADoesntExistsException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically throw e; } catch (CertificateEncodingException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); throw new EjbcaException(e.getMessage()); } catch (CertificateException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); throw new EjbcaException(e.getMessage()); } catch (InvalidAlgorithmParameterException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); throw new EjbcaException(e.getMessage()); } catch (NoSuchAlgorithmException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); throw new EjbcaException(e.getMessage()); } catch (NoSuchProviderException e) { String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid)); log.info(msg); throw new EjbcaException(e.getMessage()); } if (log.isTraceEnabled()) { log.trace("<receiveResponse: " + caid); } }