I am trying to sign an XML file in C# .NET 4.0 with a private RSA Key generated by OpenSSL.
My source code looks like :
public static void SignXml(String filePath, String certificatePath)
{
CspParameters cspParams1 = new CspParameters();
cspParams1.KeyContainerName = certificatePath;
RSACryptoServiceProvider rsakey = new RSACryptoServiceProvider(cspParams1);
XmlDocument xmlDoc = new XmlDocument();
// Load an XML file into the XmlDocument object.
xmlDoc.PreserveWhitespace = true;
xmlDoc.Load(filePath);
SignedXml signedXml = new SignedXml();
CspParameters cspParams = new CspParameters();
cspParams.KeyContainerName = certificatePath;
// Create a new RSA signing key and save it in the container.
RSACryptoServiceProvider Key = new RSACryptoServiceProvider(cspParams);
// Add the key to the SignedXml document.
signedXml.SigningKey = Key;
// Create a reference to be signed.
Reference reference = new Reference();
reference.Uri = "";
// Add an enveloped transformation to the reference.
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
// Add the reference to the SignedXml object.
signedXml.AddReference(reference);
KeyInfo keyInfo = new KeyInfo();
// Load the X509 certificate.
X509Certificate MSCert = X509Certificate.CreateFromCertFile(certificatePath);
// Load the certificate into a KeyInfoX509Data object
// and add it to the KeyInfo object.
keyInfo.AddClause(new KeyInfoX509Data(MSCert));
keyInfo.AddClause(new RSAKeyValue((RSA)Key));
// Add the KeyInfo object to the SignedXml object.
signedXml.KeyInfo = keyInfo;
// Compute the signature.
signedXml.ComputeSignature();
// Get the XML representation of the signature and save
// it to an XmlElement object.
XmlElement xmlDigitalSignature = signedXml.GetXml();
// Append the element to the XML document.
xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
xmlDoc.Save(filePath);
}
I am calling the class (CPSMSXmlGenerator) in my application as a DLL(named DBTBeneficiariesCPSMS) and code for calling it is :
Dim genXml As String = DBTBeneficiariesCPSMS.CPSMSXmlGenerator.getXmlFile1(xml)
'Dim appPath As String = Request.PhysicalApplicationPath
Dim fullPath As String = Server.MapPath("/XML/") + dataSource + ".xml"
lblMessage.Text = fullPath
Dim SwFromFile As StreamWriter = New StreamWriter(fullPath)
SwFromFile.Write(genXml)
SwFromFile.Flush()
SwFromFile.Close()
CPSMSXmlGenerator.SignXml(fullPath, Server.MapPath("/XML/aua.cer"))
Now, the problem is whenever my application runs, it halts at ' Reference.Uri="" ' and an error as :-
Error: An XmlDocument context is required to resolve the Reference Uri .
is displayed, and XML file without digital signature certificate generates.
xmDoc is not passsed to SignedXml. Passing that as param should fix the problem
SignedXml signedXml = new SignedXml(xmlDoc);
Related
Dim textToSign As String = vstrToHash
Dim contentI As Byte()
contentI = Encoding.UTF8.GetBytes(textToSign)
Dim contentInfo As New ContentInfo(Encoding.UTF8.GetBytes(textToSign))
Dim signedCms As New SignedCms(contentInfo, False)
Dim certificateFromFile = New X509Certificate2("d:\preprod-root-ca.crt")
Dim certWithKey = certificateFromFile.GetRSAPublicKey
Dim Signer As CmsSigner = New CmsSigner(certificateFromFile)
'Signer.DigestAlgorithm = New System.Security.Cryptography.Oid("2.16.840.1.101.3.4.2.1") 'sha256
signedCms.ComputeSignature(Signer, False)
get key does not exist on last command and the certificate has no private key
This is expected, because .crt file contains only public key and do not store private key which is required for signing. Certificate with embedded private key often has .p12 or .pfx file extension and often are protected with password, so you will need to use X509Certificate2 constructor which accepts a password as a parameter.
I create an asp.net 4.0 web application which has a web service for uploading images. I am uploading images by sending the image in form of Base64 string from my mobile app to the web service.
Following is my code:
public string Authenticate(string username, string password, string fileID, string imageData)
{
Dictionary<string, string> responseDictionary = new Dictionary<string, string>();
bool isAuthenticated = true; // Set this value based on the authentication logic
try
{
if (isAuthenticated)
{
UploadImage(imageData);
string result = "success";
var message = "Login successful";
responseDictionary["status"] = result;
responseDictionary["message"] = message;
}
}
catch (Exception ex)
{
responseDictionary["status"] = ex.Message;
responseDictionary["message"] = ex.StackTrace;
}
return new JavaScriptSerializer().Serialize(responseDictionary);
}
private void UploadImage(string uploadedImage)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(uploadedImage);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)Image.FromStream(ms);
string uploadPath = Server.MapPath("..\\uploads\\") + DateTime.Now.Ticks.ToString() + ".jpeg";
ms.Close();
bitmap.Save(uploadPath, System.Drawing.Imaging.ImageFormat.Jpeg);
bitmap.Dispose();
}
This code was working fine on my local ASP.NET development server and I was able to see the uploaded image in my "uploads" directory. However, after transferring the code to the FTP directory, I am now getting the following error:
A generic error occurred in GDI+
I have checked that the upload directory has proper permission by creating a dummy .aspx page and creating a text file on page_load, and it works fine.
Even after doing google search, I was not able to solve this problem. Can anybody help me fixing this?
Thanks a lot in advance.
Instead of writing directly to files, save your bitmap to a MemoryStream and then save the contents of the stream to disk. This is an old, known issue and, frankly, I don't remember all the details why this is so.
MemoryStream mOutput = new MemoryStream();
bmp.Save( mOutput, ImageFormat.Png );
byte[] array = mOutput.ToArray();
// do whatever you want with the byte[]
In your case it could be either
private void UploadImage(string uploadedImage)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(uploadedImage);
string uploadPath = Server.MapPath("..\\uploads\\") + DateTime.Now.Ticks.ToString() + ".jpeg";
// store the byte[] directly, without converting to Bitmap first
using ( FileStream fs = File.Create( uploadPath ) )
using ( BinaryWriter bw = new BinaryWriter( fs ) )
bw.Write( imageBytes );
}
or
private void UploadImage(string uploadedImage)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(uploadedImage);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)Image.FromStream(ms);
string uploadPath = Server.MapPath("..\\uploads\\") + DateTime.Now.Ticks.ToString() + ".jpeg";
ms.Close();
// convert to image first and store it to disk
using ( MemoryStream mOutput = new MemoryStream() )
{
bitmap.Save( mOutput, System.Drawing.Imaging.ImageFormat.Jpeg);
using ( FileStream fs = File.Create( uploadPath ) )
using ( BinaryWriter bw = new BinaryWriter( fs ) )
bw.Write( mOutput.ToArray() );
}
}
Furthermore I think it's worth pointing out that when MemoryStream is used, stream must always be closed and save method MUST be called before the stream closure
byte[] byteBuffer = Convert.FromBase64String(Base64String);
MemoryStream memoryStream = new MemoryStream(byteBuffer);
memoryStream.Position = 0;
Bitmap bmpReturn = (Bitmap)Bitmap.FromStream(memoryStream);
bmpReturn.Save(PicPath, ImageFormat.Jpeg);
memoryStream.Close();
I'm consume an external webservice for sending data, using a web application in asp.net and Visual Studio 2010. The
sending of data must be digitally signed using a digital signature. The webservice contains the Signature class, where I
can fill all required values (SignedInfo, SignatureValue, KeyInfo).
I'm trying to fill the KeyInfo structure with the certificate like this:
Dim Sig As New RSP.SignatureType
(...)
Sig.SignedInfo = Sig_info
(...)
Sig.SignatureValue = Sig_value
Dim rspKey_info As New RSP.KeyInfoType()
Dim rspX509 As New RSP.X509DataType()
Dim arrCertificate As X509Certificate2()
arrCertificate = myF.ReturnCertificateCC()
rspKey_info.ItemsElementName = New RSP.ItemsChoiceType2(0) {}
rspKey_info.ItemsElementName(0) = RSP.ItemsChoiceType2.X509Data
rspKey_info.Items = New Object(0) {}
rspX509.ItemsElementName = New RSP.ItemsChoiceType2(0) {}
rspX509.ItemsElementName(0) = RSP.ItemsChoiceType2.X509Data
rspX509.Items = New Object(0) {}
rspX509.Items(0) = arrCertificate (0)
Sig.KeyInfo = rspKey_info
xmlString = myF.SerializeAnObject(Sig)
When I try to serialize the Signature Object, an error occur:
"Error generating the XML document."
InnerException:
"{ " The System.Security.Cryptography.X509Certificates.X509Certificate2 type was not expected . Use XmlInclude or
SoapInclude attribute to specify types that are not known statically. "}"
Public Function SerializeAnObject(ByVal obj As Object) As String
Dim doc As System.Xml.XmlDocument = New XmlDocument()
Dim serializer As System.Xml.Serialization.XmlSerializer = New System.Xml.Serialization.XmlSerializer(obj.GetType())
Dim stream As System.IO.MemoryStream = New System.IO.MemoryStream()
Try
serializer.Serialize(stream, obj)
stream.Position = 0
doc.Load(stream)
Return doc.InnerXml
Catch ex As Exception
Return ""
Finally
stream.Close()
stream.Dispose()
End Try
'#utilização
'dim xmlObject As string = SerializeAnObject(myClass)
End Function
Please help me...
I'm at several days trying to solve this...
Thanks in advance!
Regards!
rspX509.ItemsElementName = New RSP.ItemsChoiceType(0) {}
rspX509.ItemsElementName(0) = RSP.ItemsChoiceType.X509Certificate
rspX509.Items = New Object(0) {}
rspX509.Items(0) = arrCertificate (0)
rspKey_info.Items(0) = rspX509
Hi every one when returning json data from webservice top tag is adding please let me know how to remove top xml tag in the webservice
please let me know if any one this issue
i used the below method read
var obj = new List();
//MakesInfo objMakes = new MakesInfo();
MakesBL objMakesBL = new MakesBL();
if (Session["Makes"] == null)
{
obj = (List<MakesInfo>)objMakesBL.GetMakes();
Session["Makes"] = obj;
}
else
{
obj = (List<MakesInfo>)Session["Makes"];
}
StringBuilder str = new StringBuilder();
//var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
//string sJSON = oSerializer.Serialize(obj);
//return sJSON;
//yourobject is your actula object (may be collection) you want to serialize to json
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<MakesInfo>));
//create a memory stream
MemoryStream ms = new MemoryStream();
//serialize the object to memory stream
serializer.WriteObject(ms, obj);
//convert the serizlized object to string
string jsonString = Encoding.Default.GetString(ms.ToArray());
//close the memory stream
ms.Close();
return jsonString;
Use WCF just return list json object data is returned
I have a decrypted XML string which was sent over the wire to the receiving box where my code resides. Now, I want to write this XML string to an XML file.
Here's the Decrypt method which my code calls to generate this XML string... maybe this needs to be changed?
[Update]: My problem is that I can't see a way to write/create an XML file from a string of XML... I can see samples using a stream, a URL, but that doesn't help me here.
protected string DecryptForm(byte[] encryptedString, byte[] key, byte[] vector)
{
rijndael = new RijndaelManaged();
rijndael.Mode = CipherMode.CBC;
// Create a decryptor to perform the stream transform
ICryptoTransform decryptor = rijndael.CreateDecryptor(key, vector);
string plainText = null;
try
{
//Create the streams used for decryption
using (MemoryStream msStream = new MemoryStream(encryptedString))
{
using (CryptoStream csStream = new CryptoStream(msStream,
decryptor, CryptoStreamMode.Read))
{
using (StreamReader readerStream = new StreamReader(csStream))
{
// Read the decrypted bytes from the decrypting stream
plainText = readerStream.ReadToEnd();
}
}
}
finally
{
// Clear the RijndaelManaged object
if(rijndael != null)
rijndael.Clear();
}
// Return the decrypted string
return plainText;
}
}
xmlDoc = new XmlDocument();
xmlDoc.LoadXML(MyXMLString);
xmlDoc.Save(MyFilePath)