Decrypt bytes in asp.net - 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/

Related

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.

APNS push notification error - A call to SSPI failed, see inner exception

I know that this questions has been asked before, but none of that seems to help me.
I am trying to send push notifications from my asp.net application but i get the following error:
"A call to SSPI failed, see inner exception." System.Exception {System.Security.Authentication.AuthenticationException}
"The message received was unexpected or badly formatted" System.Exception {System.ComponentModel.Win32Exception}
And here is the code:
int port = 2195;
String hostname = "gateway.sandbox.push.apple.com";
//load certificate
string certificatePath = HostingEnvironment.ApplicationPhysicalPath + "cert.pem";
string certificatePassword = "xxxxxxx";
X509Certificate2 clientCertificate = new X509Certificate2(certificatePath, certificatePassword);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
TcpClient client = new TcpClient(hostname, port);
SslStream sslStream = new SslStream(
client.GetStream(),
false,
null,
null
);
try
{
sslStream.AuthenticateAsClient(hostname, certificatesCollection, System.Security.Authentication.SslProtocols.Tls, false);
}
catch (AuthenticationException ex)
{
client.Close();
}
// Encode a test message into a byte array.
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((byte)0); //The command
writer.Write((byte)0); //The first byte of the deviceId length (big-endian first byte)
writer.Write((byte)32); //The deviceId length (big-endian second byte)
String deviceId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
writer.Write((deviceId.ToUpper().ToArray()));
String payload = "{\"aps\":{\"alert\":\"Test\",\"badge\":14}}";
writer.Write((byte)0); //First byte of payload length; (big-endian first byte)
writer.Write((byte)payload.Length); //payload length (big-endian second byte)
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
writer.Write(b1);
writer.Flush();
byte[] array = memoryStream.ToArray();
sslStream.Write(array);
sslStream.Flush();
// Close the client connection.
client.Close();
Is there a problem with my certificate, or why could this be happening?
Am i supposed to use a p12 file? If so, how can i get the p12 file if i have the .pem file?
I am developing this on windows, but i am supposed to register the certificate somewhere in windows?
Best regards,
Marius.

Encrypt in .Net and decrypt in AS3

I need to encrypt some files in ASP.net and decrypt them in a flash application built with Action Script 3.
AS3 developer found a lib call AS3crypto which seems like a good one for AS3. The idea is encrypt and decrypt using same key. Symmetrical Encryption?
But I am struggling to find .Net equivalent that would use same algorithm for encryption.
I have tried RC4 example from 4guysfromrolla blog which works too slow for me.
I have tried AES on this example (http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=vs.100).aspx) which works great on .Net but I can't seem to decrypt using AS3crypto to get the same file back. AS3crypto doesn't seem to like to have IV for decryption. I can only supply one key.
So far I am lost. How can I encrypt a file in .Net and decrypt it back in AS3 to get the same file back?
Notice: use 16 char length for both Key and IV, ex: Key: 1234567890123456 and IV: 9876543210654321
Here is C# code
public byte[] Encrypt(byte[] someData, string KEY, string IV)
{
//preparing
byte[] keyBytes = Encoding.UTF8.GetBytes(KEY);
byte[] ivBytes = Encoding.UTF8.GetBytes(IV);
//here goes encryption
RijndaelManaged rijndaelManaged = new RijndaelManaged();
rijndaelManaged.Key = keyBytes;
rijndaelManaged.IV = ivBytes;
rijndaelManaged.BlockSize = 128;
rijndaelManaged.Mode = CipherMode.CBC;
ICryptoTransform encryptor = rijndaelManaged.CreateEncryptor(rijndaelManaged.Key, rijndaelManaged.IV);
byte[] result = null;
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(someData, 0, someData.Length);
cryptoStream.FlushFinalBlock();
result = memoryStream.ToArray();
}
}
return result;
}
And here is AS3 code using AS3Crypto library
private function decrypt(input:ByteArray, decrKey:String, decrIV:String):ByteArray
{
var key:ByteArray = Hex.toArray(Hex.fromString(decrKey));
var pad:IPad = new NullPad();
var aes:ICipher = Crypto.getCipher("aes-cbc", key, pad);
var ivmode:IVMode = aes as IVMode;
ivmode.IV = Hex.toArray(Hex.fromString(decrIV));
aes.decrypt(input);
return input;
}

standalone java program to decrypt password

I have to write a standalone java program to decrypt password from file,using Symmetric key for password decryption. I didn't work with encryption and decryption before. can anybody give any suggestion how can i do this.I need your guidance.
maybe you need something like this
private static final String ALGORITHM = "AES";
....
....
Key key = new SecretKeySpec(new String("here is your symmetric key").getBytes(), ALGORITHM);
Cipher c = Cipher.getInstance(ALGORITHM);
//dencript mode (passes the key)
c.init(Cipher.DECRYPT_MODE, key);
//Decode base64 to get bytes
byte[] encBytes = new BASE64Decoder().decodeBuffer(encryptedValue);
// Decrypt
byte[] plainTxtBytes = c.doFinal(encBytes);
// Decode
String decryptedValue = new String(plainTxtBytes , "UTF-8");
Here are some resources:
http://www.javamex.com/tutorials/cryptography/symmetric.shtml
http://www.java2s.com/Code/Java/Security/EncryptionandDecryptionusingSymmetricKeys.htm
http://www.flexiprovider.de/examples/ExampleCrypt.html (This uses files as well)

Decrypt/Verify signed data using public certificate 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

Resources