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; } }
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; } }
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 ) ); } }
@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")); } }
private String getSignatureMethod(DigestAlgo digestAlgo) { if (null == digestAlgo) { throw new RuntimeException("digest algo is null"); } switch (digestAlgo) { case SHA1: return SignatureMethod.RSA_SHA1; case SHA256: return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256; case SHA512: return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512; } // TODO: complete me // if ("SHA-384".equals(digestAlgo)) { // return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384; // } // if ("RIPEMD160".equals(digestAlgo)) { // return XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160; // } throw new RuntimeException("unsupported sign algo: " + digestAlgo); }
private String getSignatureMethod(String digestAlgo) { if (null == digestAlgo) { throw new RuntimeException("digest algo is null"); } if ("SHA-1".equals(digestAlgo)) { return SignatureMethod.RSA_SHA1; } if ("SHA-256".equals(digestAlgo)) { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256; } if ("SHA-512".equals(digestAlgo)) { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512; } if ("SHA-384".equals(digestAlgo)) { return XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384; } if ("RIPEMD160".equals(digestAlgo)) { return XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160; } throw new RuntimeException("unsupported sign algo: " + digestAlgo); }
@Test public void validate_dsa_publicKey() throws Exception { // given XMLSignatureBuilder builder = new XMLSignatureBuilder( SignatureMethod.DSA_SHA1); KeyPair keyPair = generateKeyPair("DSA"); FileInputStream in = null; Document document = null; try { in = new FileInputStream(FILE_UNSIGNED_ASSERTION); document = builder.sign(in, keyPair); } finally { if (in != null) { in.close(); } } NodeList nl = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); // when boolean valid = validator.validate(nl.item(0), keyPair.getPublic()); // then assertTrue(valid); }
@Test public void validate_dsa_keySelector() throws Exception { // given XMLSignatureBuilder builder = new XMLSignatureBuilder( SignatureMethod.DSA_SHA1); KeyPair keyPair = generateKeyPair("DSA"); FileInputStream in = null; Document document = null; try { in = new FileInputStream(FILE_UNSIGNED_ASSERTION); document = builder.sign(in, keyPair); } finally { if (in != null) { in.close(); } } NodeList nl = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); // when boolean valid = validator.validate(nl.item(0)); // then assertTrue(valid); }
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; }
/** * Test signing a message body using a symmetric key with EncryptedKeySHA1 */ public void testSymmetricSignatureSHA1() throws Exception { SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope(); Document doc = unsignedEnvelope.getAsDocument(); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); WSSecSignature sign = new WSSecSignature(); sign.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER); sign.setSecretKey(keyData); sign.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1); Document signedDoc = sign.build(doc, crypto, secHeader); if (LOG.isDebugEnabled()) { LOG.debug("Signed symmetric message SHA1:"); String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc); LOG.debug(outputString); } verify(signedDoc); }
/** * 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; }
public XmlSignatureHandler() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { this.builderFactory = DocumentBuilderFactory.newInstance(); this.builderFactory.setNamespaceAware(true); this.transformerFactory = TransformerFactory.newInstance(); this.signatureFactory = XMLSignatureFactory.getInstance("DOM"); this.digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null); this.transformList = new ArrayList<Transform>(2); this.transformList.add( signatureFactory.newTransform( Transform.ENVELOPED, (TransformParameterSpec) null)); this.transformList.add( signatureFactory.newTransform( "http://www.w3.org/TR/2001/REC-xml-c14n-20010315", (TransformParameterSpec) null)); this.canonicalizationMethod = this.signatureFactory.newCanonicalizationMethod( CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null); this.signatureMethod = this.signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); this.keyInfoFactory = this.signatureFactory.getKeyInfoFactory(); }
/** * Sign SAML element. * * @param element the element * @param privKey the priv key * @param pubKey the pub key * @return the element */ private static org.jdom.Element signSamlElement(final org.jdom.Element element, final PrivateKey privKey, final PublicKey pubKey) { try { final String providerName = System.getProperty("jsr105Provider", SIGNATURE_FACTORY_PROVIDER_CLASS); final XMLSignatureFactory sigFactory = XMLSignatureFactory .getInstance("DOM", (Provider) Class.forName(providerName).newInstance()); final List<Transform> envelopedTransform = Collections.singletonList(sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); final Reference ref = sigFactory.newReference(StringUtils.EMPTY, sigFactory .newDigestMethod(DigestMethod.SHA1, null), envelopedTransform, null, null); // Create the SignatureMethod based on the type of key final SignatureMethod signatureMethod; final String algorithm = pubKey.getAlgorithm(); switch (algorithm) { case "DSA": signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null); break; case "RSA": signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); break; default: throw new RuntimeException("Error signing SAML element: Unsupported type of key"); } final CanonicalizationMethod canonicalizationMethod = sigFactory .newCanonicalizationMethod( CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); // Create the SignedInfo final SignedInfo signedInfo = sigFactory.newSignedInfo( canonicalizationMethod, signatureMethod, Collections.singletonList(ref)); // Create a KeyValue containing the DSA or RSA PublicKey final KeyInfoFactory keyInfoFactory = sigFactory.getKeyInfoFactory(); final KeyValue keyValuePair = keyInfoFactory.newKeyValue(pubKey); // Create a KeyInfo and add the KeyValue to it final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyValuePair)); // Convert the JDOM document to w3c (Java XML signature API requires w3c representation) final Element w3cElement = toDom(element); // Create a DOMSignContext and specify the DSA/RSA PrivateKey and // location of the resulting XMLSignature's parent element final DOMSignContext dsc = new DOMSignContext(privKey, w3cElement); final Node xmlSigInsertionPoint = getXmlSignatureInsertLocation(w3cElement); dsc.setNextSibling(xmlSigInsertionPoint); // Marshal, generate (and sign) the enveloped signature final XMLSignature signature = sigFactory.newXMLSignature(signedInfo, keyInfo); signature.sign(dsc); return toJdom(w3cElement); } catch (final Exception e) { throw new RuntimeException("Error signing SAML element: " + e.getMessage(), e); } }
@Override public KeySelectorResult select ( final KeyInfo keyInfo, final KeySelector.Purpose purpose, final AlgorithmMethod method, final XMLCryptoContext context ) throws KeySelectorException { if ( keyInfo == null ) { throw new KeySelectorException ( "Null KeyInfo object!" ); } final SignatureMethod sm = (SignatureMethod)method; final List<?> list = keyInfo.getContent (); for ( int i = 0; i < list.size (); i++ ) { final XMLStructure xmlStructure = (XMLStructure)list.get ( i ); if ( xmlStructure instanceof KeyValue ) { try { final PublicKey pk = ( (KeyValue)xmlStructure ).getPublicKey (); // make sure algorithm is compatible with method if ( algEquals ( sm.getAlgorithm (), pk.getAlgorithm () ) ) { return new SimpleKeySelectorResult ( pk ); } } catch ( final KeyException ke ) { throw new KeySelectorException ( ke ); } } } throw new KeySelectorException ( "No KeyValue element found!" ); }
@Override public KeySelectorResult select ( final KeyInfo keyInfo, final KeySelector.Purpose purpose, final AlgorithmMethod method, final XMLCryptoContext context ) throws KeySelectorException { if ( keyInfo == null ) { throw new KeySelectorException ( "Null KeyInfo object!" ); } final SignatureMethod sm = (SignatureMethod)method; final List<?> list = keyInfo.getContent (); for ( final Object l : list ) { final XMLStructure xmlStructure = (XMLStructure)l; if ( xmlStructure instanceof X509Data ) { for ( final Object o : ( (X509Data)xmlStructure ).getContent () ) { KeySelectorResult result = null; if ( o instanceof X509Certificate ) { result = findPublicKey ( (X509Certificate)o, sm ); } if ( result != null ) { return result; } } } } throw new KeySelectorException ( "No KeyValue element found!" ); }
synchronized void sign ( final Key privateKey, final PublicKey publicKey, final Certificate cert, final Document doc ) throws Exception { final DOMSignContext dsc = new DOMSignContext ( privateKey, doc.getDocumentElement () ); final SignatureMethod sm = this.fac.newSignatureMethod ( fromAlg ( privateKey.getAlgorithm () ), null ); final SignedInfo si = this.fac.newSignedInfo ( this.cm, sm, Collections.singletonList ( this.ref ) ); final List<Object> data = new LinkedList<Object> (); if ( cert != null ) { data.add ( this.kif.newKeyValue ( cert.getPublicKey () ) ); data.add ( this.kif.newX509Data ( Collections.singletonList ( cert ) ) ); } else { data.add ( this.kif.newKeyValue ( publicKey ) ); } final KeyInfo ki = this.kif.newKeyInfo ( data ); final XMLSignature signature = this.fac.newXMLSignature ( si, ki ); // finally sign signature.sign ( dsc ); }
@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); }
@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); }
@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); }
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; }
@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."); }
KeySelectorResult getPublicKeyFromKeystore(X509Certificate certificate, SignatureMethod signatureMethod) throws KeyStoreException, KeySelectorException { isSigningCertificate(certificate); return searchInKeystore(certificate, signatureMethod); }
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"); }
@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())); }
@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()); }
private void test_create_signature_enveloping( SignatureMethod sm, DigestMethod dm, KeyInfo ki, Key signingKey, KeySelector ks ) throws Exception { // create reference Reference ref = fac.newReference("#DSig.Object_1", dm, null, XMLObject.TYPE, null); // create SignedInfo SignedInfo si = fac.newSignedInfo(withoutComments, sm, Collections.singletonList(ref)); Document doc = db.newDocument(); // create Objects Element webElem = doc.createElementNS(null, "Web"); Text text = doc.createTextNode("up up and away"); webElem.appendChild(text); XMLObject obj = fac.newXMLObject(Collections.singletonList (new DOMStructure(webElem)), "DSig.Object_1", "text/xml", null); // create XMLSignature XMLSignature sig = fac.newXMLSignature (si, ki, Collections.singletonList(obj), null, null); DOMSignContext dsc = new DOMSignContext(signingKey, doc); dsc.setDefaultNamespacePrefix("dsig"); sig.sign(dsc); TestUtils.validateSecurityOrEncryptionElement(doc.getDocumentElement()); // XMLUtils.outputDOM(doc.getDocumentElement(), System.out); DOMValidateContext dvc = new DOMValidateContext (ks, doc.getDocumentElement()); XMLSignature sig2 = fac.unmarshalXMLSignature(dvc); assertTrue(sig.equals(sig2)); assertTrue(sig2.validate(dvc)); }
public String assinarDocumento(final String conteudoXml) throws Exception { final KeyStore keyStore = KeyStore.getInstance("PKCS12"); try (InputStream certificadoStream = new ByteArrayInputStream(this.config.getCertificado())) { keyStore.load(certificadoStream, this.config.getCertificadoSenha().toCharArray()); } final KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(keyStore.aliases().nextElement(), new KeyStore.PasswordProtection(this.config.getCertificadoSenha().toCharArray())); final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM"); final List<Transform> transforms = new ArrayList<>(2); transforms.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); transforms.add(signatureFactory.newTransform(AssinaturaDigital.C14N_TRANSFORM_METHOD, (TransformParameterSpec) null)); final KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory(); final X509Data x509Data = keyInfoFactory.newX509Data(Collections.singletonList((X509Certificate) keyEntry.getCertificate())); final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data)); final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); try (StringReader stringReader = new StringReader(conteudoXml)) { final Document document = documentBuilderFactory.newDocumentBuilder().parse(new InputSource(stringReader)); for (final String elementoAssinavel : AssinaturaDigital.ELEMENTOS_ASSINAVEIS) { final NodeList elements = document.getElementsByTagName(elementoAssinavel); for (int i = 0; i < elements.getLength(); i++) { final Element element = (Element) elements.item(i); final String id = element.getAttribute("Id"); element.setIdAttribute("Id", true); final Reference reference = signatureFactory.newReference("#" + id, signatureFactory.newDigestMethod(DigestMethod.SHA1, null), transforms, null, null); final SignedInfo signedInfo = signatureFactory.newSignedInfo(signatureFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference)); final XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, keyInfo); signature.sign(new DOMSignContext(keyEntry.getPrivateKey(), element.getParentNode())); } } return this.converteDocumentParaXml(document); } }
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("rawtypes") List list = keyInfo.getContent(); for (int i = 0; i < list.size(); i++) { XMLStructure xmlStructure = (XMLStructure) list.get(i); 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); } } } throw new KeySelectorException("No KeyValue element found!"); }
@Test public void testJsr105ReferenceUri() throws Exception { String uri = FilenameUtils.getName(new File("foo bar.txt").toURI().toURL().getFile()); KeyPair keyPair = generateKeyPair(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI()); XMLSignContext signContext = new DOMSignContext(keyPair.getPrivate(), document); byte[] externalDocument = "hello world".getBytes(); MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(externalDocument); byte[] documentDigestValue = messageDigest.digest(); DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null); Reference reference = signatureFactory.newReference(uri, digestMethod, null, null, null, documentDigestValue); SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod( CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); javax.xml.crypto.dsig.SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference)); javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, null); xmlSignature.sign(signContext); }