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

The following examples show how to use javax.xml.crypto.dsig.keyinfo.KeyInfo. 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: DOMKeyInfo.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }

    if (!(o instanceof KeyInfo)) {
        return false;
    }
    KeyInfo oki = (KeyInfo)o;

    boolean idsEqual = (id == null ? oki.getId() == null
                                   : id.equals(oki.getId()));

    return (keyInfoTypes.equals(oki.getContent()) && idsEqual);
}
 
Example #5
Source File: DOMKeyInfo.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }

    if (!(o instanceof KeyInfo)) {
        return false;
    }
    KeyInfo oki = (KeyInfo)o;

    boolean idsEqual = (id == null ? oki.getId() == null
                                   : id.equals(oki.getId()));

    return (keyInfoTypes.equals(oki.getContent()) && idsEqual);
}
 
Example #6
Source File: DOMXMLSignature.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a <code>DOMXMLSignature</code> from the specified components.
 *
 * @param si the <code>SignedInfo</code>
 * @param ki the <code>KeyInfo</code>, or <code>null</code> if not specified
 * @param objs a list of <code>XMLObject</code>s or <code>null</code>
 *  if not specified. The list is copied to protect against subsequent
 *  modification.
 * @param id an optional id (specify <code>null</code> to omit)
 * @param signatureValueId an optional id (specify <code>null</code> to
 *  omit)
 * @throws NullPointerException if <code>si</code> is <code>null</code>
 */
public DOMXMLSignature(SignedInfo si, KeyInfo ki,
                       List<? extends XMLObject> objs,
                       String id, String signatureValueId)
{
    if (si == null) {
        throw new NullPointerException("signedInfo cannot be null");
    }
    this.si = si;
    this.id = id;
    this.sv = new DOMSignatureValue(signatureValueId);
    if (objs == null) {
        this.objects = Collections.emptyList();
    } else {
        this.objects =
            Collections.unmodifiableList(new ArrayList<XMLObject>(objs));
        for (int i = 0, size = this.objects.size(); i < size; i++) {
            if (!(this.objects.get(i) instanceof XMLObject)) {
                throw new ClassCastException
                    ("objs["+i+"] is not an XMLObject");
            }
        }
    }
    this.ki = ki;
}
 
Example #7
Source File: DOMKeyInfo.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }

    if (!(o instanceof KeyInfo)) {
        return false;
    }
    KeyInfo oki = (KeyInfo)o;

    boolean idsEqual = (id == null ? oki.getId() == null
                                   : id.equals(oki.getId()));

    return (keyInfoTypes.equals(oki.getContent()) && idsEqual);
}
 
Example #8
Source File: DOMXMLSignature.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a <code>DOMXMLSignature</code> from the specified components.
 *
 * @param si the <code>SignedInfo</code>
 * @param ki the <code>KeyInfo</code>, or <code>null</code> if not specified
 * @param objs a list of <code>XMLObject</code>s or <code>null</code>
 *  if not specified. The list is copied to protect against subsequent
 *  modification.
 * @param id an optional id (specify <code>null</code> to omit)
 * @param signatureValueId an optional id (specify <code>null</code> to
 *  omit)
 * @throws NullPointerException if <code>si</code> is <code>null</code>
 */
public DOMXMLSignature(SignedInfo si, KeyInfo ki,
                       List<? extends XMLObject> objs,
                       String id, String signatureValueId)
{
    if (si == null) {
        throw new NullPointerException("signedInfo cannot be null");
    }
    this.si = si;
    this.id = id;
    this.sv = new DOMSignatureValue(signatureValueId);
    if (objs == null) {
        this.objects = Collections.emptyList();
    } else {
        this.objects =
            Collections.unmodifiableList(new ArrayList<XMLObject>(objs));
        for (int i = 0, size = this.objects.size(); i < size; i++) {
            if (!(this.objects.get(i) instanceof XMLObject)) {
                throw new ClassCastException
                    ("objs["+i+"] is not an XMLObject");
            }
        }
    }
    this.ki = ki;
}
 
Example #9
Source File: SamlDescriptorIDPKeysExtractor.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public MultivaluedHashMap<String, KeyInfo> parse(InputStream stream) throws ParsingException {
    MultivaluedHashMap<String, KeyInfo> res = new MultivaluedHashMap<>();

    try {
        DocumentBuilder builder = DocumentUtil.getDocumentBuilder();
        Document doc = builder.parse(stream);

        XPathExpression expr = xpath.compile("//m:EntityDescriptor/m:IDPSSODescriptor/m:KeyDescriptor");
        NodeList keyDescriptors = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < keyDescriptors.getLength(); i ++) {
            Node keyDescriptor = keyDescriptors.item(i);
            Element keyDescriptorEl = (Element) keyDescriptor;
            KeyInfo ki = processKeyDescriptor(keyDescriptorEl);
            if (ki != null) {
                String use = keyDescriptorEl.getAttribute(JBossSAMLConstants.USE.get());
                res.add(use, ki);
            }
        }
    } catch (SAXException | IOException | ParserConfigurationException | MarshalException | XPathExpressionException e) {
        throw new ParsingException("Error parsing SAML descriptor", e);
    }

    return res;
}
 
Example #10
Source File: SignatureVerifier.java    From IDES-Data-Preparation-Java with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
public KeySelectorResult select(KeyInfo keyInfo, KeySelector.Purpose purpose, 
		AlgorithmMethod method, XMLCryptoContext context) throws KeySelectorException {
	if (keyInfo == null)
		throw new KeySelectorException("Null KeyInfo");
	List<?> list = keyInfo.getContent();
	PublicKey pk = null;

	for (int i = 0; i < list.size(); i++) {
		XMLStructure xmlStructure = (XMLStructure) list.get(i);
		if (xmlStructure instanceof KeyValue) {
			try {
				pk = ((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);
					pk = cert.getPublicKey();
					break;
				}
			}
		}
	}
	if (pk != null) {
		final PublicKey retpk = pk;
		logger.debug("PublicKey from XML=" + pk);
		return new KeySelectorResult() {public Key getKey(){return retpk;}};
	}
	throw new KeySelectorException("Missing KeyValue");
}
 
Example #11
Source File: DOMXMLSignature.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a <code>DOMXMLSignature</code> from the specified components.
 *
 * @param si the <code>SignedInfo</code>
 * @param ki the <code>KeyInfo</code>, or <code>null</code> if not specified
 * @param objs a list of <code>XMLObject</code>s or <code>null</code>
 *  if not specified. The list is copied to protect against subsequent
 *  modification.
 * @param id an optional id (specify <code>null</code> to omit)
 * @param signatureValueId an optional id (specify <code>null</code> to
 *  omit)
 * @throws NullPointerException if <code>si</code> is <code>null</code>
 */
public DOMXMLSignature(SignedInfo si, KeyInfo ki,
                       List<? extends XMLObject> objs,
                       String id, String signatureValueId)
{
    if (si == null) {
        throw new NullPointerException("signedInfo cannot be null");
    }
    this.si = si;
    this.id = id;
    this.sv = new DOMSignatureValue(signatureValueId);
    if (objs == null) {
        this.objects = Collections.emptyList();
    } else {
        this.objects =
            Collections.unmodifiableList(new ArrayList<XMLObject>(objs));
        for (int i = 0, size = this.objects.size(); i < size; i++) {
            if (!(this.objects.get(i) instanceof XMLObject)) {
                throw new ClassCastException
                    ("objs["+i+"] is not an XMLObject");
            }
        }
    }
    this.ki = ki;
}
 
Example #12
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 #13
Source File: X509KeySelectorTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test()
public void select_wrong_structType() throws Exception {
    // given
    KeyInfo keyinfo = mock(KeyInfo.class);
    ArrayList<XMLStructure> list = new ArrayList<XMLStructure>();
    KeyName struct = mock(KeyName.class);
    list.add(struct);
    doReturn(list).when(keyinfo).getContent();

    // when
    try {
        selector.select(keyinfo, null, null, null);
        fail();
    } catch (KeySelectorException e) {
        assertTrue(e.getMessage().contains("No X509Data element found."));
    }
}
 
Example #14
Source File: XMLSignatureUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public KeySelectorResult select(KeyInfo keyInfo, KeySelector.Purpose purpose, AlgorithmMethod method, XMLCryptoContext context) throws KeySelectorException {
    try {
        KeyName keyNameEl = KeyInfoTools.getKeyName(keyInfo);
        this.keyName = keyNameEl == null ? null : keyNameEl.getName();
        final Key key = locator.getKey(keyName);
        this.keyLocated = key != null;
        return new KeySelectorResult() {
            @Override public Key getKey() {
                return key;
            }
        };
    } catch (KeyManagementException ex) {
        throw new KeySelectorException(ex);
    }

}
 
Example #15
Source File: X509KeySelectorTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test()
public void select_x509Data_noCertificate() throws Exception {
    // given
    KeyInfo keyinfo = mock(KeyInfo.class);
    ArrayList<XMLStructure> list = new ArrayList<XMLStructure>();
    X509Data x509Data = mock(X509Data.class);
    list.add(x509Data);
    doReturn(list).when(keyinfo).getContent();
    ArrayList<Object> x509DataContent = new ArrayList<Object>();
    x509DataContent.add(new String());
    doReturn(x509DataContent).when(x509Data).getContent();

    // when
    try {
        selector.select(keyinfo, null, null, null);
        fail();
    } catch (KeySelectorException e) {
        assertTrue(e.getMessage().contains("No X509Data element found."));
    }
}
 
Example #16
Source File: DOMKeyInfo.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }

    if (!(o instanceof KeyInfo)) {
        return false;
    }
    KeyInfo oki = (KeyInfo)o;

    boolean idsEqual = (id == null ? oki.getId() == null
                                   : id.equals(oki.getId()));

    return (keyInfoTypes.equals(oki.getContent()) && idsEqual);
}
 
Example #17
Source File: DOMXMLSignature.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a <code>DOMXMLSignature</code> from the specified components.
 *
 * @param si the <code>SignedInfo</code>
 * @param ki the <code>KeyInfo</code>, or <code>null</code> if not specified
 * @param objs a list of <code>XMLObject</code>s or <code>null</code>
 *  if not specified. The list is copied to protect against subsequent
 *  modification.
 * @param id an optional id (specify <code>null</code> to omit)
 * @param signatureValueId an optional id (specify <code>null</code> to
 *  omit)
 * @throws NullPointerException if <code>si</code> is <code>null</code>
 */
public DOMXMLSignature(SignedInfo si, KeyInfo ki,
                       List<? extends XMLObject> objs,
                       String id, String signatureValueId)
{
    if (si == null) {
        throw new NullPointerException("signedInfo cannot be null");
    }
    this.si = si;
    this.id = id;
    this.sv = new DOMSignatureValue(signatureValueId);
    if (objs == null) {
        this.objects = Collections.emptyList();
    } else {
        this.objects =
            Collections.unmodifiableList(new ArrayList<XMLObject>(objs));
        for (int i = 0, size = this.objects.size(); i < size; i++) {
            if (!(this.objects.get(i) instanceof XMLObject)) {
                throw new ClassCastException
                    ("objs["+i+"] is not an XMLObject");
            }
        }
    }
    this.ki = ki;
}
 
Example #18
Source File: DOMKeyInfo.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }

    if (!(o instanceof KeyInfo)) {
        return false;
    }
    KeyInfo oki = (KeyInfo)o;

    boolean idsEqual = (id == null ? oki.getId() == null
                                   : id.equals(oki.getId()));

    return (keyInfoTypes.equals(oki.getContent()) && idsEqual);
}
 
Example #19
Source File: X509KeySelectorTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test()
public void select_xmlStruct_empty() throws Exception {
    // given
    KeyInfo keyinfo = mock(KeyInfo.class);
    doReturn(new ArrayList<XMLStructure>()).when(keyinfo).getContent();

    // when
    try {
        selector.select(keyinfo, null, null, null);
        fail();
    } catch (KeySelectorException e) {
        assertTrue(e.getMessage().contains("No X509Data element found."));
    }
}
 
Example #20
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 #21
Source File: KeySelector.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public KeySelectorResult select(KeyInfo keyInfo, Purpose purpose,
    AlgorithmMethod method, XMLCryptoContext context)
    throws KeySelectorException {

    return new KeySelectorResult() {
        public Key getKey() {
            return key;
        }
    };
}
 
Example #22
Source File: KeySelector.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public KeySelectorResult select(KeyInfo keyInfo, Purpose purpose,
    AlgorithmMethod method, XMLCryptoContext context)
    throws KeySelectorException {

    return new KeySelectorResult() {
        public Key getKey() {
            return key;
        }
    };
}
 
Example #23
Source File: XMLDSigVerifier.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private XMLDsigVerificationResult validateCertificateIssuer(XMLSignature signature, XMLDsigVerificationResult result) {
    try
    {
        KeyInfo xmlKeyInfo = signature.getKeyInfo();
        List<X509Certificate> certList = getCertificateChainFromXML(xmlKeyInfo.getContent());
        List<X509Certificate> orderedCerts = reorderCertificateChain(certList);
        X509Certificate signingCert = selectSigningKeyFromXML(xmlKeyInfo.getContent());
        //Throws if invalid
        validateCertificateChain(orderedCerts);
        result.issuerPrincipal = signingCert.getIssuerX500Principal().getName();
        result.subjectPrincipal = signingCert.getSubjectX500Principal().getName();
        result.keyType = signingCert.getSigAlgName();
        for (Object o : xmlKeyInfo.getContent())
        {
            XMLStructure xmlStructure = (XMLStructure) o;
            if (xmlStructure instanceof KeyName)
            {
                result.keyName = ((KeyName) xmlStructure).getName();
            }
        }
    }
    catch(Exception e)
    {
        result.isValid = false;
        result.failureReason = e.getMessage();
    }
    return result;
}
 
Example #24
Source File: KeySelector.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public KeySelectorResult select(KeyInfo keyInfo, Purpose purpose,
    AlgorithmMethod method, XMLCryptoContext context)
    throws KeySelectorException {

    return new KeySelectorResult() {
        public Key getKey() {
            return key;
        }
    };
}
 
Example #25
Source File: KeySelector.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public KeySelectorResult select(KeyInfo keyInfo, Purpose purpose,
    AlgorithmMethod method, XMLCryptoContext context)
    throws KeySelectorException {

    return new KeySelectorResult() {
        public Key getKey() {
            return key;
        }
    };
}
 
Example #26
Source File: DefaultSAML2Validator.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Override
public KeySelectorResult select(KeyInfo keyInfo, KeySelector.Purpose purpose, AlgorithmMethod method,
        XMLCryptoContext context) throws KeySelectorException {

    if (keyInfo == null) {
        throw new KeySelectorException("Null KeyInfo object!");
    }
    SignatureMethod sm = (SignatureMethod) method;
    @SuppressWarnings("unchecked")
    List<XMLStructure> list = keyInfo.getContent();

    for (XMLStructure xmlStructure : list) {
        if (xmlStructure instanceof KeyValue) {
            PublicKey pk = null;
            try {
                pk = ((KeyValue) xmlStructure).getPublicKey();
            } catch (KeyException ke) {
                throw new KeySelectorException(ke);
            }
            // make sure algorithm is compatible with method
            if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
                return new SimpleKeySelectorResult(pk);
            }
        }
        if (xmlStructure instanceof X509Data) {
            X509Data xd = (X509Data) xmlStructure;
            @SuppressWarnings("unchecked")
            Iterator<Object> data = xd.getContent().iterator();
            for (; data.hasNext();) {
                Object o = data.next();
                if (o instanceof X509Certificate) {
                    X509Certificate cert = (X509Certificate) o;
                    return new SimpleKeySelectorResult(cert.getPublicKey());
                }
            }
        }
    }
    throw new KeySelectorException("No KeyValue element found!");
}
 
Example #27
Source File: KeySelector.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public KeySelectorResult select(KeyInfo keyInfo, Purpose purpose,
    AlgorithmMethod method, XMLCryptoContext context)
    throws KeySelectorException {

    return new KeySelectorResult() {
        public Key getKey() {
            return key;
        }
    };
}
 
Example #28
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 #29
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 #30
Source File: KeySelector.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public KeySelectorResult select(KeyInfo keyInfo, Purpose purpose,
    AlgorithmMethod method, XMLCryptoContext context)
    throws KeySelectorException {

    return new KeySelectorResult() {
        public Key getKey() {
            return key;
        }
    };
}