This week's book giveaway is in the Spring forum.
We're giving away four copies of Spring in Action (5th edition) and have Craig Walls on-line!
See this thread for details.
Win a copy of Spring in Action (5th edition) this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

WS Security Related  RSS feed

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I was trying to encrypt a message using XSS4j.I have certain issues.As for Encryption we are supposed to use Public Key of client to genrate and encrypt the symmetric key which will be used for final Enbcryption.I am trying to use the same but my doubt is how to create a symmetric key and how to encrypt it using public key.

Actually some how I coded and it is encrypting hte message also but it is throwing Null pointer Exception i.e "Key is not specified or obtained."

When I explored it further I guess it is creating this problem while resolvinfg Key.I dont have any idea how to Resolve the Key without using KeyStoreKeyInfoResolver.As My public is not being store in Key Store.I am getign this key fromCertificate sent by client.

For your knowledge I am enclosing detailed code along with.

In code I am sending a Signed Soap Request and I am trying to encrypt a paarticular element.Please help me in this typically how to resolve Key.


In the code I ahve commented use of "KeyStoreKeyInfoResolver" as for actual Requirement I am not supposed to use Key Store.But if I use this I get perfect encrypted Message My problem is to resolveKEy without using Key Store.

I am seding you out put also.
..............................................
Code
................................................

/*
* Created on Sep 13, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.sterling.webservice.WSSecurity;

import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;

import java.security.Key;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.ibm.xml.dsig.util.AdHocIDResolver;
import com.ibm.xml.enc.AlgorithmFactoryExtn;
import com.ibm.xml.enc.EncryptionContext;
//import com.ibm.xml.enc.KeyInfoResolver;
import com.ibm.xml.enc.KeyInfoResolvingException;
import com.ibm.xml.enc.StructureException;
import com.ibm.xml.enc.type.CarriedKeyName;
import com.ibm.xml.enc.type.CipherData;
import com.ibm.xml.enc.type.CipherValue;
import com.ibm.xml.enc.type.DataReference;
import com.ibm.xml.enc.type.EncryptedData;
import com.ibm.xml.enc.type.EncryptedKey;
import com.ibm.xml.enc.type.EncryptionMethod;
import com.ibm.xml.enc.type.KeyInfo;
import com.ibm.xml.enc.type.KeyName;
import com.ibm.xml.enc.type.ReferenceList;
import com.ibm.xml.enc.util.KeyStoreKeyInfoResolver;
import org.apache.xerces.parsers.DOMParser;
import javax.crypto.spec.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.Node;
import com.ibm.dom.util.XPathCanonicalizer;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import com.ibm.xml.enc.KeyInfoResolverBase;
/**
* @author ngupta
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class MessageEncryption extends KeyInfoResolverBase {

static String KEY_ALIAS = "key_neer2";
private MyKeyInfo mykeyinfo;
String soapURl = "C:\\neeru\\SoapRequest.xml";
static final String PASSWORD = "password";
String keyStorePath = "C:\\Documents and Settings\\ngupta\\.keystore";
String encType="http://www.w3.org/2001/04/xmlenc#Element";
Document doc;
KeyInfoResolverBase kiRes;
Key key;
AlgorithmFactoryExtn af;
public MessageEncryption() throws KeyStoreException
{
mykeyinfo = new MyKeyInfo(keyStorePath);
}

public Document getDocument(String soapURL) throws SAXException, IOException
{
DOMParser soapDoc = new DOMParser();
System.out.println("soapURL " + soapURL);
soapDoc.parse(soapURL);

return soapDoc.getDocument();
}




private KeyInfo getKeyInfo(Key pubKey,String password,String DataID) throws StructureException, ParserConfigurationException, KeyStoreException, SAXException, IOException, KeyInfoResolvingException
{
KeyInfo keyInfo = new KeyInfo();

EncryptedKey encKey = new EncryptedKey();
encKey.setId("#Key");
EncryptionMethod encMethod = new EncryptionMethod();
String encAlgo=null;

//String keyAlgo = this.mykeyinfo.getKey(keyAlias).getAlgorithm();
String keyAlgo=pubKey.getAlgorithm();
if ( keyAlgo== "RSA")
{
encAlgo = encMethod.RSA_1_5;

}else

{
System.out.println("Key Algo is not RSA Please Set Also");
}

encMethod.setAlgorithm(encAlgo);

encKey.setEncryptionMethod(encMethod);

KeyInfo keyinfo = new KeyInfo();
KeyName keyName = new KeyName();

keyName.setName(KEY_ALIAS);
keyinfo.addKeyName(keyName);
encKey.setKeyInfo(keyinfo);

byte data[] = "password1".getBytes();
System.out.println( data);
CipherValue ciphValue = new CipherValue();
ciphValue.setValue(data);
CipherData ciphData = new CipherData();
ciphData.setCipherValue(ciphValue);
encKey.setCipherData(ciphData);

ReferenceList refList = new ReferenceList();
DataReference dataRef =new DataReference();
dataRef.setURI(DataID);
refList.addDataReference(dataRef);
encKey.setReferenceList(refList);
keyInfo.addEncryptedKey(encKey);


return keyInfo;
}

private Document addKeyInfo(Document soapDoc,KeyInfo keyInfo) throws StructureException
{
String prefix = "soapenv:";
Element SecurityElement=null;
NodeList nl = soapDoc.getElementsByTagName("Security");
if (nl.item(0)!= null)
{
SecurityElement = (Element) nl.item(0);
}
else
{
SecurityElement = soapDoc.createElement(prefix+"Security");
}


Element keyInfoElement = keyInfo.createElement(soapDoc,true);
SecurityElement.appendChild(keyInfoElement);

return soapDoc;
}

org.w3c.dom.Document encryptMessage(org.w3c.dom.Document soapDoc,String nameOfElementToEncrypt,Key pubKey,String encType,String pwdToGenSymKey) throws Exception
{

EncryptedData encData = new EncryptedData();
encData.setId("ED#1");
EncryptionMethod encMethod = new EncryptionMethod();
encMethod.setAlgorithm(encMethod.TRIPLEDES_CBC);
encData.setEncryptionMethod(encMethod);

encData.setType(encType);

CipherData ciphData =new CipherData();
CipherValue ciphValue = new CipherValue();
ciphData.setCipherValue(ciphValue);
encData.setCipherData(ciphData);

String ID = encData.getId();
KeyInfo keyInfo =this.getKeyInfo(pubKey,pwdToGenSymKey,ID);
soapDoc = this.addKeyInfo(soapDoc, keyInfo);

NodeList keynode = soapDoc.getElementsByTagName("KeyInfo");
Element keyInfoElement = keyInfo.createElement(soapDoc,true);


NodeList n1 = soapDoc.getElementsByTagName(nameOfElementToEncrypt);
if (n1.item(0) == null) {
// no body...we have issues...just
System.out.println("it is null");
}
Element elementToEncrypt = (Element) n1.item(0);
KeyInfoResolverBase kiRes = new KeyInfoResolverBase() ;
//KeyStoreKeyInfoResolver kiRes= new KeyStoreKeyInfoResolver(mykeyinfo.keystore);
//kiRes.putAliasAndPassword(KEY_ALIAS, "password".toCharArray());

AlgorithmFactoryExtn af = new AlgorithmFactoryExtn();
// System.out.println("factory"+af.getProvider());
kiRes.setOperationMode(KeyInfoResolverBase.ENCRYPT_MODE);
kiRes.setAlgorithmFactory(af);





Element encTemp =encData.createElement(soapDoc,true);


EncryptionContext ec = new EncryptionContext();
ec.setAlgorithmFactory(af);
// ec.setKey(key);
ec.setData(elementToEncrypt);
ec.setKeyInfoResolver(kiRes);
ec.setEncryptedType(encTemp,null, null,keyInfoElement);

ec.encrypt();
ec.replace();
return soapDoc;
}
public void generateSignedDoc(Document doc, OutputStream outStream)
throws IOException {

Writer wr = new OutputStreamWriter(outStream, "UTF-8");
if (doc != null) {
XPathCanonicalizer.serializeAll(doc, true, wr);
} else {
System.out.println("Input Document is Null ");
}
wr.flush();

}


/**
* @param string
* @return
* @throws Exception
*/


....................................................................
Output
.....................................................................

soapURL C:\neeru\SoapRequest.xml
[B@26e431
java.lang.NullPointerException: Key not specified or obtained
at com.ibm.xml.enc.EncryptionContext.getEncryptionEngine(EncryptionContext.java:282)
at com.ibm.xml.enc.EncryptionContext.encrypt(EncryptionContext.java:236)
at com.ibm.xml.enc.KeyInfoResolverBase.resolveEncryptedKey(KeyInfoResolverBase.java:131)
at com.ibm.xml.enc.KeyInfoResolverBase.resolve(KeyInfoResolverBase.java:357)
at com.ibm.xml.enc.EncryptionContext._getKey(EncryptionContext.java:293)
at com.ibm.xml.enc.EncryptionContext.getEncryptionEngine(EncryptionContext.java:280)
at com.ibm.xml.enc.EncryptionContext.getEncryptionOutputStream(EncryptionContext.java:251)
at com.ibm.xml.enc.EncryptionContext.encrypt(EncryptionContext.java:232)
at com.sterling.webservice.WSSecurity.MessageEncryption.encryptMessage(MessageEncryption.java:220)
at com.sterling.webservice.WSSecurity.MessageEncryption.main(MessageEncryption.java:252)
<soapenv:Envelope xmlns:mesa="http://www.sterlingcommerce.com/mesa" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Header><Security><SOAP-SEC:Signature xmlns:SOAP-SEC="http://schemas.xmlsoap.org/soap/security/2000-12" soapenv:mustUnderstand="1"><Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"></CanonicalizationMethod>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></SignatureMethod>
<Reference URI="#Body">
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></DigestMethod>
<DigestValue>dpovPReVe9W1JQmCL2n/ggKNN7s=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>
v1t3kPFfsQA93MrQT6AzGzOkDe5zhyZdbHVxpYKL0OM1JeSWls7JDN1TyYkSH/QKjzuD
Ph/od0YD7IK3CYMG7JJRBnqrFGpc+V8ZqkeMEe8YiFte4RE5wxYSQySf8pCjc8Eqi2EE
Zklids8OmguLeWFiVcX7QsJXgIzPVPwWtbg=
</SignatureValue>
</Signature></SOAP-SEC:Signature><KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#"><EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#" Id="#Key"><EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"></EncryptionMethod><KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#"><KeyName>key_neer2</KeyName></KeyInfo><CipherData><CipherValue>cGFzc3dvcmQx</CipherValue></CipherData><ReferenceList><DataReference URI="ED#1"></DataReference></ReferenceList></EncryptedKey></KeyInfo></Security></soapenv:Header><soapenv:Body ID="Body">
<mesaAuth>
<principal>admin</principal>
<auth hashType="None">password</auth>
</mesaAuth>
<FileCollection>
<EncryptedData xmlns="http://www.w3.org/2001/04/xmlenc#" Id="ED#1" Type="http://www.w3.org/2001/04/xmlenc#Element"><EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"></EncryptionMethod><CipherData><CipherValue>+5EUyDxDSxuWzr988xiuLdYnAU7be/M0UnX6rC2ZIY8RWiP4x5t7MQCZ6FIABSDP</CipherValue></CipherData></EncryptedData>
</FileCollection>
</soapenv:Body>
</soapenv:Envelope>

....................................
Fiel which I am sending for Encryption

soapURL C:\neeru\SoapRequest.xml
<soapenv:Envelope xmlns:mesa="http://www.sterlingcommerce.com/mesa" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Header><Security><SOAP-SEC:Signature xmlns:SOAP-SEC="http://schemas.xmlsoap.org/soap/security/2000-12" soapenv:mustUnderstand="1"><Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"></CanonicalizationMethod>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></SignatureMethod>
<Reference URI="#Body">
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></DigestMethod>
<DigestValue>dpovPReVe9W1JQmCL2n/ggKNN7s=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>
v1t3kPFfsQA93MrQT6AzGzOkDe5zhyZdbHVxpYKL0OM1JeSWls7JDN1TyYkSH/QKjzuD
Ph/od0YD7IK3CYMG7JJRBnqrFGpc+V8ZqkeMEe8YiFte4RE5wxYSQySf8pCjc8Eqi2EE
Zklids8OmguLeWFiVcX7QsJXgIzPVPwWtbg=
</SignatureValue>
</Signature></SOAP-SEC:Signature></Security></soapenv:Header><soapenv:Body ID="Body">
<mesaAuth>
<principal>admin</principal>
<auth hashType="None">password</auth>
</mesaAuth>
<FileCollection>
<collectionFolder></collectionFolder>
</FileCollection>
</soapenv:Body>
</soapenv:Envelope>


Thanx In Advance

Neer

public static void main(String args[]) throws Exception
{

MessageEncryption msgEnc = new MessageEncryption();
Key pubKey=msgEnc.mykeyinfo.getMyCertificate(KEY_ALIAS).getPublicKey();

Document soapDoc = msgEnc.getDocument(msgEnc.soapURl);
Document encDoc=msgEnc.encryptMessage(soapDoc,"collectionFolder",pubKey,msgEnc.encType,msgEnc.PASSWORD);
SignSoapMessage ssm = new SignSoapMessage();
ByteArrayOutputStream barry = new ByteArrayOutputStream();
msgEnc.generateSignedDoc(encDoc,System.out);

}
}
 
High Plains Drifter
Posts: 7292
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving this to the Security forum.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!