javax.xml.crypto.dsig.SignatureMethod Java Examples

The following examples show how to use javax.xml.crypto.dsig.SignatureMethod. 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: RequestSigner.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
private String fromAlg ( final String alg )
{
    if ( "DSA".equals ( alg ) )
    {
        return SignatureMethod.DSA_SHA1;
    }
    else if ( "RSA".equals ( alg ) )
    {
        return SignatureMethod.RSA_SHA1;
    }
    else if ( "HMAC".equals ( alg ) )
    {
        return SignatureMethod.HMAC_SHA1;
    }
    else
    {
        throw new IllegalArgumentException ( String.format ( "Key algorithm '%s' is not supported", alg ) );
    }
}
 
Example #5
Source File: X509KeySelector.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
static boolean algEquals ( final String algURI, final String algName )
{
    if ( algName.equalsIgnoreCase ( "DSA" ) && algURI.equalsIgnoreCase ( SignatureMethod.DSA_SHA1 ) )
    {
        return true;
    }
    else if ( algName.equalsIgnoreCase ( "RSA" ) && algURI.equalsIgnoreCase ( SignatureMethod.RSA_SHA1 ) )
    {
        return true;
    }
    else
    {
        logger.trace ( "Failed to check key - algUri: {}, algName: {}", algURI, algName );
        return false;
    }
}
 
Example #6
Source File: SignatureVerifier.java    From IDES-Data-Preparation-Java with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
protected String getAlgorithm(String dsigAlgo) throws Exception {
	if (DigestMethod.SHA512.equals(dsigAlgo))
		return "SHA-512";
	if (DigestMethod.SHA256.equals(dsigAlgo))
		return "SHA-256";
	if (DigestMethod.SHA1.equals(dsigAlgo))
		return "SHA-1";
	if ("http://www.w3.org/2001/04/xmldsig-more#rsa-sha512".equals(dsigAlgo))
		return "SHA512withRSA";
	if ("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256".equals(dsigAlgo))
		return "SHA256withRSA";
	if ("http://www.w3.org/2001/04/xmldsig-more#rsa-sha384".equals(dsigAlgo))
		return "SHA384withRSA";
	if (SignatureMethod.DSA_SHA1.equals(dsigAlgo))
		return "SHA1withDSA";
	if (SignatureMethod.RSA_SHA1.equals(dsigAlgo))
		return "SHA1withRSA";
	throw new Exception(dsigAlgo + " not spported");
}
 
Example #7
Source File: KeyValueKeySelector.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
static boolean algEquals ( final String algURI, final String algName )
{
    if ( algName.equalsIgnoreCase ( "DSA" ) && algURI.equalsIgnoreCase ( SignatureMethod.DSA_SHA1 ) )
    {
        return true;
    }
    else if ( algName.equalsIgnoreCase ( "RSA" ) && algURI.equalsIgnoreCase ( SignatureMethod.RSA_SHA1 ) )
    {
        return true;
    }
    else
    {
        logger.warn ( "Failed to check key - algUri: {}, algName: {}", algURI, algName );
        return false;
    }
}
 
Example #8
Source File: DigSigUtil.java    From juddi with Apache License 2.0 6 votes vote down vote up
private SignedInfo initSignedInfo(XMLSignatureFactory fac) throws Exception {
        Reference ref = initReference(fac);
        String cm = null;
        cm = map.getProperty(CANONICALIZATIONMETHOD);
        String sigmethod = null;
        sigmethod = map.getProperty(SIGNATURE_METHOD);
        if (sigmethod == null) {
                sigmethod = SignatureMethod.RSA_SHA1;
        }
        if (cm == null) {
                cm = CanonicalizationMethod.EXCLUSIVE;
        }
        SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(
                cm,
                (C14NMethodParameterSpec) null),
                fac.newSignatureMethod(sigmethod,
                        null), Collections.singletonList(ref));
        return si;
}
 
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: 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 #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_publicKey_exception() throws Exception {
    // given
    selector = spy(new X509KeySelector(keystore));
    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(mock(X509Certificate.class));
    doReturn(x509DataContent).when(x509Data).getContent();
    doThrow(new KeyStoreException("key exception")).when(selector)
            .getPublicKeyFromKeystore(any(X509Certificate.class),
                    any(SignatureMethod.class));

    // when
    try {
        selector.select(keyinfo, null, null, null);
        fail();
    } catch (KeySelectorException e) {
        assertTrue(e.getCause().getMessage().contains("key exception"));
    }
}
 
Example #14
Source File: X509KeySelector.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * Searches the specified keystore for a certificate that matches the
 * specified X509Certificate and contains a public key that is compatible
 * with the specified SignatureMethod.
 *
 * @return a KeySelectorResult containing the cert's public key if there
 *         is a match; otherwise null
 */
private KeySelectorResult certSelect(X509Certificate xcert,
                                     SignatureMethod sm) throws KeyStoreException {
    // skip non-signer certs
    boolean[] keyUsage = xcert.getKeyUsage();
    if (!keyUsage[0]) {
        return null;
    }
    String alias = ks.getCertificateAlias(xcert);
    if (alias != null) {
        PublicKey pk = ks.getCertificate(alias).getPublicKey();
        // make sure algorithm is compatible with method
        if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
            return new SimpleKeySelectorResult(pk);
        }
    }
    return null;
}
 
Example #15
Source File: SamlKeySelectorTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void algorithmCompatibleWithMethod_dsa() {
    // given
    SamlKeySelector keySelector = mock(SamlKeySelector.class,
            Mockito.CALLS_REAL_METHODS);

    // when
    boolean result = keySelector.algorithmCompatibleWithMethod(
            SignatureMethod.DSA_SHA1, keySelector.ALGORITHM_DSA);

    // then
    assertTrue(result);
}
 
Example #16
Source File: SamlKeySelector.java    From development with Apache License 2.0 5 votes vote down vote up
boolean algorithmCompatibleWithMethod(String signatureMethod,
                                      String algorithmName) {
    if (ALGORITHM_DSA.equalsIgnoreCase(algorithmName)) {
        if (SignatureMethod.DSA_SHA1.equalsIgnoreCase(signatureMethod)) {
            return true;
        }
    } else if (ALGORITHM_RSA.equalsIgnoreCase(algorithmName)) {
        if (SignatureMethod.RSA_SHA1.equalsIgnoreCase(signatureMethod)
                || SigningAlgorithmType.SHA256.getUri().equalsIgnoreCase(signatureMethod)) {
            return true;
        }
    }
    return false;
}
 
Example #17
Source File: X509KeySelector.java    From development with Apache License 2.0 5 votes vote down vote up
@Override
public KeySelectorResult select(KeyInfo keyInfo,
        KeySelector.Purpose purpose, AlgorithmMethod algorithmMethod,
        XMLCryptoContext context) throws KeySelectorException {

    if (keyInfo == null) {
        throw new KeySelectorException("Null KeyInfo object!");
    }

    @SuppressWarnings("unchecked")
    List<XMLStructure> list = keyInfo.getContent();
    for (XMLStructure xmlStructure : list) {
        if (xmlStructure instanceof X509Data) {
            X509Data x509Data = (X509Data) xmlStructure;
            @SuppressWarnings("rawtypes")
            List content = x509Data.getContent();
            for (int i = 0; i < content.size(); i++) {
                Object x509Content = content.get(i);
                if (x509Content instanceof X509Certificate) {
                    X509Certificate certificate = (X509Certificate) x509Content;
                    try {
                        return getPublicKeyFromKeystore(certificate,
                                (SignatureMethod) algorithmMethod);
                    } catch (KeyStoreException e) {
                        throw new KeySelectorException(e);
                    }
                }
            }
        }
    }

    throw new KeySelectorException("No X509Data element found.");
}
 
Example #18
Source File: X509KeySelector.java    From development with Apache License 2.0 5 votes vote down vote up
KeySelectorResult getPublicKeyFromKeystore(X509Certificate certificate,
        SignatureMethod signatureMethod) throws KeyStoreException,
        KeySelectorException {

    isSigningCertificate(certificate);
    return searchInKeystore(certificate, signatureMethod);
}
 
Example #19
Source File: X509KeySelector.java    From development with Apache License 2.0 5 votes vote down vote up
KeySelectorResult searchInKeystore(X509Certificate certificate,
        SignatureMethod signatureMethod) throws KeyStoreException,
        KeySelectorException {
    String alias = keystore.getCertificateAlias(certificate);
    if (alias != null) {
        PublicKey pk = keystore.getCertificate(alias).getPublicKey();
        if (algorithmCompatibleWithMethod(signatureMethod.getAlgorithm(),
                pk.getAlgorithm())) {
            return new SimpleKeySelectorResult(pk);
        }
    }
    throw new KeySelectorException(
            "X509 content is not a signing certificate");
}
 
Example #20
Source File: SamlKeySelectorTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void algorithmCompatibleWithMethod_wrongAlgorithm() {
    // given
    SamlKeySelector keySelector = mock(SamlKeySelector.class,
            Mockito.CALLS_REAL_METHODS);

    // when
    boolean result = keySelector.algorithmCompatibleWithMethod(
            SignatureMethod.RSA_SHA1, "wrong algorithm");

    // then
    assertFalse(result);
}
 
Example #21
Source File: SamlKeySelectorTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void algorithmCompatibleWithMethod_rsa() {
    // given
    SamlKeySelector keySelector = mock(SamlKeySelector.class,
            Mockito.CALLS_REAL_METHODS);

    // when
    boolean result = keySelector.algorithmCompatibleWithMethod(
            SignatureMethod.RSA_SHA1, keySelector.ALGORITHM_RSA);

    // then
    assertTrue(result);
}
 
Example #22
Source File: AbstractDOMSignatureMethod.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean equals(Object o)
{
    if (this == o) {
        return true;
    }

    if (!(o instanceof SignatureMethod)) {
        return false;
    }
    SignatureMethod osm = (SignatureMethod)o;

    return (getAlgorithm().equals(osm.getAlgorithm()) &&
        paramsEqual(osm.getParameterSpec()));
}
 
Example #23
Source File: X509KeySelector.java    From SAMLRaider with MIT License 5 votes vote down vote up
static boolean algEquals(String algURI, String algName) {
    if ((algName.equalsIgnoreCase("DSA") &&
        algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) ||
        (algName.equalsIgnoreCase("RSA") &&
        algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) ||
        (algName.equalsIgnoreCase("RSA") &&
        algURI.equalsIgnoreCase(XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256))){
        return true;
    } else {
        return false;
    }
}
 
Example #24
Source File: AbstractDOMSignatureMethod.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean equals(Object o)
{
    if (this == o) {
        return true;
    }

    if (!(o instanceof SignatureMethod)) {
        return false;
    }
    SignatureMethod osm = (SignatureMethod)o;

    return (getAlgorithm().equals(osm.getAlgorithm()) &&
        paramsEqual(osm.getParameterSpec()));
}
 
Example #25
Source File: AbstractDOMSignatureMethod.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean equals(Object o)
{
    if (this == o) {
        return true;
    }

    if (!(o instanceof SignatureMethod)) {
        return false;
    }
    SignatureMethod osm = (SignatureMethod)o;

    return (getAlgorithm().equals(osm.getAlgorithm()) &&
        paramsEqual(osm.getParameterSpec()));
}
 
Example #26
Source File: XmlSignatureApplet.java    From juddi with Apache License 2.0 5 votes vote down vote up
private SignedInfo initSignedInfo(XMLSignatureFactory fac) throws Exception {
    Reference ref = initReference(fac);
    SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
            (C14NMethodParameterSpec) null),
            fac.newSignatureMethod(SignatureMethod.RSA_SHA1,
            null),
            Collections.singletonList(ref));
    return si;
}
 
Example #27
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 #28
Source File: XMLSignatureUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static void signImpl(DOMSignContext dsc, String digestMethod, String signatureMethod, String referenceURI, String keyName, PublicKey publicKey,
                             X509Certificate x509Certificate, String canonicalizationMethodType)
        throws GeneralSecurityException, MarshalException, XMLSignatureException {
    dsc.setDefaultNamespacePrefix("dsig");

    DigestMethod digestMethodObj = fac.newDigestMethod(digestMethod, null);
    Transform transform1 = fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
    Transform transform2 = fac.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (TransformParameterSpec) null);

    List<Transform> transformList = new ArrayList<>();
    transformList.add(transform1);
    transformList.add(transform2);

    Reference ref = fac.newReference(referenceURI, digestMethodObj, transformList, null, null);

    CanonicalizationMethod canonicalizationMethod = fac.newCanonicalizationMethod(canonicalizationMethodType,
            (C14NMethodParameterSpec) null);

    List<Reference> referenceList = Collections.singletonList(ref);
    SignatureMethod signatureMethodObj = fac.newSignatureMethod(signatureMethod, null);
    SignedInfo si = fac.newSignedInfo(canonicalizationMethod, signatureMethodObj, referenceList);

    KeyInfo ki;
    if (includeKeyInfoInSignature) {
        ki = createKeyInfo(keyName, publicKey, x509Certificate);
    } else {
        ki = createKeyInfo(keyName, null, null);
    }
    XMLSignature signature = fac.newXMLSignature(si, ki);

    signature.sign(dsc);
}
 
Example #29
Source File: X509KeySelector.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an OID of a public-key algorithm compatible with the specified
 * signature algorithm URI.
 * @param algURI The base uri of the algorithm the key was made with
 * @return String A reference OID for the algorithim used to sign.
 */
private String getPKAlgorithmOID(String algURI) {
    if (algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) {
        return "1.2.840.10040.4.1";
    } else if (algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) {
        return "1.2.840.113549.1.1";
    } else {
        return null;
    }
}
 
Example #30
Source File: X509KeySelector.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if a JCA/JCE public key algorithm name is compatible with
 * the specified signature algorithm URI.
 * @param algName
 *               The name of the Algorithm. "SHA1"
 * @param algURI
 *               The URI that specifies the algorithm.
 *
 */
//@@@FIXME: this should also work for key types other than DSA/RSA
private boolean algEquals(String algURI, String algName) {
    if (algName.equalsIgnoreCase("DSA")
            && algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) {
        return true;
    }
    if (algName.equalsIgnoreCase("RSA")
            && algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) {
        return true;
    }
    return false;
}