javax.xml.crypto.dsig.keyinfo.KeyInfoFactory Java Examples

The following examples show how to use javax.xml.crypto.dsig.keyinfo.KeyInfoFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DigitalSignatures.java    From org.hl7.fhir.core with Apache License 2.0 8 votes vote down vote up
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException, FHIRException {
  // http://docs.oracle.com/javase/7/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html
  //
  byte[] inputXml = "<Envelope xmlns=\"urn:envelope\">\r\n</Envelope>\r\n".getBytes();
  // load the document that's going to be signed
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
  dbf.setNamespaceAware(true);
  DocumentBuilder builder = dbf.newDocumentBuilder();  
  Document doc = builder.parse(new ByteArrayInputStream(inputXml)); 
  
  // create a key pair
  KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
  kpg.initialize(512);
  KeyPair kp = kpg.generateKeyPair(); 
  
  // sign the document
  DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement()); 
  XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); 
 
  Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
  SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
  
  KeyInfoFactory kif = fac.getKeyInfoFactory(); 
  KeyValue kv = kif.newKeyValue(kp.getPublic());
  KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
  XMLSignature signature = fac.newXMLSignature(si, ki); 
  signature.sign(dsc);
  
  OutputStream os = System.out;
  new XmlGenerator().generate(doc.getDocumentElement(), os);
}
 
Example #2
Source File: DigitalSignatures.java    From org.hl7.fhir.core with Apache License 2.0 7 votes vote down vote up
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException, FHIRException, org.hl7.fhir.exceptions.FHIRException {
  // http://docs.oracle.com/javase/7/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html
  //
  byte[] inputXml = "<Envelope xmlns=\"urn:envelope\">\r\n</Envelope>\r\n".getBytes();
  // load the document that's going to be signed
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
  dbf.setNamespaceAware(true);
  DocumentBuilder builder = dbf.newDocumentBuilder();  
  Document doc = builder.parse(new ByteArrayInputStream(inputXml)); 
  
  // create a key pair
  KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
  kpg.initialize(512);
  KeyPair kp = kpg.generateKeyPair(); 
  
  // sign the document
  DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement()); 
  XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); 
 
  Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
  SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
  
  KeyInfoFactory kif = fac.getKeyInfoFactory(); 
  KeyValue kv = kif.newKeyValue(kp.getPublic());
  KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
  XMLSignature signature = fac.newXMLSignature(si, ki); 
  signature.sign(dsc);
  
  OutputStream os = System.out;
  new XmlGenerator().generate(doc.getDocumentElement(), os);
}
 
Example #3
Source File: STSServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void signRequest(Element requestElement, PrivateKey privateKey, Object keyInfoValue) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, KeyException {
   DOMSignContext domSignContext = new DOMSignContext(privateKey, requestElement, requestElement.getFirstChild());
   String requestId = requestElement.getAttribute("RequestID");
   requestElement.setIdAttribute("RequestID", true);
   List<Transform> transforms = new LinkedList();
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature", (TransformParameterSpec)null));
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null));
   Reference reference = xmlSignatureFactory.newReference("#" + requestId, xmlSignatureFactory.newDigestMethod("http://www.w3.org/2000/09/xmldsig#sha1", (DigestMethodParameterSpec)null), transforms, (String)null, (String)null);
   CanonicalizationMethod canonicalizationMethod = xmlSignatureFactory.newCanonicalizationMethod("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null);
   SignatureMethod signatureMethod = xmlSignatureFactory.newSignatureMethod("http://www.w3.org/2000/09/xmldsig#rsa-sha1", (SignatureMethodParameterSpec)null);
   SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference));
   KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
   KeyInfo keyInfo = null;
   if (keyInfoValue instanceof PublicKey) {
      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newKeyValue((PublicKey)keyInfoValue)));
   } else {
      if (!(keyInfoValue instanceof X509Certificate)) {
         throw new IllegalArgumentException("Unsupported keyinfo type [" + keyInfoValue.getClass() + "]");
      }

      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newX509Data(Collections.singletonList(keyInfoValue))));
   }

   XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);
   xmlSignature.sign(domSignContext);
}
 
Example #4
Source File: GetInstanceTests.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void TestKeyInfoFactory() throws Exception {
    KeyInfoFactory fac = KeyInfoFactory.getInstance();
    Provider p = fac.getProvider();
    String mechType = fac.getMechanismType();
    Provider p2;
    try {
        fac = KeyInfoFactory.getInstance(mechType);
        p2 = fac.getProvider();
        fac = KeyInfoFactory.getInstance(mechType, p);
        fac = KeyInfoFactory.getInstance(mechType, p.getName());
    } catch (Exception ex) {
        throw new RuntimeException("Error: Unexpected exception", ex);
    }
    if (p2.getName() != p.getName()) {
        throw new RuntimeException("Error: Provider equality check failed");
    }
}
 
Example #5
Source File: Assinar.java    From Java_CTe with MIT License 6 votes vote down vote up
private static void loadCertificates(ConfiguracoesCte config, XMLSignatureFactory signatureFactory)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException, CertificadoException {

    Certificado certificado = config.getCertificado();
    KeyStore keyStore = CertificadoService.getKeyStore(certificado);

    KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(certificado.getNome(),
            new KeyStore.PasswordProtection(certificado.getSenha().toCharArray()));
    privateKey = pkEntry.getPrivateKey();

    KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
    List<X509Certificate> x509Content = new ArrayList<X509Certificate>();

    x509Content.add(CertificadoService.getCertificate(certificado, keyStore));
    X509Data x509Data = keyInfoFactory.newX509Data(x509Content);
    keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data));
}
 
Example #6
Source File: Assinar.java    From Java_NFe with MIT License 6 votes vote down vote up
private static void loadCertificates(ConfiguracoesNfe config, XMLSignatureFactory signatureFactory)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException, CertificadoException {

    Certificado certificado = config.getCertificado();
    KeyStore keyStore = CertificadoService.getKeyStore(certificado);

    KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(certificado.getNome(),
            new KeyStore.PasswordProtection(certificado.getSenha().toCharArray()));
    privateKey = pkEntry.getPrivateKey();

    KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
    List<X509Certificate> x509Content = new ArrayList<X509Certificate>();

    x509Content.add(CertificadoService.getCertificate(certificado, keyStore));
    X509Data x509Data = keyInfoFactory.newX509Data(x509Content);
    keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data));
}
 
Example #7
Source File: STSServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void signRequest(Element requestElement, PrivateKey privateKey, Object keyInfoValue) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, KeyException {
   DOMSignContext domSignContext = new DOMSignContext(privateKey, requestElement, requestElement.getFirstChild());
   String requestId = requestElement.getAttribute("RequestID");
   requestElement.setIdAttribute("RequestID", true);
   List<Transform> transforms = new LinkedList();
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature", (TransformParameterSpec)null));
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null));
   Reference reference = xmlSignatureFactory.newReference("#" + requestId, xmlSignatureFactory.newDigestMethod("http://www.w3.org/2000/09/xmldsig#sha1", (DigestMethodParameterSpec)null), transforms, (String)null, (String)null);
   CanonicalizationMethod canonicalizationMethod = xmlSignatureFactory.newCanonicalizationMethod("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null);
   SignatureMethod signatureMethod = xmlSignatureFactory.newSignatureMethod("http://www.w3.org/2000/09/xmldsig#rsa-sha1", (SignatureMethodParameterSpec)null);
   SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference));
   KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
   KeyInfo keyInfo = null;
   if (keyInfoValue instanceof PublicKey) {
      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newKeyValue((PublicKey)keyInfoValue)));
   } else {
      if (!(keyInfoValue instanceof X509Certificate)) {
         throw new IllegalArgumentException("Unsupported keyinfo type [" + keyInfoValue.getClass() + "]");
      }

      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newX509Data(Collections.singletonList(keyInfoValue))));
   }

   XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);
   xmlSignature.sign(domSignContext);
}
 
Example #8
Source File: STSServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void signRequest(Element requestElement, PrivateKey privateKey, Object keyInfoValue) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, KeyException {
   DOMSignContext domSignContext = new DOMSignContext(privateKey, requestElement, requestElement.getFirstChild());
   String requestId = requestElement.getAttribute("RequestID");
   requestElement.setIdAttribute("RequestID", true);
   List<Transform> transforms = new LinkedList();
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature", (TransformParameterSpec)null));
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null));
   Reference reference = xmlSignatureFactory.newReference("#" + requestId, xmlSignatureFactory.newDigestMethod("http://www.w3.org/2000/09/xmldsig#sha1", (DigestMethodParameterSpec)null), transforms, (String)null, (String)null);
   CanonicalizationMethod canonicalizationMethod = xmlSignatureFactory.newCanonicalizationMethod("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null);
   SignatureMethod signatureMethod = xmlSignatureFactory.newSignatureMethod("http://www.w3.org/2000/09/xmldsig#rsa-sha1", (SignatureMethodParameterSpec)null);
   SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference));
   KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
   KeyInfo keyInfo = null;
   if (keyInfoValue instanceof PublicKey) {
      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newKeyValue((PublicKey)keyInfoValue)));
   } else {
      if (!(keyInfoValue instanceof X509Certificate)) {
         throw new IllegalArgumentException("Unsupported keyinfo type [" + keyInfoValue.getClass() + "]");
      }

      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newX509Data(Collections.singletonList(keyInfoValue))));
   }

   XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);
   xmlSignature.sign(domSignContext);
}
 
Example #9
Source File: STSServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void signRequest(Element requestElement, PrivateKey privateKey, Object keyInfoValue) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, KeyException {
   DOMSignContext domSignContext = new DOMSignContext(privateKey, requestElement, requestElement.getFirstChild());
   String requestId = requestElement.getAttribute("RequestID");
   requestElement.setIdAttribute("RequestID", true);
   List<Transform> transforms = new LinkedList();
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature", (TransformParameterSpec)null));
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null));
   Reference reference = xmlSignatureFactory.newReference("#" + requestId, xmlSignatureFactory.newDigestMethod("http://www.w3.org/2000/09/xmldsig#sha1", (DigestMethodParameterSpec)null), transforms, (String)null, (String)null);
   CanonicalizationMethod canonicalizationMethod = xmlSignatureFactory.newCanonicalizationMethod("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null);
   SignatureMethod signatureMethod = xmlSignatureFactory.newSignatureMethod("http://www.w3.org/2000/09/xmldsig#rsa-sha1", (SignatureMethodParameterSpec)null);
   SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference));
   KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
   KeyInfo keyInfo = null;
   if (keyInfoValue instanceof PublicKey) {
      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newKeyValue((PublicKey)keyInfoValue)));
   } else {
      if (!(keyInfoValue instanceof X509Certificate)) {
         throw new IllegalArgumentException("Unsupported keyinfo type [" + keyInfoValue.getClass() + "]");
      }

      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newX509Data(Collections.singletonList(keyInfoValue))));
   }

   XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);
   xmlSignature.sign(domSignContext);
}
 
Example #10
Source File: STSServiceImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private void signRequest(Element requestElement, PrivateKey privateKey, Object keyInfoValue) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, KeyException {
   DOMSignContext domSignContext = new DOMSignContext(privateKey, requestElement, requestElement.getFirstChild());
   String requestId = requestElement.getAttribute("RequestID");
   requestElement.setIdAttribute("RequestID", true);
   List<Transform> transforms = new LinkedList();
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature", (TransformParameterSpec)null));
   transforms.add(xmlSignatureFactory.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null));
   Reference reference = xmlSignatureFactory.newReference("#" + requestId, xmlSignatureFactory.newDigestMethod("http://www.w3.org/2000/09/xmldsig#sha1", (DigestMethodParameterSpec)null), transforms, (String)null, (String)null);
   CanonicalizationMethod canonicalizationMethod = xmlSignatureFactory.newCanonicalizationMethod("http://www.w3.org/2001/10/xml-exc-c14n#", (C14NMethodParameterSpec)null);
   SignatureMethod signatureMethod = xmlSignatureFactory.newSignatureMethod("http://www.w3.org/2000/09/xmldsig#rsa-sha1", (SignatureMethodParameterSpec)null);
   SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference));
   KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
   KeyInfo keyInfo = null;
   if (keyInfoValue instanceof PublicKey) {
      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newKeyValue((PublicKey)keyInfoValue)));
   } else {
      if (!(keyInfoValue instanceof X509Certificate)) {
         throw new IllegalArgumentException("Unsupported keyinfo type [" + keyInfoValue.getClass() + "]");
      }

      keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyInfoFactory.newX509Data(Collections.singletonList(keyInfoValue))));
   }

   XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);
   xmlSignature.sign(domSignContext);
}
 
Example #11
Source File: XmlSignature.java    From cstc with GNU General Public License v3.0 6 votes vote down vote up
protected KeyInfo getKeyInfo() throws Exception {
  PrivateKeyEntry keyEntry = this.selectedEntry;
  String keyInfoChoice = (String) includeKeyInfo.getSelectedItem();
  if( Boolean.parseBoolean(keyInfoChoice) ) {
    X509Certificate cert = (X509Certificate)keyEntry.getCertificate();
    KeyInfoFactory keyInfoFac = signatureFac.getKeyInfoFactory();
    List<Object> x509Content = new ArrayList<Object>();
    if( this.subject.isSelected() ) {
      x509Content.add(cert.getSubjectX500Principal().getName());
    } 
    if( this.serialIssuer.isSelected() ) {
      x509Content.add(keyInfoFac.newX509IssuerSerial(cert.getIssuerX500Principal().getName(),cert.getSerialNumber()));
    }
    if( this.issuer.isSelected() ) {
      x509Content.add(cert.getIssuerX500Principal().getName());
    }
    if( this.certificate.isSelected() ) {
      x509Content.add(cert);
    }
    X509Data xd = keyInfoFac.newX509Data(x509Content);
    return keyInfoFac.newKeyInfo(Collections.singletonList(xd));
  }
  return (KeyInfo)null;
}
 
Example #12
Source File: SoapMultiSignature.java    From cstc with GNU General Public License v3.0 6 votes vote down vote up
private KeyInfo getKeyInfo(XMLSignatureFactory fac, PrivateKeyEntry keyEntry) throws Exception {
  String keyInfoChoice = (String) includeKeyInfo.getSelectedItem();
  if( Boolean.parseBoolean(keyInfoChoice) ) {
    KeyInfo keyInfo;
    X509Certificate cert = (X509Certificate)keyEntry.getCertificate();
    KeyInfoFactory keyInfoFac = fac.getKeyInfoFactory();
    List<Object> x509Content = new ArrayList<Object>();
    if( this.subject.isSelected() ) {
      x509Content.add(cert.getSubjectX500Principal().getName());
    } 
    if( this.serialIssuer.isSelected() ) {
      x509Content.add(keyInfoFac.newX509IssuerSerial(cert.getIssuerX500Principal().getName(),cert.getSerialNumber()));
    }
    if( this.issuer.isSelected() ) {
      x509Content.add(cert.getIssuerX500Principal().getName());
    }
    if( this.certificate.isSelected() ) {
      x509Content.add(cert);
    }
    X509Data xd = keyInfoFac.newX509Data(x509Content);
    keyInfo = keyInfoFac.newKeyInfo(Collections.singletonList(xd));
    return keyInfo;
  }
  return (KeyInfo)null;
}
 
Example #13
Source File: XMLSignatureUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private static KeyInfo createKeyInfo(String keyName, PublicKey publicKey, X509Certificate x509Certificate) throws KeyException {
    KeyInfoFactory keyInfoFactory = fac.getKeyInfoFactory();

    List<XMLStructure> items = new LinkedList<>();

    if (keyName != null) {
        items.add(keyInfoFactory.newKeyName(keyName));
    }

    if (x509Certificate != null) {
        items.add(keyInfoFactory.newX509Data(Collections.singletonList(x509Certificate)));
    }

    if (publicKey != null) {
        items.add(keyInfoFactory.newKeyValue(publicKey));
    }

    return keyInfoFactory.newKeyInfo(items);
}
 
Example #14
Source File: Marshal.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    KeyInfoFactory fac = KeyInfoFactory.getInstance();
    KeyInfo ki = fac.newKeyInfo
        (Collections.singletonList(fac.newKeyName("foo")), "keyid");
    try {
        ki.marshal(null, null);
        throw new Exception("Should raise a NullPointerException");
    } catch (NullPointerException npe) {}

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().newDocument();
    Element elem = doc.createElementNS("http://acme.org", "parent");
    doc.appendChild(elem);
    DOMStructure parent = new DOMStructure(elem);
    ki.marshal(parent, null);

    Element kiElem = DOMUtils.getFirstChildElement(elem);
    if (!kiElem.getLocalName().equals("KeyInfo")) {
        throw new Exception
            ("Should be KeyInfo element: " + kiElem.getLocalName());
    }
    Element knElem = DOMUtils.getFirstChildElement(kiElem);
    if (!knElem.getLocalName().equals("KeyName")) {
        throw new Exception
            ("Should be KeyName element: " + knElem.getLocalName());
    }
}
 
Example #15
Source File: Marshal.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    KeyInfoFactory fac = KeyInfoFactory.getInstance();
    KeyInfo ki = fac.newKeyInfo
        (Collections.singletonList(fac.newKeyName("foo")), "keyid");
    try {
        ki.marshal(null, null);
        throw new Exception("Should raise a NullPointerException");
    } catch (NullPointerException npe) {}

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().newDocument();
    Element elem = doc.createElementNS("http://acme.org", "parent");
    doc.appendChild(elem);
    DOMStructure parent = new DOMStructure(elem);
    ki.marshal(parent, null);

    Element kiElem = DOMUtils.getFirstChildElement(elem);
    if (!kiElem.getLocalName().equals("KeyInfo")) {
        throw new Exception
            ("Should be KeyInfo element: " + kiElem.getLocalName());
    }
    Element knElem = DOMUtils.getFirstChildElement(kiElem);
    if (!knElem.getLocalName().equals("KeyName")) {
        throw new Exception
            ("Should be KeyName element: " + knElem.getLocalName());
    }
}
 
Example #16
Source File: Marshal.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    KeyInfoFactory fac = KeyInfoFactory.getInstance();
    KeyInfo ki = fac.newKeyInfo
        (Collections.singletonList(fac.newKeyName("foo")), "keyid");
    try {
        ki.marshal(null, null);
        throw new Exception("Should raise a NullPointerException");
    } catch (NullPointerException npe) {}

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().newDocument();
    Element elem = doc.createElementNS("http://acme.org", "parent");
    doc.appendChild(elem);
    DOMStructure parent = new DOMStructure(elem);
    ki.marshal(parent, null);

    Element kiElem = DOMUtils.getFirstChildElement(elem);
    if (!kiElem.getLocalName().equals("KeyInfo")) {
        throw new Exception
            ("Should be KeyInfo element: " + kiElem.getLocalName());
    }
    Element knElem = DOMUtils.getFirstChildElement(kiElem);
    if (!knElem.getLocalName().equals("KeyName")) {
        throw new Exception
            ("Should be KeyName element: " + knElem.getLocalName());
    }
}
 
Example #17
Source File: Marshal.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    KeyInfoFactory fac = KeyInfoFactory.getInstance();
    KeyInfo ki = fac.newKeyInfo
        (Collections.singletonList(fac.newKeyName("foo")), "keyid");
    try {
        ki.marshal(null, null);
        throw new Exception("Should raise a NullPointerException");
    } catch (NullPointerException npe) {}

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().newDocument();
    Element elem = doc.createElementNS("http://acme.org", "parent");
    doc.appendChild(elem);
    DOMStructure parent = new DOMStructure(elem);
    ki.marshal(parent, null);

    Element kiElem = DOMUtils.getFirstChildElement(elem);
    if (!kiElem.getLocalName().equals("KeyInfo")) {
        throw new Exception
            ("Should be KeyInfo element: " + kiElem.getLocalName());
    }
    Element knElem = DOMUtils.getFirstChildElement(kiElem);
    if (!knElem.getLocalName().equals("KeyName")) {
        throw new Exception
            ("Should be KeyName element: " + knElem.getLocalName());
    }
}
 
Example #18
Source File: Marshal.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    KeyInfoFactory fac = KeyInfoFactory.getInstance();
    KeyInfo ki = fac.newKeyInfo
        (Collections.singletonList(fac.newKeyName("foo")), "keyid");
    try {
        ki.marshal(null, null);
        throw new Exception("Should raise a NullPointerException");
    } catch (NullPointerException npe) {}

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().newDocument();
    Element elem = doc.createElementNS("http://acme.org", "parent");
    doc.appendChild(elem);
    DOMStructure parent = new DOMStructure(elem);
    ki.marshal(parent, null);

    Element kiElem = DOMUtils.getFirstChildElement(elem);
    if (!kiElem.getLocalName().equals("KeyInfo")) {
        throw new Exception
            ("Should be KeyInfo element: " + kiElem.getLocalName());
    }
    Element knElem = DOMUtils.getFirstChildElement(kiElem);
    if (!knElem.getLocalName().equals("KeyName")) {
        throw new Exception
            ("Should be KeyName element: " + knElem.getLocalName());
    }
}
 
Example #19
Source File: Marshal.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    KeyInfoFactory fac = KeyInfoFactory.getInstance();
    KeyInfo ki = fac.newKeyInfo
        (Collections.singletonList(fac.newKeyName("foo")), "keyid");
    try {
        ki.marshal(null, null);
        throw new Exception("Should raise a NullPointerException");
    } catch (NullPointerException npe) {}

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().newDocument();
    Element elem = doc.createElementNS("http://acme.org", "parent");
    doc.appendChild(elem);
    DOMStructure parent = new DOMStructure(elem);
    ki.marshal(parent, null);

    Element kiElem = DOMUtils.getFirstChildElement(elem);
    if (!kiElem.getLocalName().equals("KeyInfo")) {
        throw new Exception
            ("Should be KeyInfo element: " + kiElem.getLocalName());
    }
    Element knElem = DOMUtils.getFirstChildElement(kiElem);
    if (!knElem.getLocalName().equals("KeyName")) {
        throw new Exception
            ("Should be KeyName element: " + knElem.getLocalName());
    }
}
 
Example #20
Source File: Marshal.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    KeyInfoFactory fac = KeyInfoFactory.getInstance();
    KeyInfo ki = fac.newKeyInfo
        (Collections.singletonList(fac.newKeyName("foo")), "keyid");
    try {
        ki.marshal(null, null);
        throw new Exception("Should raise a NullPointerException");
    } catch (NullPointerException npe) {}

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().newDocument();
    Element elem = doc.createElementNS("http://acme.org", "parent");
    doc.appendChild(elem);
    DOMStructure parent = new DOMStructure(elem);
    ki.marshal(parent, null);

    Element kiElem = DOMUtils.getFirstChildElement(elem);
    if (!kiElem.getLocalName().equals("KeyInfo")) {
        throw new Exception
            ("Should be KeyInfo element: " + kiElem.getLocalName());
    }
    Element knElem = DOMUtils.getFirstChildElement(kiElem);
    if (!knElem.getLocalName().equals("KeyName")) {
        throw new Exception
            ("Should be KeyName element: " + knElem.getLocalName());
    }
}
 
Example #21
Source File: XMLSignatureBuilder.java    From development with Apache License 2.0 5 votes vote down vote up
public Document sign(FileInputStream fileStream, KeyPair keyPair)
        throws ParserConfigurationException, SAXException, IOException,
        NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        KeyException, MarshalException, XMLSignatureException {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);

    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(fileStream);

    DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(),
            document.getDocumentElement());
    XMLSignatureFactory signFactory = XMLSignatureFactory
            .getInstance("DOM");
    Reference ref = signFactory.newReference("", signFactory
            .newDigestMethod(digestMethod, null), Collections
            .singletonList(signFactory.newTransform(Transform.ENVELOPED,
                    (TransformParameterSpec) null)), null, null);
    SignedInfo si = signFactory.newSignedInfo(signFactory
            .newCanonicalizationMethod(
                    CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null), signFactory
            .newSignatureMethod(signatureMethod, null), Collections
            .singletonList(ref));

    KeyInfoFactory kif = signFactory.getKeyInfoFactory();
    KeyValue kv = kif.newKeyValue(keyPair.getPublic());
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));

    XMLSignature signature = signFactory.newXMLSignature(si, ki);
    signature.sign(signContext);

    return document;
}
 
Example #22
Source File: SignatureVerifier.java    From IDES-Data-Preparation-Java with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
protected void setSigPublicKeyFromXml(String xml, DocumentBuilder docBuilderNSTrue) throws Exception {
	xml = sigStartElemToWrapXml + xml + sigEndElemToWrapXml;
       Document doc = docBuilderNSTrue.parse(new InputSource(new StringReader(xml)));
       DOMStructure ds = new DOMStructure(doc.getDocumentElement().getFirstChild());
       KeyInfo keyInfo = KeyInfoFactory.getInstance().unmarshalKeyInfo(ds);
	List<?> list = keyInfo.getContent();
	for (int i = 0; i < list.size(); i++) {
		XMLStructure xmlStructure = (XMLStructure) list.get(i);
		if (xmlStructure instanceof KeyValue) {
			try {
				sigPublicKey = ((KeyValue)xmlStructure).getPublicKey();
			} catch(KeyException ke) {
				throw new KeySelectorException(ke.getMessage());
			}
			break;
		} else if (xmlStructure instanceof X509Data) {
			X509Data x509data = (X509Data)xmlStructure;
			List<?> x509datalist = x509data.getContent();
			for (int j = 0; j < x509datalist.size(); j++) {
				if (x509datalist.get(j) instanceof X509Certificate) {
					X509Certificate cert = (X509Certificate)x509datalist.get(j);
					sigPublicKey = cert.getPublicKey();
					break;
				}
			}
		}
	}
}
 
Example #23
Source File: XmlSecurityIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
private static KeyAccessor getKeyAccessor(final PrivateKey privateKey) {
    KeyAccessor accessor = new KeyAccessor() {

        @Override
        public KeySelector getKeySelector(Message message) throws Exception {
            return KeySelector.singletonKeySelector(privateKey);
        }

        @Override
        public KeyInfo getKeyInfo(Message mess, Node messageBody, KeyInfoFactory keyInfoFactory) throws Exception {
            return null;
        }
    };
    return accessor;
}
 
Example #24
Source File: XML.java    From restcommander with Apache License 2.0 5 votes vote down vote up
/**
 * Sign the XML document using xmldsig.
 * @param document the document to sign; it will be modified by the method.
 * @param publicKey the public key from the key pair to sign the document.
 * @param privateKey the private key from the key pair to sign the document.
 * @return the signed document for chaining.
 */
public static Document sign(Document document, RSAPublicKey publicKey, RSAPrivateKey privateKey) {
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
    KeyInfoFactory keyInfoFactory = fac.getKeyInfoFactory();

    try {
        Reference ref =fac.newReference(
                "",
                fac.newDigestMethod(DigestMethod.SHA1, null),
                Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
                null,
                null);
        SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE,
                                                                        (C14NMethodParameterSpec) null),
                                          fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
                                          Collections.singletonList(ref));
        DOMSignContext dsc = new DOMSignContext(privateKey, document.getDocumentElement());
        KeyValue keyValue = keyInfoFactory.newKeyValue(publicKey);
        KeyInfo ki = keyInfoFactory.newKeyInfo(Collections.singletonList(keyValue));
        XMLSignature signature = fac.newXMLSignature(si, ki);
        signature.sign(dsc);
    } catch (Exception e) {
        Logger.warn("Error while signing an XML document.", e);
    }

    return document;
}
 
Example #25
Source File: XmlSignatureHelper.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Signs the SAML assertion using the specified public and private keys.
 * 
 * @param document
 *            SAML assertion be signed.
 * @param privateKey
 *            Private key used to sign SAML assertion.
 * @param publicKey
 *            Public key used to sign SAML asserion.
 * @return w3c element representation of specified document.
 * @throws NoSuchAlgorithmException
 * @throws InvalidAlgorithmParameterException
 * @throws KeyException
 * @throws MarshalException
 * @throws XMLSignatureException
 */
private Element signSamlAssertion(Document document, PrivateKey privateKey, X509Certificate certificate)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException,
        XMLSignatureException {
    XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");
    List<Transform> envelopedTransform = Collections.singletonList(signatureFactory.newTransform(
            Transform.ENVELOPED, (TransformParameterSpec) null));
    Reference ref = signatureFactory.newReference("", signatureFactory.newDigestMethod(DigestMethod.SHA1, null),
            envelopedTransform, null, null);
    
    SignatureMethod signatureMethod = null;
    if (certificate.getPublicKey() instanceof DSAPublicKey) {
        signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null);
    } else if (certificate.getPublicKey() instanceof RSAPublicKey) {
        signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
    }
    
    CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod(
            CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null);
    
    SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod,
            Collections.singletonList(ref));
    
    KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
    X509Data data = keyInfoFactory.newX509Data(Collections.singletonList(certificate));
    KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(data));
    
    Element w3cElement = document.getDocumentElement();
    Node xmlSigInsertionPoint = getXmlSignatureInsertionLocation(w3cElement);
    DOMSignContext dsc = new DOMSignContext(privateKey, w3cElement, xmlSigInsertionPoint);
    
    XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, keyInfo);
    signature.sign(dsc);
    return w3cElement;
}
 
Example #26
Source File: XmlSignatureApplet.java    From juddi with Apache License 2.0 5 votes vote down vote up
private void signDOM(Node node, PrivateKey privateKey, Certificate origCert) {
    XMLSignatureFactory fac = initXMLSigFactory();
    X509Certificate cert = (X509Certificate) origCert;
    // Create the KeyInfo containing the X509Data.
    KeyInfoFactory kif = fac.getKeyInfoFactory();
    List<Object> x509Content = new ArrayList<Object>();
    //x509Content.add(cert.getSubjectX500Principal().getName());
    x509Content.add(cert);
    X509Data xd = kif.newX509Data(x509Content);
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));

    // Create a DOMSignContext and specify the RSA PrivateKey and
    // location of the resulting XMLSignature's parent element.
    DOMSignContext dsc = new DOMSignContext(privateKey, node);
    dsc.putNamespacePrefix(XML_DIGSIG_NS, "ns2");

    // Create the XMLSignature, but don't sign it yet.
    try {
        SignedInfo si = initSignedInfo(fac);
        XMLSignature signature = fac.newXMLSignature(si, ki);

        // Marshal, generate, and sign the enveloped signature.
        signature.sign(dsc);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #27
Source File: TckSigningUtil.java    From juddi with Apache License 2.0 5 votes vote down vote up
public static void signDOM(Node node, PrivateKey privateKey, Certificate origCert) {
    XMLSignatureFactory fac = initXMLSigFactory();
    X509Certificate cert = (X509Certificate) origCert;
    // Create the KeyInfo containing the X509Data.
    KeyInfoFactory kif = fac.getKeyInfoFactory();
    List<Object> x509Content = new ArrayList<Object>();
    x509Content.add(cert.getSubjectX500Principal().getName());
    x509Content.add(cert);
    X509Data xd = kif.newX509Data(x509Content);
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));

    // Create a DOMSignContext and specify the RSA PrivateKey and
    // location of the resulting XMLSignature's parent element.
    DOMSignContext dsc = new DOMSignContext(privateKey, node);
    dsc.putNamespacePrefix("http://www.w3.org/2000/09/xmldsig#", "ns2");

    // Create the XMLSignature, but don't sign it yet.
    try {
        SignedInfo si = initSignedInfo(fac);
        XMLSignature signature = fac.newXMLSignature(si, ki);

        // Marshal, generate, and sign the enveloped signature.
        signature.sign(dsc);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #28
Source File: Marshal.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    KeyInfoFactory fac = KeyInfoFactory.getInstance();
    KeyInfo ki = fac.newKeyInfo
        (Collections.singletonList(fac.newKeyName("foo")), "keyid");
    try {
        ki.marshal(null, null);
        throw new Exception("Should raise a NullPointerException");
    } catch (NullPointerException npe) {}

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().newDocument();
    Element elem = doc.createElementNS("http://acme.org", "parent");
    doc.appendChild(elem);
    DOMStructure parent = new DOMStructure(elem);
    ki.marshal(parent, null);

    Element kiElem = DOMUtils.getFirstChildElement(elem);
    if (!kiElem.getLocalName().equals("KeyInfo")) {
        throw new Exception
            ("Should be KeyInfo element: " + kiElem.getLocalName());
    }
    Element knElem = DOMUtils.getFirstChildElement(kiElem);
    if (!knElem.getLocalName().equals("KeyName")) {
        throw new Exception
            ("Should be KeyName element: " + knElem.getLocalName());
    }
}
 
Example #29
Source File: DigitalSignatures.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // http://docs.oracle.com/javase/7/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html
    //
    byte[] inputXml = "<Envelope xmlns=\"urn:envelope\">\r\n</Envelope>\r\n".getBytes();
    // load the document that's going to be signed
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
    dbf.setNamespaceAware(true);
    DocumentBuilder builder = dbf.newDocumentBuilder();  
    Document doc = builder.parse(new ByteArrayInputStream(inputXml)); 
    
//    // create a key pair
//    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
//    kpg.initialize(512);
//    KeyPair kp = kpg.generateKeyPair(); 
    PublicKey pub = getPublicKey("C:\\work\\fhirserver\\tests\\signatures\\public_key.der");
    PrivateKey priv = getPrivateKey("C:\\work\\fhirserver\\tests\\signatures\\private_key.der");
    
    // sign the document
    DOMSignContext dsc = new DOMSignContext(priv, doc.getDocumentElement()); 
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); 
   
    Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
    SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
    
    KeyInfoFactory kif = fac.getKeyInfoFactory(); 
    KeyValue kv = kif.newKeyValue(pub);
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
    XMLSignature signature = fac.newXMLSignature(si, ki); 
    signature.sign(dsc);
    
    OutputStream os = new FileOutputStream("c:\\temp\\java-digsig.xml");
    new XmlGenerator().generate(doc.getDocumentElement(), os);
  }
 
Example #30
Source File: Marshal.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    KeyInfoFactory fac = KeyInfoFactory.getInstance();
    KeyInfo ki = fac.newKeyInfo
        (Collections.singletonList(fac.newKeyName("foo")), "keyid");
    try {
        ki.marshal(null, null);
        throw new Exception("Should raise a NullPointerException");
    } catch (NullPointerException npe) {}

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().newDocument();
    Element elem = doc.createElementNS("http://acme.org", "parent");
    doc.appendChild(elem);
    DOMStructure parent = new DOMStructure(elem);
    ki.marshal(parent, null);

    Element kiElem = DOMUtils.getFirstChildElement(elem);
    if (!kiElem.getLocalName().equals("KeyInfo")) {
        throw new Exception
            ("Should be KeyInfo element: " + kiElem.getLocalName());
    }
    Element knElem = DOMUtils.getFirstChildElement(kiElem);
    if (!knElem.getLocalName().equals("KeyName")) {
        throw new Exception
            ("Should be KeyName element: " + knElem.getLocalName());
    }
}