List of usage examples for java.security.cert X509Certificate getPublicKey
public abstract PublicKey getPublicKey();
From source file:org.apache.pdfbox.pdmodel.encryption.PublicKeySecurityHandler.java
private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0) throws GeneralSecurityException, IOException { ASN1InputStream asn1inputstream = new ASN1InputStream( new ByteArrayInputStream(x509certificate.getTBSCertificate())); TBSCertificateStructure tbscertificatestructure = TBSCertificateStructure .getInstance(asn1inputstream.readObject()); AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.getSubjectPublicKeyInfo() .getAlgorithmId();/* w w w. j av a 2 s. c o m*/ IssuerAndSerialNumber issuerandserialnumber = new IssuerAndSerialNumber(tbscertificatestructure.getIssuer(), tbscertificatestructure.getSerialNumber().getValue()); Cipher cipher = Cipher.getInstance(algorithmidentifier.getObjectId().getId()); cipher.init(1, x509certificate.getPublicKey()); DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0)); RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber); return new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring); }
From source file:org.apache.ws.security.components.crypto.AlgorithmSuiteValidator.java
/** * Check the asymmetric key length//from w w w .ja v a 2 s . c o m */ public void checkAsymmetricKeyLength(X509Certificate x509Certificate) throws WSSecurityException { if (x509Certificate == null) { return; } checkAsymmetricKeyLength(x509Certificate.getPublicKey()); }
From source file:org.apache.ws.security.components.crypto.CryptoBase.java
/** * Reads the SubjectKeyIdentifier information from the certificate. * <p/>/* ww w . j av a 2 s . co m*/ * If the the certificate does not contain a SKI extension then * try to compute the SKI according to RFC3280 using the * SHA-1 hash value of the public key. The second method described * in RFC3280 is not support. Also only RSA public keys are supported. * If we cannot compute the SKI throw a WSSecurityException. * * @param cert The certificate to read SKI * @return The byte array containing the binary SKI data */ public byte[] getSKIBytesFromCert(X509Certificate cert) throws WSSecurityException { // // Gets the DER-encoded OCTET string for the extension value (extnValue) // identified by the passed-in oid String. The oid string is represented // by a set of positive whole numbers separated by periods. // byte[] derEncodedValue = cert.getExtensionValue(SKI_OID); if (cert.getVersion() < 3 || derEncodedValue == null) { PublicKey key = cert.getPublicKey(); if (!(key instanceof RSAPublicKey)) { throw new WSSecurityException(1, "noSKIHandling", new Object[] { "Support for RSA key only" }); } byte[] encoded = key.getEncoded(); // remove 22-byte algorithm ID and header byte[] value = new byte[encoded.length - 22]; System.arraycopy(encoded, 22, value, 0, value.length); MessageDigest sha; try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { throw new WSSecurityException(WSSecurityException.UNSUPPORTED_SECURITY_TOKEN, "noSKIHandling", new Object[] { "Wrong certificate version (<3) and no SHA1 message digest availabe" }, ex); } sha.reset(); sha.update(value); return sha.digest(); } // // Strip away first four bytes from the DerValue (tag and length of // ExtensionValue OCTET STRING and KeyIdentifier OCTET STRING) // byte abyte0[] = new byte[derEncodedValue.length - 4]; System.arraycopy(derEncodedValue, 4, abyte0, 0, abyte0.length); return abyte0; }
From source file:org.apache.ws.security.components.crypto.Merlin.java
/** * Find the Public Key in a keystore. /* w w w. j av a2 s .com*/ */ private boolean findPublicKeyInKeyStore(PublicKey publicKey, KeyStore keyStoreToSearch) { if (keyStoreToSearch == null) { return false; } try { for (Enumeration<String> e = keyStoreToSearch.aliases(); e.hasMoreElements();) { String alias = e.nextElement(); Certificate[] certs = keyStoreToSearch.getCertificateChain(alias); Certificate cert; if (certs == null || certs.length == 0) { // no cert chain, so lets check if getCertificate gives us a result. cert = keyStoreToSearch.getCertificate(alias); if (cert == null) { continue; } } else { cert = certs[0]; } if (!(cert instanceof X509Certificate)) { continue; } X509Certificate x509cert = (X509Certificate) cert; if (publicKey.equals(x509cert.getPublicKey())) { return true; } } } catch (KeyStoreException e) { return false; } return false; }
From source file:org.apache.ws.security.message.WSSecEncryptedKey.java
/** * Encrypt the symmetric key data and prepare the EncryptedKey element * /* w w w. j a v a2s.c om*/ * This method does the most work for to prepare the EncryptedKey element. * It is also used by the WSSecEncrypt sub-class. * * @param keyBytes The bytes that represent the symmetric key * @param remoteCert The certificate that contains the public key to encrypt the * symmetric key data * @param crypto An instance of the Crypto API to handle keystore and certificates * @throws WSSecurityException */ protected void prepareInternal(byte[] keyBytes, X509Certificate remoteCert, Crypto crypto) throws WSSecurityException { String certUri = UUIDGenerator.getUUID(); Cipher cipher = WSSecurityUtil.getCipherInstance(keyEncAlgo); try { cipher.init(Cipher.ENCRYPT_MODE, remoteCert.getPublicKey()); } catch (InvalidKeyException e) { throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e); } if (doDebug) { log.debug("cipher blksize: " + cipher.getBlockSize() + ", symm key length: " + keyBytes.length); } int blockSize = cipher.getBlockSize(); if (blockSize > 0 && blockSize < keyBytes.length) { throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyTransp", new Object[] { "public key algorithm too weak to encrypt symmetric key" }); } try { this.encryptedEphemeralKey = cipher.doFinal(keyBytes); } catch (IllegalStateException e1) { throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e1); } catch (IllegalBlockSizeException e1) { throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e1); } catch (BadPaddingException e1) { throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e1); } Text keyText = WSSecurityUtil.createBase64EncodedTextNode(document, this.encryptedEphemeralKey); // // Now we need to setup the EncryptedKey header block 1) create a // EncryptedKey element and set a wsu:Id for it 2) Generate ds:KeyInfo // element, this wraps the wsse:SecurityTokenReference 3) Create and set // up the SecurityTokenReference according to the keyIdentifier parameter // 4) Create the CipherValue element structure and insert the encrypted // session key // encryptedKeyElement = createEncryptedKey(document, keyEncAlgo); if (this.encKeyId == null || "".equals(this.encKeyId)) { this.encKeyId = "EncKeyId-" + UUIDGenerator.getUUID(); } encryptedKeyElement.setAttributeNS(null, "Id", this.encKeyId); KeyInfo keyInfo = new KeyInfo(document); SecurityTokenReference secToken = new SecurityTokenReference(document); switch (keyIdentifierType) { case WSConstants.X509_KEY_IDENTIFIER: secToken.setKeyIdentifier(remoteCert); break; case WSConstants.SKI_KEY_IDENTIFIER: secToken.setKeyIdentifierSKI(remoteCert, crypto); break; case WSConstants.THUMBPRINT_IDENTIFIER: secToken.setKeyIdentifierThumb(remoteCert); break; case WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER: // // This identifier is not applicable for this case, so fall back to // ThumbprintRSA. // secToken.setKeyIdentifierThumb(remoteCert); break; case WSConstants.ISSUER_SERIAL: XMLX509IssuerSerial data = new XMLX509IssuerSerial(document, remoteCert); X509Data x509Data = new X509Data(document); x509Data.add(data); secToken.setX509IssuerSerial(x509Data); break; case WSConstants.BST_DIRECT_REFERENCE: Reference ref = new Reference(document); ref.setURI("#" + certUri); bstToken = new X509Security(document); ((X509Security) bstToken).setX509Certificate(remoteCert); bstToken.setID(certUri); ref.setValueType(bstToken.getValueType()); secToken.setReference(ref); break; case WSConstants.CUSTOM_KEY_IDENTIFIER: secToken.setKeyIdentifier(customEKTokenValueType, customEKTokenId); break; default: throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId"); } keyInfo.addUnknownElement(secToken.getElement()); Element keyInfoElement = keyInfo.getElement(); keyInfoElement.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS); encryptedKeyElement.appendChild(keyInfoElement); Element xencCipherValue = createCipherValue(document, encryptedKeyElement); xencCipherValue.appendChild(keyText); envelope = document.getDocumentElement(); envelope.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.ENC_PREFIX, WSConstants.ENC_NS); }
From source file:org.apache.xml.security.keys.keyresolver.implementations.RetrievalMethodResolver.java
/** * Method engineResolvePublicKey/* w w w .jav a2 s . co m*/ * @inheritDoc * @param element * @param BaseURI * @param storage */ public PublicKey engineLookupAndResolvePublicKey(Element element, String BaseURI, StorageResolver storage) { if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RETRIEVALMETHOD)) { return null; } try { // Create a retrieval method over the given element RetrievalMethod rm = new RetrievalMethod(element, BaseURI); String type = rm.getType(); XMLSignatureInput resource = resolveInput(rm, BaseURI); if (RetrievalMethod.TYPE_RAWX509.equals(type)) { // a raw certificate, direct parsing is done! X509Certificate cert = getRawCertificate(resource); if (cert != null) { return cert.getPublicKey(); } return null; } Element e = obtainReferenceElement(resource); return resolveKey(e, BaseURI, storage); } catch (XMLSecurityException ex) { if (log.isDebugEnabled()) { log.debug("XMLSecurityException", ex); } } catch (CertificateException ex) { if (log.isDebugEnabled()) { log.debug("CertificateException", ex); } } catch (IOException ex) { if (log.isDebugEnabled()) { log.debug("IOException", ex); } } catch (ParserConfigurationException e) { if (log.isDebugEnabled()) { log.debug("ParserConfigurationException", e); } } catch (SAXException e) { if (log.isDebugEnabled()) { log.debug("SAXException", e); } } return null; }
From source file:org.apache.xml.security.keys.keyresolver.implementations.X509CertificateResolver.java
/** * Method engineResolvePublicKey//from www. j a v a2s .c o m * @inheritDoc * @param element * @param BaseURI * @param storage * * @throws KeyResolverException */ public PublicKey engineLookupAndResolvePublicKey(Element element, String BaseURI, StorageResolver storage) throws KeyResolverException { X509Certificate cert = this.engineLookupResolveX509Certificate(element, BaseURI, storage); if (cert != null) { return cert.getPublicKey(); } return null; }
From source file:org.apache.xml.security.samples.signature.CreateNullURIReference.java
/** * Method main// www . j a v a 2 s .c om * * @param unused * @throws Exception */ public static void main(String unused[]) throws Exception { //J- String keystoreType = "JKS"; String keystoreFile = "data/org/apache/xml/security/samples/input/keystore.jks"; String keystorePass = "xmlsecurity"; String privateKeyAlias = "test"; String privateKeyPass = "xmlsecurity"; String certificateAlias = "test"; File signatureFile = new File("signature.xml"); //J+ KeyStore ks = KeyStore.getInstance(keystoreType); FileInputStream fis = new FileInputStream(keystoreFile); ks.load(fis, keystorePass.toCharArray()); PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray()); javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.newDocument(); String BaseURI = signatureFile.toURL().toString(); Constants.setSignatureSpecNSprefix(null); XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_DSA); byte[][] memoryData = { "The secret data".getBytes(), "dataset 2".getBytes(), }; sig.addResourceResolver(new NullURIReferenceResolver(memoryData)); doc.appendChild(sig.getElement()); { sig.addDocument(null, null, Constants.ALGO_ID_DIGEST_SHA1); sig.addDocument(null, null, Constants.ALGO_ID_DIGEST_SHA1); } { X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias); sig.addKeyInfo(cert); sig.addKeyInfo(cert.getPublicKey()); System.out.println("Start signing"); sig.sign(privateKey); System.out.println("Finished signing"); } FileOutputStream f = new FileOutputStream(signatureFile); XMLUtils.outputDOMc14nWithComments(doc, f); f.close(); System.out.println("Wrote signature to " + BaseURI); }
From source file:org.apache.xml.security.samples.signature.CreateSignature.java
/** * Method main//from w w w. j ava 2 s. c om * * @param unused * @throws Exception */ public static void main(String unused[]) throws Exception { Constants.setSignatureSpecNSprefix("ds"); //J- //All the parameters for the keystore String keystoreType = "JKS"; String keystoreFile = "data/org/apache/xml/security/samples/input/keystore.jks"; String keystorePass = "xmlsecurity"; String privateKeyAlias = "test"; String privateKeyPass = "xmlsecurity"; String certificateAlias = "test"; File signatureFile = new File("signature.xml"); //J+ 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()); 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">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, "attr1", "test1"); root.setAttributeNS(null, "attr2", "test2"); root.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:foo", "http://example.org/#foo"); root.setAttributeNS("http://example.org/#foo", "foo:attr1", "foo's test"); root.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:apache", "http://www.apache.org/ns/#app1"); doc.appendChild(root); root.appendChild(doc.createTextNode("Some simple text\n")); //The BaseURI is the URI that's used to prepend to relative URIs String BaseURI = signatureFile.toURL().toString(); //Create an XML Signature object from the document, BaseURI and //signature algorithm (in this case DSA) XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_DSA); //Append the signature element to the root element before signing because //this is going to be an enveloped signature. //This means the signature is going to be enveloped by the document. //Two other possible forms are enveloping where the document is inside the //signature and detached where they are seperate. //Note that they can be mixed in 1 signature with seperate references as //shown below. root.appendChild(sig.getElement()); doc.appendChild(doc.createComment(" Comment after ")); sig.getSignedInfo() .addResourceResolver(new org.apache.xml.security.samples.utils.resolver.OfflineResolver()); { //create the transforms object for the Document/Reference Transforms transforms = new Transforms(doc); //First we have to strip away the signature element (it's not part of the //signature calculations). The enveloped transform can be used for this. transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE); //Part of the signature element needs to be canonicalized. It is a kind //of normalizing algorithm for XML. For more information please take a //look at the W3C XML Digital Signature webpage. transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS); //Add the above Document/Reference sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1); } { //Add in 2 external URIs. This is a detached Reference. // // When sign() is called, two network connections are made. -- well, // not really, as we use the OfflineResolver which acts as a proxy for // these two resouces ;-)) // sig.addDocument("http://www.w3.org/TR/xml-stylesheet"); sig.addDocument("http://www.nue.et-inf.uni-siegen.de/index.html"); } { //Add in the KeyInfo for the certificate that we used the private key of X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias); sig.addKeyInfo(cert); sig.addKeyInfo(cert.getPublicKey()); System.out.println("Start signing"); sig.sign(privateKey); System.out.println("Finished signing"); } FileOutputStream f = new FileOutputStream(signatureFile); XMLUtils.outputDOMc14nWithComments(doc, f); f.close(); System.out.println("Wrote signature to " + BaseURI); }
From source file:org.apache.xml.security.samples.signature.HereSigner.java
/** * Method main//from ww w.ja v a 2 s .c o m * * @param unused * @throws Exception */ public static void main(String unused[]) throws Exception { //J- String keystoreType = "JKS"; String keystoreFile = "data/org/apache/xml/security/samples/input/keystore.jks"; String keystorePass = "xmlsecurity"; String privateKeyAlias = "test"; String privateKeyPass = "xmlsecurity"; String certificateAlias = "test"; File signatureFile = new File("hereSignature.xml"); //J+ KeyStore ks = KeyStore.getInstance(keystoreType); FileInputStream fis = new FileInputStream(keystoreFile); ks.load(fis, keystorePass.toCharArray()); PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray()); javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.newDocument(); String BaseURI = signatureFile.toURL().toString(); Constants.setSignatureSpecNSprefix("prof"); XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_DSA); doc.appendChild(sig.getElement()); sig.getSignedInfo() .addResourceResolver(new org.apache.xml.security.samples.utils.resolver.OfflineResolver()); { ObjectContainer ob1 = new ObjectContainer(doc); ob1.setId("object-1"); ob1.appendChild(doc.createTextNode("\nSigned Text\n")); Element c = doc.createElementNS(null, "element"); c.setAttributeNS(null, "name", "val"); ob1.appendChild(c); sig.appendObject(ob1); Transforms transforms = new Transforms(doc); XPathContainer xc = new XPathContainer(doc); xc.setXPathNamespaceContext("prof", Constants.SignatureSpecNS); //J- String xpath = "\n" + "count(" + "\n" + " ancestor-or-self::prof:Object " + "\n" + " | " + "\n" + " here()/ancestor::prof:Signature[1]/child::prof:Object[@Id='object-1']" + "\n" + ") <= count(" + "\n" + " ancestor-or-self::prof:Object" + "\n" + ") " + "\n"; //J+ xc.setXPath(xpath); HelperNodeList nl = new HelperNodeList(); nl.appendChild(doc.createTextNode("\n")); nl.appendChild(xc.getElement()); nl.appendChild(doc.createTextNode("\n")); transforms.addTransform(Transforms.TRANSFORM_XPATH, nl); transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS); sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1); } { X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias); sig.addKeyInfo(cert); sig.addKeyInfo(cert.getPublicKey()); System.out.println("Start signing"); sig.sign(privateKey); System.out.println("Finished signing"); } SignedInfo s = sig.getSignedInfo(); for (int i = 0; i < s.getSignedContentLength(); i++) { System.out.println(new String(s.getSignedContentItem(i))); } FileOutputStream f = new FileOutputStream(signatureFile); XMLUtils.outputDOMc14nWithComments(doc, f); f.close(); System.out.println("Wrote signature to " + BaseURI); }