List of usage examples for java.security.cert X509Certificate getPublicKey
public abstract PublicKey getPublicKey();
From source file:org.apache.xml.security.signature.XMLSignature.java
/** * Extracts the public key from the certificate and verifies if the signature * is valid by re-digesting all References, comparing those against the * stored DigestValues and then checking to see if the Signatures match on * the SignedInfo.//from ww w. java 2 s . c o m * * @param cert Certificate that contains the public key part of the keypair * that was used to sign. * @return true if the signature is valid, false otherwise * @throws XMLSignatureException */ public boolean checkSignatureValue(X509Certificate cert) throws XMLSignatureException { // see if cert is null if (cert != null) { // check the values with the public key from the cert return this.checkSignatureValue(cert.getPublicKey()); } Object exArgs[] = { "Didn't get a certificate" }; throw new XMLSignatureException("empty", exArgs); }
From source file:org.apache.xml.security.stax.ext.XMLSecurityUtils.java
public static void createKeyValueTokenStructure(AbstractOutputProcessor abstractOutputProcessor, OutputProcessorChain outputProcessorChain, X509Certificate[] x509Certificates) throws XMLStreamException, XMLSecurityException { if (x509Certificates == null || x509Certificates.length == 0) { throw new XMLSecurityException("stax.signature.publicKeyOrCertificateMissing"); }// w w w. j a va2s . co m X509Certificate x509Certificate = x509Certificates[0]; PublicKey publicKey = x509Certificate.getPublicKey(); createKeyValueTokenStructure(abstractOutputProcessor, outputProcessorChain, publicKey); }
From source file:org.apache.xml.security.test.signature.CreateSignatureTest.java
String doSignWithCert() throws Exception { KeyStore ks = KeyStore.getInstance("JKS"); FileInputStream fis = null;// ww w . j a v a 2 s . c o m if (BASEDIR != null && !"".equals(BASEDIR)) { fis = new FileInputStream(BASEDIR + SEP + "data/test.jks"); } else { fis = new FileInputStream("data/test.jks"); } ks.load(fis, "changeit".toCharArray()); PrivateKey privateKey = (PrivateKey) ks.getKey("mullan", "changeit".toCharArray()); org.w3c.dom.Document doc = db.newDocument(); X509Certificate signingCert = (X509Certificate) ks.getCertificate("mullan"); doc.appendChild(doc.createComment(" Comment before ")); Element root = doc.createElementNS("", "RootElement"); doc.appendChild(root); root.appendChild(doc.createTextNode("Some simple text\n")); Element canonElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_CANONICALIZATIONMETHOD); canonElem.setAttributeNS(null, Constants._ATT_ALGORITHM, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc, XMLSignature.ALGO_ID_SIGNATURE_DSA); XMLSignature sig = new XMLSignature(doc, null, signatureAlgorithm.getElement(), canonElem); root.appendChild(sig.getElement()); doc.appendChild(doc.createComment(" Comment after ")); Transforms transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE); transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS); sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1); sig.addKeyInfo(signingCert); sig.sign(privateKey); X509Certificate cert = sig.getKeyInfo().getX509Certificate(); sig.checkSignatureValue(cert.getPublicKey()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); XMLUtils.outputDOMc14nWithComments(doc, bos); return new String(bos.toByteArray()); }
From source file:org.apache.xml.security.test.signature.XmlSecTest.java
private void checkXmlSignatureSoftwareStack(boolean cert) throws Exception { Init.init();/* w ww. j a v a2 s . c o m*/ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document testDocument = documentBuilder.newDocument(); Element rootElement = testDocument.createElementNS("urn:namespace", "tns:document"); rootElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "urn:namespace"); testDocument.appendChild(rootElement); Element childElement = testDocument.createElementNS("urn:childnamespace", "t:child"); childElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:t", "urn:childnamespace"); childElement.appendChild(testDocument.createTextNode("hello world")); rootElement.appendChild(childElement); PrivateKey privateKey = null; PublicKey publicKey = null; X509Certificate signingCert = null; if (cert) { // get key & self-signed certificate from keystore String fs = System.getProperty("file.separator"); FileInputStream fis = new FileInputStream(BASEDIR + fs + "data" + fs + "test.jks"); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(fis, "changeit".toCharArray()); signingCert = (X509Certificate) ks.getCertificate("mullan"); publicKey = signingCert.getPublicKey(); privateKey = (PrivateKey) ks.getKey("mullan", "changeit".toCharArray()); } else { KeyPair keyPair = KeyPairGenerator.getInstance("DSA").generateKeyPair(); publicKey = keyPair.getPublic(); privateKey = keyPair.getPrivate(); } XMLSignature signature = new XMLSignature(testDocument, "", XMLSignature.ALGO_ID_SIGNATURE_DSA, Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS); Element signatureElement = signature.getElement(); rootElement.appendChild(signatureElement); Transforms transforms = new Transforms(testDocument); XPathContainer xpath = new XPathContainer(testDocument); xpath.setXPathNamespaceContext("ds", Constants.SignatureSpecNS); xpath.setXPath("not(ancestor-or-self::ds:Signature)"); transforms.addTransform(Transforms.TRANSFORM_XPATH, xpath.getElementPlusReturns()); transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS); signature.addDocument("", transforms, MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1); if (cert) { signature.addKeyInfo(signingCert); } else { signature.addKeyInfo(publicKey); } Element nsElement = testDocument.createElementNS(null, "nsElement"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS); signature.sign(privateKey); // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer t = tf.newTransformer(); // t.transform(new DOMSource(testDocument), new StreamResult(System.out)); NodeList signatureElems = XPathAPI.selectNodeList(testDocument, "//ds:Signature", nsElement); signatureElement = (Element) signatureElems.item(0); XMLSignature signatureToVerify = new XMLSignature(signatureElement, ""); boolean signResult = signatureToVerify.checkSignatureValue(publicKey); assertTrue(signResult); }
From source file:org.apache.zeppelin.realm.jwt.KnoxJwtRealm.java
public static RSAPublicKey parseRSAPublicKey(String pem) throws IOException, ServletException { final String pemHeader = "-----BEGIN CERTIFICATE-----\n"; final String pemFooter = "\n-----END CERTIFICATE-----"; String fullPem = pemHeader + pem + pemFooter; PublicKey key = null;// w w w . java 2s. c om try { CertificateFactory fact = CertificateFactory.getInstance("X.509"); ByteArrayInputStream is = new ByteArrayInputStream( FileUtils.readFileToString(new File(pem)).getBytes("UTF8")); X509Certificate cer = (X509Certificate) fact.generateCertificate(is); key = cer.getPublicKey(); } catch (CertificateException ce) { String message = null; if (pem.startsWith(pemHeader)) { message = "CertificateException - be sure not to include PEM header " + "and footer in the PEM configuration element."; } else { message = "CertificateException - PEM may be corrupt"; } throw new ServletException(message, ce); } catch (UnsupportedEncodingException uee) { throw new ServletException(uee); } catch (IOException e) { throw new IOException(e); } return (RSAPublicKey) key; }
From source file:org.atricore.idbus.capabilities.sso.support.test.XmlDsigTest.java
/** * Sign a simple DOM document using the configured JSR 105 Provider *//*from ww w.jav a2s .c om*/ @Test public void simpleDocumentSign() throws Exception { //All the parameters for the keystore String keystoreType = "JKS"; String keystoreFile = "src/test/resources/keystore.jks"; String keystorePass = "xmlsecurity"; String privateKeyAlias = "test"; String privateKeyPass = "xmlsecurity"; String certificateAlias = "test"; File signatureFile = new File("target/signature.xml"); KeyStore ks = KeyStore.getInstance(keystoreType); FileInputStream fis = new FileInputStream(keystoreFile); //load the keystore ks.load(fis, keystorePass.toCharArray()); //get the private key for signing. PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray()); X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias); PublicKey publicKey = cert.getPublicKey(); // Create a DOM XMLSignatureFactory that will be used to generate the // enveloped signature String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI"); XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance()); // Create a Reference to the enveloped document (in this case we are // signing the whole document, so a URI of "" signifies that) and // also specify the SHA1 digest algorithm and the ENVELOPED Transform. Reference ref = fac.newReference("#12345", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); // Create the SignedInfo SignedInfo si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); // Instantiate the document to be signed javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); //XML Signature needs to be namespace aware dbf.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.newDocument(); //Build a sample document. It will look something like: //<!-- Comment before --> //<apache:RootElement xmlns:apache="http://www.apache.org/ns/#app1" ID="12345">Some simple text //</apache:RootElement> //<!-- Comment after --> doc.appendChild(doc.createComment(" Comment before ")); Element root = doc.createElementNS("http://www.apache.org/ns/#app1", "apache:RootElement"); root.setAttributeNS(null, "ID", "12345"); root.setAttributeNS(null, "attr1", "test1"); root.setAttributeNS(null, "attr2", "test2"); root.setAttributeNS(org.apache.xml.security.utils.Constants.NamespaceSpecNS, "xmlns:foo", "http://example.org/#foo"); root.setAttributeNS("http://example.org/#foo", "foo:attr1", "foo's test"); root.setAttributeNS(org.apache.xml.security.utils.Constants.NamespaceSpecNS, "xmlns:apache", "http://www.apache.org/ns/#app1"); doc.appendChild(root); root.appendChild(doc.createTextNode("Some simple text\n")); // Create a DOMSignContext and specify the DSA PrivateKey and // location of the resulting XMLSignature's parent element DOMSignContext dsc = new DOMSignContext(privateKey, doc.getDocumentElement()); // Create the XMLSignature (but don't sign it yet) KeyInfoFactory kif = fac.getKeyInfoFactory(); X509Data kv = kif.newX509Data(Collections.singletonList(cert)); // Create a KeyInfo and add the KeyValue to it KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); javax.xml.crypto.dsig.XMLSignature signature = fac.newXMLSignature(si, ki); signature.sign(dsc); // TODO : Verify signature ? // output the resulting document FileOutputStream f = new FileOutputStream(signatureFile); XMLUtils.outputDOMc14nWithComments(doc, f); f.close(); }
From source file:org.atricore.idbus.capabilities.sso.support.test.XmlDsigTest.java
/** * Sign a SAMLR2 Assertion using the configured JSR 105 Provider *//*from w w w . j av a 2 s . co m*/ @Test public void assertionSign() throws Exception { //All the parameters for the keystore String keystoreType = "JKS"; String keystoreFile = "src/test/resources/keystore.jks"; String keystorePass = "xmlsecurity"; String privateKeyAlias = "test"; String privateKeyPass = "xmlsecurity"; String certificateAlias = "test"; File assertionFile = new File("src/test/resources/assertion-001.xml"); File signatureFile = new File("target/assertion-signed-001.xml"); JAXBContext context = JAXBContext.newInstance("oasis.names.tc.saml._2_0.assertion"); Unmarshaller um = context.createUnmarshaller(); JAXBElement jaxbElement = (JAXBElement) um.unmarshal(assertionFile); AssertionType assertion = (AssertionType) jaxbElement.getValue(); // Unmarshall the assertion KeyStore ks = KeyStore.getInstance(keystoreType); FileInputStream fis = new FileInputStream(keystoreFile); //load the keystore ks.load(fis, keystorePass.toCharArray()); //get the private key for signing. PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray()); X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias); PublicKey publicKey = cert.getPublicKey(); // Create a DOM XMLSignatureFactory that will be used to generate the // enveloped signature String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI"); XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance()); // Create a Reference to the enveloped document (in this case we are // signing the whole document, so a URI of "" signifies that) and // also specify the SHA1 digest algorithm and the ENVELOPED Transform. Reference ref = fac.newReference("#" + assertion.getID(), fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); // Create the SignedInfo SignedInfo si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); // Instantiate the document to be signed javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); //XML Signature needs to be namespace aware dbf.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.newDocument(); Marshaller m = context.createMarshaller(); m.marshal(jaxbElement, doc); // Create a DOMSignContext and specify the DSA PrivateKey and // location of the resulting XMLSignature's parent element DOMSignContext dsc = new DOMSignContext(privateKey, doc.getDocumentElement(), doc.getDocumentElement().getFirstChild()); // Create the XMLSignature (but don't sign it yet) KeyInfoFactory kif = fac.getKeyInfoFactory(); X509Data kv = kif.newX509Data(Collections.singletonList(cert)); // Create a KeyInfo and add the KeyValue to it KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); javax.xml.crypto.dsig.XMLSignature signature = fac.newXMLSignature(si, ki); signature.sign(dsc); // output the resulting document FileOutputStream f = new FileOutputStream(signatureFile); XMLUtils.outputDOMc14nWithComments(doc, f); f.close(); }
From source file:org.bibsonomy.webapp.validation.opensocial.BibSonomyOAuthValidator.java
private PublicKey getPublicKeyFromDerCert(byte[] certObject) throws GeneralSecurityException { CertificateFactory fac = CertificateFactory.getInstance("X509"); ByteArrayInputStream in = new ByteArrayInputStream(certObject); X509Certificate cert = (X509Certificate) fac.generateCertificate(in); return cert.getPublicKey(); }
From source file:org.cesecore.certificates.ca.internal.CaCertificateCacheTest.java
@Test public void test01CACertificates() throws Exception { // Prepare the certificate cache with some test certificates Collection<Certificate> certs = new ArrayList<Certificate>(); X509Certificate testrootcert = CertTools.getCertfromByteArray(testroot, X509Certificate.class); certs.add(testrootcert);/*from ww w . jav a 2 s. co m*/ X509Certificate testrootnewcert = CertTools.getCertfromByteArray(testrootnew, X509Certificate.class); certs.add(testrootnewcert); X509Certificate testsubcert = CertTools.getCertfromByteArray(testsub, X509Certificate.class); certs.add(testsubcert); Certificate testcvccert = CertTools.getCertfromByteArray(testcvc, Certificate.class); certs.add(testcvccert); X509Certificate testscepcert = CertTools.getCertfromByteArray(testscepca, X509Certificate.class); certs.add(testscepcert); CaCertificateCache cache = CaCertificateCache.INSTANCE; cache.loadCertificates(certs); // Test lookup of not existing cert X509Certificate cert = cache.findLatestBySubjectDN(HashID.getFromDNString("CN=Foo,C=SE")); assertNull(cert); // Old root cert should not be found, we only store the latest to be found by subjectDN X509Certificate rootcert = cache.findLatestBySubjectDN(HashID.getFromSubjectDN(testrootnewcert)); assertNotNull(rootcert); X509Certificate subcert = cache.findLatestBySubjectDN(HashID.getFromSubjectDN(testsubcert)); // This old subcert should not be possible to verify with the new root cert try { subcert.verify(rootcert.getPublicKey()); fail("verification should have failed"); } catch (SignatureException e) { } // NOPMD: BC 1.47 // CVC certificate should not be part of OCSP certificate cache cert = cache.findLatestBySubjectDN(HashID.getFromDNString(CertTools.getSubjectDN(testcvccert))); assertNull(cert); cert = cache.findLatestBySubjectDN(HashID.getFromSubjectDN(testscepcert)); assertEquals(CertTools.getSubjectDN(testscepcert), CertTools.getSubjectDN(cert)); }
From source file:org.cesecore.certificates.ca.X509CA.java
@Override public byte[] createPKCS7(CryptoToken cryptoToken, Certificate cert, boolean includeChain) throws SignRequestSignatureException { // First verify that we signed this certificate try {// ww w .j a va 2 s . c o m if (cert != null) { final PublicKey verifyKey; final X509Certificate cacert = (X509Certificate) getCACertificate(); if (cacert != null) { verifyKey = cacert.getPublicKey(); } else { verifyKey = cryptoToken .getPublicKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); } cert.verify(verifyKey); } } catch (CryptoTokenOfflineException e) { throw new SignRequestSignatureException("The cryptotoken was not available, could not create a PKCS7", e); } catch (InvalidKeyException e) { throw new SignRequestSignatureException("The specified certificate contains the wrong public key.", e); } catch (CertificateException e) { throw new SignRequestSignatureException("An encoding error was encountered.", e); } catch (NoSuchAlgorithmException e) { throw new SignRequestSignatureException( "The certificate provided was signed with an invalid algorithm.", e); } catch (NoSuchProviderException e) { throw new SignRequestSignatureException( "The crypto provider was not found for verification of the certificate.", e); } catch (SignatureException e) { throw new SignRequestSignatureException("Cannot verify certificate in createPKCS7(), did I sign this?", e); } Collection<Certificate> chain = getCertificateChain(); ArrayList<X509CertificateHolder> certList = new ArrayList<X509CertificateHolder>(); try { if (cert != null) { certList.add(new JcaX509CertificateHolder((X509Certificate) cert)); } if (includeChain) { for (Certificate certificate : chain) { certList.add(new JcaX509CertificateHolder((X509Certificate) certificate)); } } } catch (CertificateEncodingException e) { throw new SignRequestSignatureException("Could not encode certificate", e); } try { CMSTypedData msg = new CMSProcessableByteArray("EJBCA".getBytes()); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); final PrivateKey privateKey = cryptoToken .getPrivateKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); if (privateKey == null) { String msg1 = "createPKCS7: Private key does not exist!"; log.debug(msg1); throw new SignRequestSignatureException(msg1); } String signatureAlgorithmName = AlgorithmTools .getAlgorithmNameFromDigestAndKey(CMSSignedGenerator.DIGEST_SHA1, privateKey.getAlgorithm()); try { ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName) .setProvider(cryptoToken.getSignProviderName()).build(privateKey); JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME); JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder( calculatorProviderBuilder.build()); gen.addSignerInfoGenerator(builder.build(contentSigner, (X509Certificate) getCACertificate())); } catch (OperatorCreationException e) { throw new IllegalStateException("BouncyCastle failed in creating signature provider.", e); } gen.addCertificates(new CollectionStore(certList)); CMSSignedData s = null; CAToken catoken = getCAToken(); if (catoken != null && !(cryptoToken instanceof NullCryptoToken)) { log.debug("createPKCS7: Provider=" + cryptoToken.getSignProviderName() + " using algorithm " + privateKey.getAlgorithm()); s = gen.generate(msg, true); } else { String msg1 = "CA Token does not exist!"; log.debug(msg); throw new SignRequestSignatureException(msg1); } return s.getEncoded(); } catch (CryptoTokenOfflineException e) { throw new RuntimeException(e); } catch (Exception e) { //FIXME: This right here is just nasty throw new RuntimeException(e); } }