RSACryptoServiceProvider error - rsacryptoserviceprovider

I encountered this error when I deployed the application in the production server, but in my local machine it is much working well.The error generates from this line (rsa.FromXmlString(xmlKey); in SignAndSecureData function). Anyone who encountered the error below? I also include the code snippets below the error message.
Error in: /sample.html.
Error Message:The profile for the user is a temporary profile.
Source: mscorlib
Method: System.Security.Cryptography.SafeProvHandle CreateProvHandle(System.Security.Cryptography.CspParameters, Boolean)
Stack Trace: at System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
at System.Security.Cryptography.RSACryptoServiceProvider.ImportParameters(RSAParameters parameters)
at System.Security.Cryptography.RSA.FromXmlString(String xmlString)
at website1.CryptoHelper.SignAndSecureData(String xmlKey, String[] values) in C:\website1\CryptoHelper.cs:line 52
at website1.CryptoHelper.SignAndSecureData(String[] values) in C:\website1\CryptoHelper.cs:line 40
-----------------------------Code-------------------------------
public static string SignAndSecureData(string[] values)
{
string xmlKey = "<RSAKeyValue><Modulus>p9HPjw9PMOCbYlu7YiE5chOOLgLfPR4L9jmcAyjrRsAekw0Z/xhs9G3Nl2P5G+/kMangrwg0egh2ium+3j5NuB0UGFEs8jKk/deSwwbxsxp+0p1JoY6jkHaQ1ItmrDVU5TZGjh7jNjBn5TpsrcFdxkslJp1x9ki248E7z7q1uhs=</Modulus><Exponent>AQAB</Exponent><P>27HXXHera3Voek0qg5pJf8wsl0Tq4xGl+tl1/f0rt1g6hyx4egS4/finWlptUnTnXu81oboYq7mI/kjzFiOPbQ==</P><Q>w41mCFTmdmINIo85D/8umTdwDsC+FOVlyYTVlw/xHBc/HxQQVOQOCVOJA9kZsVSUBr6fXY3yfSe/jxQXyzOSpw==</Q><DP>QCo38TzOZys6YYYKJbe5QccbOu8Y/0rXRGWhDZaU3w64wWQep9ybPyoRjtUcWtnj/Zk1+89Dh1xAA6zAurWWHQ==</DP><DQ>dsWiDDtswshpC+2LjgDCz8KRKBS/Hrf567zncdn36sTfzMOF69mcAOQg2xp4dXFWewY6izsU5hlHSuK8VOodDw==</DQ><InverseQ>WAmgU5XPgZNVXDMqYePpVZzQoiOblX4UlM21xTt/ZmvC7+af0c00LqOW4nbkwDqKCuRcD8X5Yr3H7IraaANjyg==</InverseQ><D>QbMRGAe9T/xOuLYC6Qrqy28+dWLodKvjsPSi0FXfriYekiFJ8SVl2ld2anNYHgjPhGXmMX/7016m0gFqmOU5VV1zzHVH0c0wecnKhhnJC+irjNgNwy9xwM1mnVoce9auk2qiAMhr2cL1NtwUf8cuXBfzm39ZF9Sxsn4fE1+p+ck=</D></RSAKeyValue>";
return SignAndSecureData(xmlKey, values);
}
public static string SignAndSecureData(string xmlKey, string[] values)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<x></x>");
for (int i = 0; i < values.Length; i++)
_AddNode(xmlDoc, "v" + i.ToString(), values[i]);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlKey);
byte[] signature = rsa.SignData(Encoding.ASCII.GetBytes(xmlDoc.InnerXml),
"SHA1");
_AddNode(xmlDoc, "s", Convert.ToBase64String(signature, 0, signature.Length));
return EncryptCookie(xmlDoc.InnerXml);
}

Related

RestAssured delete method returns status code 405

RestAssured Delete method returns status code as 405 but when I try from Postman it returns 202 ( which is as expected )
In Postman :
Method : DELETE
PATH : .../rest/end1/end2?name=xyz
Code :
String name = "xyz";
String baseURI = System.getProperty("environmentPathUrl");
String path = "/rest/end1";
public void deleteName(String baseURI, String path, String name) {
String Resp = RestAssured.given().baseUri(baseURI).basePath(path).queryParam("name", name).when()
.delete("/end2").then().assertThat().statusCode(202).and().extract().response().asString();
System.out.println("Response is\t" + Resp);
}
You're making a mistake in the Rest Assured code, Add a .log().all() after given() to see the request traffic and you will be able to see your mistake
I've made few changes to the code and this should work for you hopefully
public static void deleteName() {
String name = "xyz";
String baseURI = System.getProperty("environmentPathUrl");
String path = "/rest/end1";
String Resp = RestAssured.given().log().all().baseUri(baseURI).basePath(path).queryParam("name", name).when()
.delete("/end2").then().assertThat().statusCode(202).and().extract().response().asString();
System.out.println("Response is\t" + Resp);
}
public static void main(String[] args) {
deleteName();
}

How to convert httppostedfilebase to String array

public ActionResult Import(HttpPostedFileBase currencyConversionsFile)
{
string filename = "CurrencyConversion Upload_" + DateTime.Now.ToString("dd-MM-yyyy") + ".csv";
string folderPath = Server.MapPath("~/Files/");
string filePath = Server.MapPath("~/Files/" + filename);
currencyConversionsFile.SaveAs(filePath);
string[] csvData = System.IO.File.ReadAllLines(filePath);
//the later code isn't show here
}
I know the usual way to convert httppostedfilebase to String array, which will store the file in the server first, then read the data from the server. Is there anyway to get the string array directly from the httppostedfilebase with out store the file into the server?
Well you can read your file line by line from Stream like this:
List<string> csvData = new List<string>();
using (System.IO.StreamReader reader = new System.IO.StreamReader(currencyConversionsFile.InputStream))
{
while (!reader.EndOfStream)
{
csvData.Add(reader.ReadLine());
}
}
From another thread addressing the same issue, this answer helped me get the posted file to a string -
https://stackoverflow.com/a/40304761/5333178
To quote,
string result = string.Empty;
using (BinaryReader b = new BinaryReader(file.InputStream))
{
byte[] binData = b.ReadBytes(file.ContentLength);
result = System.Text.Encoding.UTF8.GetString(binData);
}
Splitting the string into an array -
string[] csvData = new string[] { };
csvData = result.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);

handleURI for http://AAA.BBB.CCC.DDD:8080/myapp/ uri: '' returns ambigious result (Vaadin 6)

In my Vaadin 6 application I sometimes get the following error:
SEVERE: Terminal error:
java.lang.RuntimeException: handleURI for http://AAA.BBB.CCC.DDD:8080/myapp/ uri: '' returns ambigious result.
at com.vaadin.ui.Window.handleURI(Window.java:432)
at com.vaadin.terminal.gwt.server.AbstractCommunicationManager.handleURI(AbstractCommunicationManager.java:2291)
at com.vaadin.terminal.gwt.server.CommunicationManager.handleURI(CommunicationManager.java:370)
at com.vaadin.terminal.gwt.server.AbstractApplicationServlet.handleURI(AbstractApplicationServlet.java:1099)
at com.vaadin.terminal.gwt.server.AbstractApplicationServlet.service(AbstractApplicationServlet.java:535)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
Accrording to Vaadin source it occurs in the following method:
public DownloadStream handleURI(URL context, String relativeUri) {
DownloadStream result = null;
if (uriHandlerList != null) {
Object[] handlers;
synchronized (uriHandlerList) {
handlers = uriHandlerList.toArray();
}
for (int i = 0; i < handlers.length; i++) {
final DownloadStream ds = ((URIHandler) handlers[i]).handleURI(
context, relativeUri);
if (ds != null) {
if (result != null) {
throw new RuntimeException("handleURI for " + context
+ " uri: '" + relativeUri
+ "' returns ambigious result.");
}
result = ds;
}
}
}
return result;
}
I actually create a DownloadStream in a column generator (in order to display images in a table):
public class ImageColumnGenerator implements Table.ColumnGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(ImageColumnGenerator.class);
public final static String IMAGE_FIELD = "image";
public Object generateCell(final Table aTable, final Object aItemId, final Object aColumnId) {
if (!IMAGE_FIELD.equals(aColumnId)) {
return null;
}
final BeanItem<UserProductImageBean> beanItem = (BeanItem<UserProductImageBean>)
aTable.getItem(aItemId);
final StreamResource streamResource = new StreamResource(new StreamResource.StreamSource() {
public InputStream getStream() {
return new ByteArrayInputStream(beanItem.getBean().getImageData());
}
},
beanItem.getBean().getFileName(),
MyApplication.getInstance());
LOGGER.debug("imageResource: " + streamResource);
final Embedded embedded = new Embedded("", streamResource);
return embedded;
}
}
beanItem.getBean().getImageData() is a byte array (byte[]) with image data, which I get from a web service.
MyApplication.getInstance() is defined as follows:
public class MyApplication extends Application implements ApplicationContext.TransactionListener
{
private static ThreadLocal<MyApplication> currentApplication =
new ThreadLocal<MyApplication> ();
public static MyApplication getInstance()
{
return currentApplication.get ();
}
}
What can I do in order to fix the aforementioned (severe) error?
As soon as nobody answer. I'm not at all expert in what hell it is above, but - try to find out on what kind of urls this error arise on, and do with them something before feed them to DownloadStream

Reading a file with a read method using Scanner (InputMismatchException)

I'm new to java and I have a problem with reading a file using the scanner class.
My objective is to read the following .txt file:
3
Emmalaan 23
3051JC Rotterdam
7 rooms
price 300000
Javastraat 88
4078KB Eindhoven
3 rooms
price 50000
Javastraat 93
4078KB Eindhoven
4 rooms
price 55000
The "3" on top of the file should be read as an integer that tells how many houses the file has. The following four lines after the "3" determine one house.
I try to read this file using a read method in the class portefeuille:
public static Portefeuille read(String infile)
{
Portefeuille returnvalue = new Portefeuille();
try
{
Scanner scan = new Scanner(new File(infile)).useDelimiter(" |/n");
int aantalwoningen = scan.nextInt();
for(int i = 0; i<aantalwoningen; ++i)
{
Woning.read(scan);
}
}
catch (FileNotFoundException e)
{
System.out.println("File could not be found");
}
catch (IOException e)
{
System.out.println("Exception while reading the file");
}
return returnvalue;
}
The read method in the Woning class looks like this:
public static Woning read(Scanner sc)
{
String token_adres = sc.next();
String token_dr = sc.next();
String token_postcd = sc.next();
String token_plaats = sc.next();
int token_vraagPrijs = sc.nextInt();
String token_kamerstxt = sc.next();
String token_prijstxt = sc.next();
int token_kamers = sc.nextInt();
return new Woning(adresp, token_vraagPrijs, token_kamers);
}
When I try to execute the following code:
Portefeuille port1 = Portefeuille.read("woningen.txt");
I get the following error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Portefeuille.read(Portefeuille.java:48)
at Portefeuille.main(Portefeuille.java:112)
However if I use the read method from the Woning class to read one adres in a string format:
Emmalaan 23
3051JC Rotterdam
7 Rooms
price 300000
It works fine.
I tried to change the .txt file into only one address without the "3" on top so that it is exactly formatted like the address that should work. But when I call the read method from Woning class it still gives me the error.
Could anyone please help me with this?
Thank you!
I was also facing a similar issue, so I put my answer so that it could help in future:
There are two possible modifications which I did to make this code run.
First option: Change the use of useDelimiter method to .useDelimiter("\\r\\n") when creating the Scanner class, I was in windows so we might need \\r for Windows compatibility.
Using this modification, there will be no exception.But the code will again fail at int token_vraagPrijs = sc.nextInt();.
Because in the public static Woning read(Scanner sc), you are suing sc.next();.Actually this method finds and returns the next complete token from this scanner.A complete token is preceded and followed by input that matches the delimiter pattern.
So, every sc.next() is actually reading a line not a token.
So as per your code sc.nextInt() is trying to read something like Javastraat 88.So again it will give you the same exception.
Second option (Preferred):Don't use any delimiter, Scanner class will default whitespace and your code will work fine.I modified your code and It worked fine for me.
Code:
public class Test3{
public static void main(String... s)
{
read("test.txt");
}
public static void read(String infile)
{
try (Scanner scan = new Scanner(new File(infile)))
{
int aantalwoningen = scan.nextInt();
System.out.println(aantalwoningen);
for (int i = 0; i < aantalwoningen; ++i)
{
read(scan);
}
}
catch (FileNotFoundException e)
{
System.out.println("File could not be found");
}
}
public static void read(Scanner sc)
{
String token_adres = sc.next();
String token_dr = sc.next();
String token_postcd = sc.next();
String token_plaats = sc.next();
int token_vraagPrijs = sc.nextInt();
String token_kamerstxt = sc.next();
String token_prijstxt = sc.next();
int token_kamers = sc.nextInt();
System.out.println(token_adres + " " + token_dr + " " + token_postcd + " " + token_plaats + " "
+ token_vraagPrijs + " " + token_kamerstxt + " " + token_prijstxt + " " + token_kamers);
} }

A generic error occurred in GDI+ When uploading an image from Desktop application to web server using web api

I am trying to upload an image from my Windows Desktop application (VB.NET) to Web Server
using web api
The Code runs correctly in local machine. but fails when run on web server with the error message A generic error occurred in GDI+.
The following is the WebApi Code which accepts the image
public void PostFile(ImageData objImage)
{
Image img = BytesToImage(objImage.ImageFile);
string ImageName = objImage.EmployeeGUID.ToString() + ".Jpg";
string FilePath = "";
FilePath = System.Web.HttpContext.Current.Server.MapPath("~/photo") ;
try {
img.Save(FilePath + '\\' + ImageName.ToString(), System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception ex) {
}
}
public class ImageData
{
public long EmployeeCode;
public Guid EmployeeGUID;
public byte[] ImageFile ;
}
private Image BytesToImage(byte[] ImageBytes)
{
Image imgNew;
MemoryStream memImage = new MemoryStream(ImageBytes);
imgNew = Image.FromStream(memImage);
return imgNew;
}
The following code is VB.NET Code (Windows forms Application) from which image is
uploaded
Public Sub SendFile()
Dim EmployeeGUID As GUID
Dim EmployeeCode As long
Dim ImagefileToSend As String
Dim objImage As ImageData
Dim client As New HttpClient
client.BaseAddress = New Uri(WebApiPath)
client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
objImage = New ImageData()
objImage.EmployeeCode = EmployeeCode
objImage.EmployeeGUID = EmployeeGUID
objImage.ImageFile = ImageToBytes(Image.FromFile(ImagefileToSend))
Dim jsonFormatter As MediaTypeFormatter = New JsonMediaTypeFormatter()
Dim content As HttpContent = New ObjectContent(GetType(ImageData), objImage, jsonFormatter)
Dim result As System.Net.Http.HttpResponseMessage
Try
result = client.PostAsync("api/GetFile", content).Result
Catch ex As Exception
End Try
End Sub
Private Class ImageData
Public EmployeeCode As Long
Public EmployeeGUID As Guid
Public ImageFile As Byte()
End Class
Private Function ImageToBytes(ByVal image As Image) As Byte()
Dim memImage As New IO.MemoryStream
Dim bytImage() As Byte
image.Save(memImage, image.RawFormat)
bytImage = memImage.GetBuffer()
Return bytImage
End Function
The Photo directory did not had write permission. Now it is working correctly

Resources