简体   繁体   中英

Java WebService call with authentication

I'm working on webservice client which requires authentication and xml signing. I've read a lot of articles but it looks like my one looks different.

I need to send a request containing tag with some certificate details. I received from Service provider few files (certificate.crt , certificate.p12 , certificate.pem)

I managed to attach crt file into request using follString providerName =

System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");

        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance());

        Reference ref = fac.newReference("", fac.newDigestMethod(
                DigestMethod.SHA1, null), Collections.singletonList(fac
                .newTransform(Transform.ENVELOPED, (XMLStructure) null)), null,
                null);

        // Create the SignedInfo
        SignedInfo si = fac.newSignedInfo(
                fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null),
                fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(512);
        KeyPair kp = kpg.generateKeyPair();

        KeyInfoFactory kif = fac.getKeyInfoFactory();
        KeyValue kv = kif.newKeyValue(kp.getPublic());

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate cert = cf.generateCertificate(new FileInputStream(new File("certificate.crt")));

        X509Data x509d = kif.newX509Data(Collections.singletonList(cert));
        KeyInfo ki = kif.newKeyInfo(Arrays.asList(x509d, kv));

        Document doc = (Document) result.getNode();

        DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc.getDocumentElement());

        XMLSignature signature = fac.newXMLSignature(si, ki);
        signature.sign(dsc);

But RSA key is generated and different each call. It is obvious because I'm using KeyPairGenerator. Is it possible to import my private key from P12 file instead?

When I run this application on tomcat do I need to configure it somehow to enable the HTTPS calls to the service?

You can use KeySotre

Load the file:

KeyStore ks = KeyStore.getInstance("PKCS12");
FileInputStream ksin = new FileInputStream("myfile.p12");
ks.load(ksin, "password");
getKey("keyalis", "password");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM