Decrypt/Verify signed data using public certificate asp.net - asp.net

My client has signed the xml in Java using private key & IAIK tool. I want to decrypt/verify the data in ASP.NET 2.0. I have public certificate of my client. I have tried various methods but verifcation fails. Kindly suggest any code to verify/decrypt the data. The signed XML is as follows
<TrnResponse>
<Transaction>
<Type>TrnResponse</MessageType>
<ReferenceNo>123456</ReferenceNo>
<ClientName>ABCDI</ClientName>
<TReferenceNo>111111</CTReferenceNo>
<Mode>05</Mode>
<Status>SUCCESSFUL</Status>
<TRXDateTime>06-03-2012 13:16:21</TRXDateTime>
<TRXID>001111222</TRXID>
</Transaction>
<Signature> <SignatureValue>MIAGCSqGSIb3DQEHAqCAMIIHlwIBATELMAkGBSsOAwIaBQAwCwYJKoZIhvcNAQcB</SignatureValue>
</Signature>
</TrnResponse>
i am trying following code to verify
XmlDocument Doc = new XmlDocument();
Doc.PreserveWhitespace = false;
Doc.Load(#"d:\data.xml");
SignedXml signedXml = new SignedXml(Doc);
XmlNodeList nodeList = Doc.GetElementsByTagName("Signature");
X509Certificate2 cert = GetRecipientCert(); // method returns public certificate
RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PublicKey.Key;
string publickey = cert.PublicKey.Key.ToXmlString(false);
XmlNodeList xn1 = Doc.GetElementsByTagName("Transaction");
string license_code = xn1.Item(0).OuterXml.ToString();
ASCIIEncoding ByteConverter = new ASCIIEncoding();
byte[] verify_this = ByteConverter.GetBytes(license_code);
string base64_encoded_signature = Doc.GetElementsByTagName("SignatureValue").Item(0).InnerText;
byte[] signature = Convert.FromBase64String(base64_encoded_signature);
bool ok = csp.VerifyData(verify_this, new SHA1CryptoServiceProvider(), signature);
Please help to solve this

Related

Using an X509 certificate from an Azure Blob and using it in an Azure website

I read another post about this, I try the answers but I am having errors running in azure, running locally it's OK.
I cant find the solution, to use a certificate.p12 from file.
I have the error in ObjCert.Import(certData) when I run in Azure, not in local.
Thanks!
X509Certificate2 objCert = new X509Certificate2();
string accountName = "xxxxxstorage";
string accountKey = "qqqqqqqqqqqqqqqjt8DGAI6aBoBzdwwwwwwwwwwwwwzZg==";
StorageCredentials creds = new StorageCredentials(accountName, accountKey);
CloudStorageAccount account = new CloudStorageAccount(creds, useHttps: true);
// Create the blob client.
CloudBlobClient blobClient = account.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("certificate");
CloudBlockBlob blockBlob = container.GetBlockBlobReference("Certificate.p12");
byte[] certData;
// Save blob contents to a memorystream.
using (var stream = new MemoryStream())
{
blockBlob.DownloadToStream(stream);
certData = stream.ToArray();
}
objCert.Import(certData);
I solve it
Replacing:
objCert.Import(certData)
by
X509Certificate2 selfSignedCert = new X509Certificate2(certData, "", X509KeyStorageFlags.MachineKeySet);

JSEncrypt encrypt on client and decrypt on server

I am using JSEncrypt to encrypt user's password on the client and send to server to decrypt.
I get the public key from the server which I build the RSA Key on the client with Javascript:
var leafCert = new X509();
leafCert.readCertPEM(publicCertificate);
In my encrypt method
var encryptKey = new JSEncrypt();
var encryptedValue = serverPublicKey.encrypt(inputStr)
return String(inputStr)
On server when I decrypt I see junk message. My server-side code:
public String decryptString(String encryptedVal, String sessionId)
{
String sResult="";
try
{
PrivateKey pvtKey = getPrivateKeyFromSession(sessionId);
Cipher pkCipher=null;
pkCipher = Cipher.getInstance("RSA/None/NoPadding", "BC");
pkCipher.init(Cipher.DECRYPT_MODE, pvtKey);
Base64 encoder = Base64.getInstance();
byte[] decodedValue = encoder.decode(encryptedVal);
byte[] deCryptedBytes =pkCipher.doFinal( decodedValue );
sResult = new String(deCryptedBytes);
}
catch(Exception ex){log.error("Error decryptString" + ex.getMessage()); }
return sResult.trim();
}
Can you let me know where am I going wrong. I do not see the actual decrypted message on the server.

How to authenticate Google Drive in asp.net without copy/pasting auth tokens

I am developing Web Application to Upload a file on Google Drive in ASP.NET using C#.
While running the Application I want to upload file automatically to Google Drive with automatic authentication technique.
Following is the class file used to upload file but unable to authenticate to Google API.There is something Wrong with GetAuthorization(). Please help me for that...
namespace Cloud
{
class Code
{
private static readonly string CLIENT_ID = "303453771054- 4ftp53uun2o6jeiii85i22muc4fio76f.apps.googleusercontent.com";
private static readonly string CLIENT_SECRET = "wMc6mptgMTOL1ncGSJX-qoPS";
private static readonly string APIKEY = "AIzaSyAVyZF8OVl4Vvrbu9pWUQCzx35afdpYJR0";
private static readonly string REDIRECTURI = "http://localhost:49632/CloudCode.aspx";
private static readonly string[] SCOPES = new[] { DriveService.Scopes.Drive.GetStringValue() };
public void Main(string Filename)
{
var provider = new WebServerClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET);
provider.ClientIdentifier = CLIENT_ID;
provider.ClientSecret = CLIENT_SECRET;
provider.RequestUserAuthorization();
provider.ProcessUserAuthorization(null);
var authenticator = new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization);
File body = new File();
body.Title = "My document";
body.Description = "A test document";
body.MimeType = "text/plain";
body.OriginalFilename = Filename;
byte[] byteArray = System.IO.File.ReadAllBytes(body.OriginalFilename.ToString());
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
DriveService service = new DriveService();
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain");
request.Upload();
File file = request.ResponseBody;
}
private IAuthorizationState GetAuthorization(WebServerClient arg)
{
IAuthorizationState state = arg.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request));
IAuthorizationState AuthorizationState=new AuthorizationState(SCOPES);
AuthorizationState.Callback = new Uri(REDIRECTURI);
return AuthorizationState;
}

Serializing using protobuf-net and sending as postdata in http

I'm using Protobuf-net to try and send a serialized object to a webapplication that I'm running in another project. The Serializer.Serialize<T>() method takes a Stream (to write to) and and instance of T (in this case, a list of a few objects that I set up to work with protobuf-net)
How do I go about doing this? Do I need to write to a file or can I send the stream as postdata somehow? Below you can see I'm using a string as the postdata.
My execute post method
public static void ExecuteHttpWebPostRequest(Uri uri,string postdata, int requestTimeOut, ref string responseContent)
{
if (string.IsNullOrEmpty(uri.Host))// || !IsConnectedToInternet(uri))
return;
var httpWebReq = (HttpWebRequest)WebRequest.Create(uri);
var bytePostData = Encoding.UTF8.GetBytes(postdata);
httpWebReq.Timeout = requestTimeOut*1000;
httpWebReq.Method = "POST";
httpWebReq.ContentLength = bytePostData.Length;
//httpWebReq.ContentType = "text/xml;charset=utf-8";
httpWebReq.ContentType = "application/octet-stream";
//httpWebReq.TransferEncoding=
//httpWebReq.ContentType = "application/xml";
//httpWebReq.Accept = "application/xml";
var dataStream = httpWebReq.GetRequestStream();
dataStream.Write(bytePostData, 0, bytePostData.Length);
dataStream.Close();
var httpWebResponse = (HttpWebResponse)httpWebReq.GetResponse();
// Get the stream associated with the response.
var receiveStream = httpWebResponse.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
var readStream = new StreamReader(receiveStream,Encoding.Default);
responseContent = readStream.ReadToEnd();
httpWebResponse.Close();
}
You can just serialize to the request:
Serializer.Serialize(dataStream, obj);
And equally, you can deserialize from receiveStream, if you choose.
Note, however, that protobuf data is not text, and should not be treated as such - very bad things happen if you try that.

Decrypt bytes in asp.net

Following is my Java applet code
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] privKeyBytes = loadPriavteKeyFromFile(fileName, new String(txtPassword.getPassword()));
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes);
RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec);
Cipher rsaCipher = Cipher.getInstance("RSA");
rsaCipher.init(Cipher.ENCRYPT_MODE, privKey);
byte[] ciphertext = null;
ciphertext = rsaCipher.doFinal(xmlToSign.getBytes());
String urlString = "http://localhost:3290/SignApplet.aspx";
String senddata = Base64.encodeBase64String(ciphertext);
doHttpUrlConnectionAction(urlString,senddata.getBytes());
JOptionPane.showMessageDialog(this, "XML successfully signed and sent to server.");
on the server side i am trying too decrypt the byte using the public key
byte[] b;
b = Request.BinaryRead(178);
string encodedbytes = new System.Text.UTF8Encoding().GetString(b);
b = Convert.FromBase64String(encodedbytes);
Debug.WriteLine("decrypted bytes:" + new System.Text.UTF8Encoding().GetString(b));
// The path to the certificate.
string Certificate = #"c:\certs\lafa801114sd3.cer";
//// Load the certificate into an X509Certificate object.
X509Certificate cert = new X509Certificate(Certificate);
RSACryptoServiceProvider publicprovider = (RSACryptoServiceProvider)CertUtil.GetCertPublicKey(cert);
byte[] decbytes = publicprovider.Decrypt(b, false);
Debug.WriteLine("decrypted bytes" + new System.Text.UTF8Encoding().GetString(decbytes));
can any one help in following exception which i am getting at byte[] decbytes = publicprovider.Decrypt(b, false); line
A first chance exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll
Key does not exist.
and the certificate is not installed in nay key store.Also i can successfully decrypt the data using Java servlet .
i am using asp.net vs2010 on windows 7
the public and private keys are stored in separate files
Here are a few articles that might help you: Java RSA Encrypt - Decrypt .NET (which seems like what you are looking for)
and http://www.jensign.com/JavaScience/dotnet/RSAEncrypt/

Resources