Examples of XMLSignatureFactory


Examples of javax.xml.crypto.dsig.XMLSignatureFactory

    // Step 1: Load an XMLSignatureFactory instance. This factory class will
    // be responsible for constructing almost all the major objects we need
    // in working with XML Signature in JSR-105 APIs, except those related
    // to KeyInfo.
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    // Step 3 : Find all Xml Signature element into the provided XML
    // document (here for sample use only the first)
    NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
      throw new Exception("Cannot find Signature element!");
    }

    // Step 4: Create a DOMValidateContext instance (extract public key from
    // the "KeyInfo" bloc using overrided KeySelector impl.)
    DOMValidateContext valContext = new DOMValidateContext(new KeyValueKeySelector(), nl.item(0));

    // Step 5: Unmarshal the Signature node into an XMLSiganture object.
    XMLSignature signature = fac.unmarshalXMLSignature(valContext);

    // Step 6 : Validate signature
    boolean isValid = signature.validate(valContext);
    if (isValid) {
      System.out.println("OK");
View Full Code Here

Examples of javax.xml.crypto.dsig.XMLSignatureFactory

    // Step 1: Load an XMLSignatureFactory instance. This factory class will
    // be responsible for constructing almost all the major objects we need
    // in working with XML Signature in JSR-105 APIs, except those related
    // to KeyInfo.
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    // Step 2: Decide on a digest method and create the reference object. We
    // use the XMLSignatureFactory instance created in the first step to
    // create both the DigestMethod and Reference objects.
    Reference ref = fac.newReference("#invoice", fac.newDigestMethod(DigestMethod.SHA256, null));

    // Step 3: Load invoice.xml and wrap it in an XMLObject object. Not all
    // signature generation processes require this step. XMLObject in
    // JSR-105 models the optional Object element we briefly discussed
    // before.
    Document XML = dbf.newDocumentBuilder().parse(new File(XML_SOURCE));
    Node invoice = XML.getDocumentElement();
    XMLStructure content = new DOMStructure(invoice);
    XMLObject obj = fac.newXMLObject(Collections.singletonList(content), "invoice", null, null);

    // Step 4: Create the SignedInfo object.
    SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null),
        fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));

    // Step 5 : Retrieve private and public key from keystore
    KeyPair kp = KeyStoreUtil.getKeyPair(KEYSTORE, KEYSTORE_PASSWORD, PRIVATE_KEY_ALIAS_PASSWORD, PRIVATE_KEY_ALIAS);

    // Step 6: Create a KeyInfo object. This step is optional, just as
    // KeyInfo as an element in Signature element is optional.
    KeyInfoFactory kif = fac.getKeyInfoFactory();
    KeyValue kv = kif.newKeyValue(kp.getPublic());
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));

    // Step 7: Create an XMLSignature object. In JSR-105, the XMLSignature
    // interface models the Signature element of the W3C recommendation.
    XMLSignature signature = fac.newXMLSignature(si, ki, Collections.singletonList(obj), null, null);

    // Step 8: Instantiate a DOMSignContext object, and register the private
    // key with it. The XMLSignContext interface (which DOMSignContext
    // implements) contains context information for generating XML
    // signatures.
View Full Code Here

Examples of javax.xml.crypto.dsig.XMLSignatureFactory

   * @throws Exception
   */
  private static void GenerateXmlSignatureFile() throws Exception {
    // Step 1 : Create a DOM XMLSignatureFactory that will be used to
    // generate the enveloped signature.
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    // Step 2 : Create a Reference to a remote PDF file
    // and also specify the SHA256 digest algorithm
    Reference ref = fac.newReference("http://www.actstudent.org/plan/pdf/sample.pdf", fac.newDigestMethod(DigestMethod.SHA256, null));

    // Step 3 : Create the SignedInfo.
    SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null),
        fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));

    // Step 4 : Create the Document that will hold the resulting
    // XMLSignature
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true); // must be set
    Document doc = dbf.newDocumentBuilder().newDocument();

    // Step 5a : Retrieve private and public key from keystore
    KeyPair kp = KeyStoreUtil.getKeyPair(KEYSTORE, KEYSTORE_PASSWORD, PRIVATE_KEY_ALIAS_PASSWORD, PRIVATE_KEY_ALIAS);

    // Step 5b: Create a KeyInfo object. This step is optional, just as
    // KeyInfo as an element in Signature element is optional.
    KeyInfoFactory kif = fac.getKeyInfoFactory();
    KeyValue kv = kif.newKeyValue(kp.getPublic());
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));

    // Step 5c : Create a DOMSignContext and specify the DSA PrivateKey and
    // location of the resulting XMLSignature's parent element.
    DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc);

    // Step 6 : Create the XMLSignature, but don't sign it yet.
    XMLSignature signature = fac.newXMLSignature(si, ki);

    // Step 7 : Marshal, generate, and sign the enveloped signature.
    signature.sign(dsc);

    // Final step : Save XML Signature to a XML file
View Full Code Here

Examples of javax.xml.crypto.dsig.XMLSignatureFactory

   * @throws Exception
   */
  private static void GenerateXmlSignatureFile() throws Exception {
    // Step 1 : Create a DOM XMLSignatureFactory that will be used to
    // generate the enveloped signature.
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    // Step 2 : Create a Reference to the enveloped document (in this case,
    // you are signing the whole document, so a URI of "" signifies
    // that, and also specify the SHA256 digest algorithm and
    // the ENVELOPED Transform.
    Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA256, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null,
        null);

    // Step 3 : Create the SignedInfo.
    SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null),
        Collections.singletonList(ref));

    // Step 4 : Instantiate the document to be signed.
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().parse(new FileInputStream(XML_SOURCE));

    // Step 5a : Retrieve private and public key from keystore
    KeyPair kp = KeyStoreUtil.getKeyPair(KEYSTORE, KEYSTORE_PASSWORD, PRIVATE_KEY_ALIAS_PASSWORD, PRIVATE_KEY_ALIAS);

    // Step 5b: Create a KeyInfo object. This step is optional, just as
    // KeyInfo as an element in Signature element is optional.
    KeyInfoFactory kif = fac.getKeyInfoFactory();
    KeyValue kv = kif.newKeyValue(kp.getPublic());
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));

    // Step 5c : Create a DOMSignContext and specify the DSA PrivateKey and
    // location of the resulting XMLSignature's parent element.
    DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement());

    // Step 6 : Create the XMLSignature, but don't sign it yet.
    XMLSignature signature = fac.newXMLSignature(si, ki);

    // Step 7 : Marshal, generate, and sign the enveloped signature.
    signature.sign(dsc);

    // Final step : Save XML Signature to a XML file
View Full Code Here

Examples of javax.xml.crypto.dsig.XMLSignatureFactory

    private SignedInfo generateSignedInfo(FilterProcessingContext fpContext)
    throws PolicyGenerationException,NoSuchAlgorithmException,InvalidAlgorithmParameterException ,XWSSecurityException{
        SignaturePolicy signaturePolicy = (SignaturePolicy) fpContext.getSecurityPolicy();
        SignaturePolicy.FeatureBinding featureBinding = (SignaturePolicy.FeatureBinding)signaturePolicy.getFeatureBinding();
        MLSPolicy keyBinding = signaturePolicy.getKeyBinding();
        XMLSignatureFactory signatureFactory = getSignatureFactory();
        SecurableSoapMessage secureMessage = fpContext.getSecurableSoapMessage();
        String canonicalAlgo = featureBinding.getCanonicalizationAlgorithm();
        boolean disableInclusivePrefix = featureBinding.getDisableInclusivePrefix();
        //String digestAlgo = featureBinding.getDigestAlgorithm();
        ArrayList targetList = featureBinding.getTargetBindings();
        String keyAlgo = null;
        String algo = MessageConstants.RSA_SHA1;
        if (fpContext.getAlgorithmSuite() != null) {
            algo = fpContext.getAlgorithmSuite().getSignatureAlgorithm();
        }

        keyAlgo = SecurityUtil.getKeyAlgo(algo);
               
        if(PolicyTypeUtil.x509CertificateBinding(keyBinding)) {
            AuthenticationTokenPolicy.X509CertificateBinding certificateBinding =
                    (AuthenticationTokenPolicy.X509CertificateBinding)keyBinding;
            if (!"".equals(certificateBinding.getKeyAlgorithm())) {
                keyAlgo = certificateBinding.getKeyAlgorithm();
            }
        } else if (PolicyTypeUtil.samlTokenPolicy(keyBinding)) {
            AuthenticationTokenPolicy.SAMLAssertionBinding samlBinding =
                    (AuthenticationTokenPolicy.SAMLAssertionBinding)keyBinding;
            if (!"".equals(samlBinding.getKeyAlgorithm())) {
                keyAlgo = samlBinding.getKeyAlgorithm();
            }
        }else if(PolicyTypeUtil.symmetricKeyBinding(keyBinding)){
            SymmetricKeyBinding symmetricKeybinding = (SymmetricKeyBinding)keyBinding;
            if (!"".equals(symmetricKeybinding.getKeyAlgorithm())) {
                keyAlgo = symmetricKeybinding.getKeyAlgorithm();
            } else {
                keyAlgo = MessageConstants.HMAC_SHA1_SIGMETHOD;
            }    
        } else if (PolicyTypeUtil.secureConversationTokenKeyBinding(keyBinding)) {
            keyAlgo = MessageConstants.HMAC_SHA1_SIGMETHOD;
        } else if (PolicyTypeUtil.derivedTokenKeyBinding(keyBinding)) {
           keyAlgo = MessageConstants.HMAC_SHA1_SIGMETHOD;
           if(PolicyTypeUtil.issuedTokenKeyBinding(((DerivedTokenKeyBinding)keyBinding).getOriginalKeyBinding())){
               if(fpContext.getTrustContext().getProofKey() == null){
                   keyAlgo = MessageConstants.RSA_SHA1_SIGMETHOD;
               }                          
           }
       } else if (PolicyTypeUtil.issuedTokenKeyBinding(keyBinding)) {
           //TODO: verify if this is always correct
           keyAlgo = MessageConstants.HMAC_SHA1_SIGMETHOD;
           if(fpContext.getTrustContext().getProofKey() == null){
               keyAlgo = MessageConstants.RSA_SHA1_SIGMETHOD;
           }
       } else {
            logger.log(Level.SEVERE, LogStringsMessages.WSS_1335_UNSUPPORTED_KEYBINDING_SIGNATUREPOLICY());
            throw new XWSSecurityException("Unsupported KeyBinding for SignaturePolicy");
       }
       
        C14NMethodParameterSpec spec = null;
        if (MessageConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS.equalsIgnoreCase(canonicalAlgo)) {
            //List inc = getInclusiveNamespacePrefixes(secureMessage.findSecurityHeader(), false);
            //spec = new ExcC14NParameterSpec(inc);
            //NOTE: looking at BSP flag on sending side just for
            //ExC14N parameterList. Because XWSS11(xmlsec.jar) cannot
            //process the PrefixList, thereby breaking BC
            if (featureBinding.isBSP() || !disableInclusivePrefix) {
                List inc = getInclusiveNamespacePrefixes(secureMessage.findSecurityHeader(), false);
                spec = new ExcC14NParameterSpec(inc);
            } else {
                spec = null;
            }

        }
        CanonicalizationMethod canonicalMethod=
                signatureFactory.newCanonicalizationMethod(canonicalAlgo,spec);
       
        SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(keyAlgo, null);
        //Note : Signature algorithm parameters null for now , fix me.
        SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalMethod,signatureMethod,
                generateReferenceList(targetList,signatureFactory,secureMessage,fpContext,false, featureBinding.isEndorsingSignature()),null);
        //Note : Id is now null , check ?,
        return signedInfo;
    }
View Full Code Here

Examples of javax.xml.crypto.dsig.XMLSignatureFactory

    }
   
    public List generateReferenceList(List targetList,SecurableSoapMessage secureMessage,FilterProcessingContext fpContext,
            boolean verify, boolean isEndorsing)
    throws PolicyGenerationException,NoSuchAlgorithmException,InvalidAlgorithmParameterException,XWSSecurityException {
        XMLSignatureFactory factory = getSignatureFactory();
        return generateReferenceList(targetList,factory,secureMessage,fpContext,verify, isEndorsing);
    }
View Full Code Here

Examples of javax.xml.crypto.dsig.XMLSignatureFactory

                        localName));
                context.isPrimaryPolicyViolation(true);
                return 0;
            }
            DOMValidateContext validationContext = new DOMValidateContext(KeySelectorImpl.getInstance(), signElement);
            XMLSignatureFactory signatureFactory = WSSPolicyConsumerImpl.getInstance().getSignatureFactory();
            // unmarshal the XMLSignature
            XMLSignature signature = signatureFactory.unmarshalXMLSignature(validationContext);
            verifySignatureAlgorithm(signature);
           
            //For SignatureConfirmation
            List scList = (ArrayList)context.getExtraneousProperty("receivedSignValues");
            if(scList != null){
View Full Code Here

Examples of javax.xml.crypto.dsig.XMLSignatureFactory

        try {
           
           
            DOMValidateContext validationContext =
                    new DOMValidateContext(KeySelectorImpl.getInstance(), signElement);
            XMLSignatureFactory signatureFactory = WSSPolicyConsumerImpl.getInstance().getSignatureFactory();
            // unmarshal the XMLSignature
            XMLSignature signature = signatureFactory.unmarshalXMLSignature(validationContext);
            validationContext.setURIDereferencer(DSigResolver.getInstance());
            // Validate the XMLSignature (generated above)
            validationContext.put(MessageConstants.WSS_PROCESSING_CONTEXT, context);
            boolean coreValidity = signature.validate(validationContext);
            if (coreValidity == false){
View Full Code Here

Examples of javax.xml.crypto.dsig.XMLSignatureFactory

        }
        setupCertificates();
    }

    private XMLSignatureFactory initXMLSigFactory() {
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance();
        return fac;
    }
View Full Code Here

Examples of javax.xml.crypto.dsig.XMLSignatureFactory

     * XML digital signature namespace
     */
    public final static String XML_DIGSIG_NS = "http://www.w3.org/2000/09/xmldsig#";

    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);
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.