SAML2 assertion encryption using public key (opensaml) - encryption

I've recently tried to encrypt Saml2 assertion using relaying-party service public key. Unfortunately I can't finalise even the test phase
here is my code
public class EncryptionTest {
public static void main(String args[]){
try {
// The Assertion to be encrypted
FileInputStream fis;
DataInputStream in, in2;
File f = new File("src/main/resources/AssertionTest");
byte[] buffer = new byte[(int) f.length()];
in = new DataInputStream(new FileInputStream(f));
in.readFully(buffer);
in.close();
//Assertion = DataInputStream.readUTF(in);
String in_assert = new String(buffer);
System.out.println(in_assert);
org.apache.axiom.om.OMElement OMElementAssertion = org.apache.axiom.om.util.AXIOMUtil.stringToOM(in_assert);
Assertion assertion = convertOMElementToAssertion2(OMElementAssertion);
// Assume this contains a recipient's RSA public key
Credential keyEncryptionCredential;
keyEncryptionCredential = getCredentialFromFilePath("src/main/resources/cert.pem");
EncryptionParameters encParams = new EncryptionParameters();
encParams.setAlgorithm(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128);
KeyEncryptionParameters kekParams = new KeyEncryptionParameters();
kekParams.setEncryptionCredential(keyEncryptionCredential);
kekParams.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP);
KeyInfoGeneratorFactory kigf =
Configuration.getGlobalSecurityConfiguration()
.getKeyInfoGeneratorManager().getDefaultManager()
.getFactory(keyEncryptionCredential);
kekParams.setKeyInfoGenerator(kigf.newInstance());
Encrypter samlEncrypter = new Encrypter(encParams, kekParams);
samlEncrypter.setKeyPlacement(KeyPlacement.PEER);
EncryptedAssertion encryptedAssertion = samlEncrypter.encrypt(assertion);
System.out.println(encryptedAssertion);
} catch (EncryptionException e) {
e.printStackTrace();
} catch (CertificateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (KeyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (XMLStreamException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
public static Credential getCredentialFromFilePath(String certPath) throws IOException, CertificateException, KeyException {
InputStream inStream = new FileInputStream(certPath);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(inStream);
inStream.close();
//"Show yourself!"
System.out.println(cert.toString());
BasicX509Credential cred = new BasicX509Credential();
cred.setEntityCertificate((java.security.cert.X509Certificate) cert);
cred.setPrivateKey(null);
//System.out.println(cred.toString());
return cred;
//return (Credential) org.opensaml.xml.security.SecurityHelper.getSimpleCredential( (X509Certificate) cert, privatekey);
}
public static Assertion convertOMElementToAssertion2(OMElement element) {
Element assertionSAMLDOOM = (Element) new StAXOMBuilder(DOOMAbstractFactory.getOMFactory(), element.getXMLStreamReader()).getDocumentElement();
try {
UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(Assertion.DEFAULT_ELEMENT_NAME);
return (Assertion) unmarshaller.unmarshall(assertionSAMLDOOM);
} catch (Exception e1) {
System.out.println("error: " + e1.toString());
}
return null;
}
}
I constantly recive Null pointer exception in
KeyInfoGeneratorFactory kigf =
Configuration.getGlobalSecurityConfiguration()
.getKeyInfoGeneratorManager().getDefaultManager()
.getFactory(keyEncryptionCredential);
kekParams.setKeyInfoGenerator(kigf.newInstance());
How can I set GlobalSecurityConfiguration or is there different approach of encrypting Assertion which will work?

This question was laying open for too long. The problem was initialization of OpenSaml.
Simple
DefaultBootstrap.bootstrap();
helped and solved problem.

Related

How to save objects in a proper way with the stream writer?

In the program.cs the user is asked if he wanna read the data, if he types y then the method Doc.ReadDoc starts is there any proper way:
class Program
{
static void Main(string[] args)
{
do
{
var path = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path + #"\TestFile.txt";
Console.WriteLine("Do you want to read it? y/n");
string yesorno = Console.ReadLine();
if (yesorno=="y")
{
Console.Clear();
Doc.ReadDoc();
}
Console.WriteLine("Which type of vehicle");
string type = Console.ReadLine();
Console.WriteLine("how many tires");
int raeder = Convert.ToInt32( Console.ReadLine());
var Vehicle = new Used_Cars(type, raeder);
Doc.Write(Vehicle);
} while (true);
}
}
The Class with the methods (Read, Write):
public static List<string> ReadDoc()
{
var list = new List<string>();
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
try
{
using (StreamReader sr = new StreamReader(fileName))
{
Console.WriteLine("Data found");
string line;
Console.WriteLine(sr.ReadToEnd());
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("Data not found");
Console.WriteLine(e.Message);
list = null;
}
return list;
}
And the last Method is the Write method, is this a good code to save properties in a file? How could i stop the program with ESC or smth like that, so if the user presses ESC it should stop.
public static void Write(Used_Cars vehicle)
{
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
Console.WriteLine("Is it correct?");
Console.WriteLine("y/n");
string yeahorno= Console.ReadLine();
if (jaodernein == "y")
{
try
{
using (StreamWriter writer = new StreamWriter(fileName))
{
writer.WriteLine(vehicle.Vehicle);
writer.WriteLine(vehicle.Wheels);
Console.WriteLine();
}
}
catch (Exception exp)
{
Console.Write(exp.Message);
}
}
}

CancellationToken Source does not return taskcancelled when token.cancel is called

Below is the Service method that i call....
after i have called the service... my net goes off and i cancel the token
Which means after i have hit the service i cancel the token... is there a way to cancel the service i have called...
below is my code
public async Task<List<MeritData>> GetSyncupData(string Id, string BusinessDate, CancellationToken cancellationToken)
{
List<MeritData> PendingData = new List<MeritData>();
HttpResponseMessage responseMessage = null;
try
{
cancellationToken.ThrowIfCancellationRequested();
var api = RestService.For<IInventoryMeritStatusApi>(_httpClient);
responseMessage = await api.GetMeritData(Id, BusinessDate, cancellationToken).ConfigureAwait(false);
if (cancellationToken.IsCancellationRequested)
cancellationToken.ThrowIfCancellationRequested();
if (responseMessage.StatusCode == System.Net.HttpStatusCode.OK)
{
// my code on success
}
}
catch (SocketException SocketEx)
{
ServiceException serviceException = new ServiceException("SocketException", SocketEx);
throw serviceException;
}
catch (HttpRequestException httpReqEx)
{
ServiceException serviceException = new ServiceException("NoInternet", httpReqEx);
throw serviceException;
}
catch (ServiceException serviceEx)
{
ServiceException serviceException = new ServiceException("NoInternet", serviceEx);
throw serviceException;
}
catch (OperationCanceledException ex)
{
Console.WriteLine("TaskCanceledException GetProduct");
throw ex;
}
catch (Exception ex)
{
throw ex;
}
return PendingData;
}
after the line
responseMessage = await api.GetMeritData(Id, BusinessDate, cancellationToken).ConfigureAwait(false);
is executed i switch off the net and call cancellationTokenSource.Cancel();
it takes a long time and finally get a "httprequestexception" not a token cancelled exception
how do i solve this ? i want to cancel the call to the webservice when token.Cancel is called

Spring MVC returns 405 for api call made from my android client

I have an android app which is making api requests to my server running Spring MVC. The RestController works fine when I make a request from the browser but it responds with 404 when I am making requests from android. Not sure why
Here is code snippet from Android app making requests
public class AsyncFetch extends AsyncTask<Pair<String, String>, String, String> {
public ProgressDialog pdLoading;
private HttpURLConnection conn;
private String urlStr;
private String requestMethod = "GET";
public AsyncFetch(String endpoint, Context ctx)
{
pdLoading = new ProgressDialog(ctx);
Properties reader = PropertiesReader.getInstance().getProperties(ctx, "app.properties");
String host = reader.getProperty("host", "10.0.2.2");
String port = reader.getProperty("port", "8080");
String protocol = reader.getProperty("protocol", "http");
String context = reader.getProperty("context", "");
this.urlStr = protocol+"://"+host+":"+port+context+endpoint;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(Pair<String, String>... params) {
URL url;
try {
url = new URL(urlStr);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod(requestMethod);
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made`enter code here`
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
Spring MVC Controller
#RestController
public class ApiController {
#RequestMapping(value = "homefeed", method=RequestMethod.GET)
public String homefeed(#RequestParam(value="userId", required = false) Integer id, #RequestParam(value="search", required = false) String search, #RequestParam(value="page", required = false, defaultValue = "0") Integer page) { ... }
}
localhost:8080/api/homefeed -- works
127.0.0.1:8080/api/homefeed -- works
My Public IP:8080/api/homefeed -- does not works
10.0.2.2:8080/api/homefeed -- android emulator to localhost -- does not work
10.0.2.2:8080/Some resource other than the api endpoint -- works
Any help is highly appreciable, have wasted quiet some time in debugging.

Rxjava, Retrofit response body doesn't get the right answer?

My code like this:
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
Gson gson = new GsonBuilder()
.setLenient()
.create();
this.client = new OkHttpClient.Builder().addInterceptor(logging)
.connectTimeout(25, TimeUnit.SECONDS)
.readTimeout(25, TimeUnit.SECONDS)
.build();
// retrofit with custom client
this.retrofit = new Retrofit.Builder()
.baseUrl(NetUtil.getServerBaseUrl())
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(client)
.build();
this.apiService = retrofit.create(ApiEndpoints.class);
}
public Call<String> downloadImageCall(String uri){
return apiService.rxGetImageCall(uri);
}
The retrofit is like:
#GET
Call<String> rxGetImageCall(#Url String imageUrl);
When i run my code :
String url="";
Call<String> downCall = downloadImageCall(url);
try {
Response<String> mresponse = downCall.execute();
String info =mresponse.body();
LogHelper.i("final info: "+info);
} catch (IOException e1) {
e1.printStackTrace();
}
The data returned from the server is like :
"Please contact the administrator".
However in the above code, The info is just "Please"
I am confused about it, where is wrong about my code?
Depends on #Hans answer, I changed it to Responsebody, it works. But I don't know why "Call <String>" doesn't work. Feel free to post your answer.
This is my code:
#GET
Call<ResponseBody> rxGetImageCall(#Url String imageUrl);
public Call<ResponseBody> downloadImageCall(String uri){
return apiService.rxGetImageCall(uri);
}
Call<ResponseBody> mbody = mOperation.downloadContentDetail("http://javascript.info/tutorial/hello-world");
try {
Response<ResponseBody> mResponse = mbody.execute();
InputStream mStream =mResponse.body().byteStream();
StringWriter writer = new StringWriter();
BufferedInputStream bis = new BufferedInputStream(mStream);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
buf.write((byte) result);
result = bis.read();
}
LogHelper.i("result 1" + buf.toString());
} catch (IOException e) {
e.printStackTrace();
}

getServletContext().getResource(file3) returns null url resource

Here is my code which reads excelsheet files.but i can see my other functions are working fine but when try to get resource as url it return null.
URL resource = null;
try {
System.out.println(file3);
resource = getServletContext().getResource(file3);
System.out.println("Problem with getting resource"+resource);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file = null;
try {
System.out.println(resource.toURI());
file = new File(resource.toURI());
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FileInputStream input = null;
try {
input = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Workbook w;
w = Workbook.getWorkbook(input);
// Get the first sheet
Sheet sheet = w.getSheet(0);
return sheet;

Resources