The System.Security.Cryptography does include a DES Decode method, but the Windows.Security.Cryptography Namespace for Windows Phone 8.1 programming doesn't include any method for decoding DES.
I just found a Class, Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.DesCbc,
but I don't have any idea how to decrypt my DES encrypted String. I would appreciate every idea you have in your mind.
I think I've got it.
Code Snippet:
strAsymmetricAlgName = SymmetricAlgorithmNames.DesCbc;
SymmetricKeyAlgorithmProvider objAlgProv = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAsymmetricAlgName);
CryptographicKey keyPair = objAlgProv.CreateSymmetricKey(CryptographicBuffer.ConvertStringToBinary("xxx", BinaryStringEncoding.Utf8));
IBuffer val = CryptographicEngine.Decrypt(keyPair, CryptographicBuffer.ConvertStringToBinary(encodedData, BinaryStringEncoding.Utf8), null);
byte[] arr = val.ToArray();
string returnValue = System.Text.Encoding.UTF8.GetString(arr, 0, arr.Length);
I currently don't know the initialization vector that's why it is null.
I am still not 100 % sure if that is right.
The DES string is encrypted by a Java programm:
Cipher c = Cipher.getInstance( "DES" );
Key k = new SecretKeySpec( pass.getBytes(), "DES" );
c.init( Cipher.ENCRYPT_MODE, k );
OutputStream cos = new CipherOutputStream( out, c );
cos.write( bytes );
cos.close()
I can't find any Information about the initialization vector.
I just solved my Problem.
String strAsymmetricAlgName = SymmetricAlgorithmNames.DesEcbPkcs7;
SymmetricKeyAlgorithmProvider objAlgProv = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAsymmetricAlgName);
CryptographicKey keyPair = objAlgProv.CreateSymmetricKey(CryptographicBuffer.ConvertStringToBinary("key", BinaryStringEncoding.Utf8));
IBuffer str = CryptographicBuffer.CreateFromByteArray(encodedDataAsBytes);
IBuffer buf = CryptographicEngine.Decrypt(keyPair, str, null);
byte[] arr = buf.ToArray();
string returnValue = System.Text.Encoding.UTF8.GetString(arr, 0, arr.Length);
Related
Can anyone please let me know where I made a mistake in this code? This code is written in C#.NET. I need to write an algorithm for encoding a string using base64 format using C#.NET, and then decoded with base64_decode() using PHP. Please see the snippit below:
System.Security.Cryptography.RijndaelManaged rijndaelCipher = new System.Security.Cryptography.RijndaelManaged();
rijndaelCipher.Mode = System.Security.Cryptography.CipherMode.CBC;
rijndaelCipher.Padding = System.Security.Cryptography.PaddingMode.Zeros;
rijndaelCipher.KeySize = 256;
rijndaelCipher.BlockSize = 128;
byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(_key);
byte[] keyBytes = new byte[16];
int len = pwdBytes.Length;
if (len > keyBytes.Length) len = keyBytes.Length;
System.Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = keyBytes;
System.Security.Cryptography.ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = Encoding.UTF8.GetBytes(unencryptedString);
byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
return Convert.ToBase64String(cipherBytes);
I think your code sample is doing "encryption", and you want "encoding".
For encoding a string with Based64 in C#, it should look like this:
static public string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
And the PHP should look like this:
<?php
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str);
?>
I need to write an algorithm for encoding a string using base64 format using C#.net
That's actually quite easy. You don't need all that cryptography stuff that your copy-and-pasted code is using. The following suffices:
byte[] bytes = Encoding.UTF8.GetBytes(inputString);
string outputString = Convert.ToBase64String(bytes);
If you plan to send the data from C# to PHP via a HTTP GET request, don't forget to UrlEncode it. See this question for details:
C# to PHP base64 encode/decode
I am trying to decrypt a blowfish encrypted string with Bouncycastle in C#.
I am able to easily encrypt and decrypt my own string but, unfortunately, I have to decrypt a string that is generated by another system.
I AM able to recreate that same string with C# / Bouncycastle using the following but I have yet to decrypt it successfully.
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
...
static readonly Encoding Encoding = Encoding.UTF8;
public string BlowfishEncrypt(string strValue, string key)
{
try
{
BlowfishEngine engine = new BlowfishEngine();
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine);
KeyParameter keyBytes = new KeyParameter(Encoding.GetBytes(key));
cipher.Init(true, keyBytes);
byte[] inB = Encoding.GetBytes(strValue);
byte[] outB = new byte[cipher.GetOutputSize(inB.Length)];
int len1 = cipher.ProcessBytes(inB, 0, inB.Length, outB, 0);
cipher.DoFinal(outB, len1);
return BitConverter.ToString(outB).Replace("-", "");
}
catch (Exception)
{
return "";
}
}
Below is what I have for decryption at the moment. The line that fails with error "pad block corrupted" is cipher.DoFinal(out2, len2);
public string BlowfishDecrypt(string name, string keyString)
{
BlowfishEngine engine = new BlowfishEngine();
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine);
StringBuilder result = new StringBuilder();
cipher.Init(false, new KeyParameter(Encoding.GetBytes(keyString)));
byte[] out1 = Convert.FromBase64String(name);
byte[] out2 = new byte[cipher.GetOutputSize(out1.Length)];
int len2 = cipher.ProcessBytes(out1, 0, out1.Length, out2, 0);
cipher.DoFinal(out2, len2); //Pad block corrupted error happens here
String s2 = BitConverter.ToString(out2);
for (int i = 0; i < s2.Length; i++) {
char c = s2[i];
if (c != 0) {
result.Append(c.ToString());
}
}
return result.ToString();
}
Any idea what I might be doing wrong in BlowfishDecrypt()?
Note:
I converted the above (encrypt and decrypt) from a bouncycastle Java example I found somewhere; the encrypt works. The only difference I can see is that the Java example uses a StringBuffer where I use a StringBuilder.
Thank you, Artjom B!
byte[] out1 = Convert.FromBase64String(name);
Should have been
byte[] out1 = Hex.Decode(name);
From there, all I had to do was convert the Hex to a string.
I have used RSA Assymetric Key Encryption Algorithm in C# program (I have mentioned below) and I have to encrypt data through a java program. I want my java program to generate same encrypted key as like result of C# program.
Public Key:
<RSAKeyValue>
<Modulus>zgfXY1oUe4nyndX4qtobP1BMxtJ1/rfKU5csdAcWrSVu6ZaEAX3rL3cWnaSLzX4E1BNjSP9pjge6TH7UoaWqOQ==</Modulus>
<Exponent>AQAB</Exponent>
</RSAKeyValue>
C# Encryption Programme:
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(PublicKey); // read public key XML defined above
byte[] buffer = rsa.Encrypt(Encoding.UTF8.GetBytes(strToEncrypt), false);
string encryptedStr = HttpUtility.UrlEncode(buffer);// byteConverterGetString;
Java Encryption Programme:
byte[] modulusBytes = Base64.decode("zgfXY1oUe4nyndX4qtobP1BMxtJ1/rfKU5csdAcWrSVu6ZaEAX3rL3cWnaSLzX4E1BNjSP9pjge6TH7UoaWqOQ==");
byte[] exponentBytes = Base64.decode("AQAB");
BigInteger modulus = new BigInteger(1, modulusBytes );
BigInteger exponent = new BigInteger(1, exponentBytes);
RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(rsaPubKey);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] plainBytes = new String("Admin123").getBytes("UTF-8");
byte[] cipherData = cipher.doFinal( plainBytes );
String encryptedString = Base64.encodeBytes(cipherData);
System.out.println(URLEncoder.encode(encryptedString));
I tried above java program but it gives me result like:
o%2Bgw7%2BXhYxA9ltDV5zERsF4DyXgMTc%2Fgx82wRtT1xfR3suY0XBJLadp7bXjmSX7CplDVdoQyH05Jpqgkd%2B1G4A%3D%3D
and C# program generates like
%23E%03%c2%10)%40E%bf%7b%f9%11%87c0%12q%b9w%ba%2c%98%b4%b1%96%bc%ee%c5_%c9t%1e'%e71%85%b68t%00%3a%b7%d9%fb%a1%18%ba%10%b4%c3c%e1'*%3b%f6D%e2%cc6%82%80%f2%a6
so can anyone help me to correct my java program..
thanks
It seems to me that you're URL encoding two different things:
In Java you're encoding a Base64 encoded string, whereas
In C# you're doing it on a byte array
The result of these two different approaches will not be the same. Perhaps you should encode new String( cipherData ) in the Java part - or just compare the two byte[] arrays before encoding?
Cheers,
You are URLencoding diferent objects, just try this code:
byte[] modulusBytes = Base64.decode("zgfXY1oUe4nyndX4qtobP1BMxtJ1/rfKU5csdAcWrSVu6ZaEAX3rL3cWnaSLzX4E1BNjSP9pjge6TH7UoaWqOQ==");
byte[] exponentBytes = Base64.decode("AQAB");
BigInteger modulus = new BigInteger(1, modulusBytes );
BigInteger exponent = new BigInteger(1, exponentBytes);
RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(rsaPubKey);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] plainBytes = new String("Admin123").getBytes("UTF-8");
byte[] cipherData = cipher.doFinal( plainBytes );
String string = new String(cipherData);
System.out.println(URLEncoder.encode(string,"UTF-8"));
Can anyone please let me know where I made a mistake in this code? This code is written in C#.NET. I need to write an algorithm for encoding a string using base64 format using C#.NET, and then decoded with base64_decode() using PHP. Please see the snippit below:
System.Security.Cryptography.RijndaelManaged rijndaelCipher = new System.Security.Cryptography.RijndaelManaged();
rijndaelCipher.Mode = System.Security.Cryptography.CipherMode.CBC;
rijndaelCipher.Padding = System.Security.Cryptography.PaddingMode.Zeros;
rijndaelCipher.KeySize = 256;
rijndaelCipher.BlockSize = 128;
byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(_key);
byte[] keyBytes = new byte[16];
int len = pwdBytes.Length;
if (len > keyBytes.Length) len = keyBytes.Length;
System.Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = keyBytes;
System.Security.Cryptography.ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = Encoding.UTF8.GetBytes(unencryptedString);
byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
return Convert.ToBase64String(cipherBytes);
I think your code sample is doing "encryption", and you want "encoding".
For encoding a string with Based64 in C#, it should look like this:
static public string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
And the PHP should look like this:
<?php
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str);
?>
I need to write an algorithm for encoding a string using base64 format using C#.net
That's actually quite easy. You don't need all that cryptography stuff that your copy-and-pasted code is using. The following suffices:
byte[] bytes = Encoding.UTF8.GetBytes(inputString);
string outputString = Convert.ToBase64String(bytes);
If you plan to send the data from C# to PHP via a HTTP GET request, don't forget to UrlEncode it. See this question for details:
C# to PHP base64 encode/decode
I am trying to encrypt below base64 string in objective c .. Now i need to decrypt the output of below code in C# ... Please advice simplest way as i don't want to install any libs at server.
Please advice how can convert encripted string back to base64 using C# .
Thanks
My Objective c Code for encripting the base 64
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
SSCrypto *crypto;
NSString *password =#"abcdefghijklmnoqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnoqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyz";
NSData *seedData1 = [password dataUsingEncoding:NSUTF8StringEncoding];
crypto = [[SSCrypto alloc] initWithSymmetricKey:seedData1];
NSString *base64String = #"SUkqAAgAAAARAP4ABAABAAAAAAAAAAABAwABAAAAsAQAAAEBAwABAAAAEAIAAAIBAwABAAAAAQAAAAMBAwABAAAABAAAAAYBAwABAAAAAAAAAAoBAwABAAAAAQAAABEBBAABAAAACgEAABIBAwABAAAAAQAAABUBAwABAAAAAQAAABYBAwABAAAAEAIAABcBBAABAAAA3yUAABoBBQABAAAA2gAAABsBBQABAAAA4gAAACUBBAABAAAAAAAAACgBAwABAAAAAgAAADEBAgAgAAAA6gAAAAAAAADIAAAAAQAAAMgAAAABAAAAQ29tcHJlc3NlZCB3aXRoIFBBTklOSSBJbWFnZSsAAAAmoy1xRBcev/r/LSUkbRxE+cRxGpEdF0Rw2EcNhHDIBcufR2+R0XZJjI6OIj5HjCPRHR9F0R8wCmRwXI6I+eROjiNxpEdkdEdl2R8ujTMMuy+R0R8j5HZvNo2yOzcXyOiPkdFzLsjxHGRwbC5lwJQaQRDaCchYbAxEREREREREREREREREREREREREREREREREI0BuRww+RIyPFw2MSnIccp0yY58fgxZ5EcKaVhJdx//pL0OQwm5EA///WlgnWSAb/+q9KEgt4X+961qgtKkZJCMH/XlnojiSvNBUkmSCPZBiQlT//iR7pdK0tgnwzep3zv//DLtrqmuLDodf/X7w2lasnCq7CWPf/0l2a6sIIRSVjoLFf9/3sMJ+jrkIjeTonRHRtE6N5A86ohEQtF0d6Ijol0IiIiIiIiIiIi0IiIiIiOIiIiIiIiIiIiIiIiIiIiIgwjtb8tBIhXABABA==";
[crypto setClearTextWithString:base64String];
NSData *cipherText = [crypto encrypt:#"aes256"];
NSLog(#"Cipher text: '%#' using %#", [cipherText encodeBase64WithNewlines:NO], #"aes256");
NSLog(#" ");
[ pool release];
Below is my C# code for Decryption
public static string DecryptString(string base64StringToDecrypt, string passphrase)
{
//Set up the encryption objects
using (AesCryptoServiceProvider acsp = GetProvider(Encoding.Default.GetBytes(passphrase)))
{
byte[] RawBytes = Convert.FromBase64String(base64StringToDecrypt);
ICryptoTransform ictD = acsp.CreateDecryptor();
// TripleDES.
//RawBytes now contains original byte array, still in Encrypted state
//Decrypt into stream
MemoryStream msD = new MemoryStream(RawBytes, 0, RawBytes.Length);
CryptoStream csD = new CryptoStream(msD, ictD, CryptoStreamMode.Read);
//csD now contains original byte array, fully decrypted
//return the content of msD as a regular string
return (new StreamReader(csD)).ReadToEnd();
}
private static AesCryptoServiceProvider GetProvider(byte[] key)
{
AesCryptoServiceProvider result = new AesCryptoServiceProvider();
result.BlockSize = 128;
result.KeySize = 128;
result.Mode = CipherMode.CBC;
result.Padding = PaddingMode.PKCS7;
result.GenerateIV();
result.IV = new byte[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
byte[] RealKey = GetKey(key, result);
result.Key = RealKey;
// result.IV = RealKey;
return result;
}
private static byte[] GetKey(byte[] suggestedKey, SymmetricAlgorithm p)
{
byte[] kRaw = suggestedKey;
List<byte> kList = new List<byte>();
for (int i = 0; i < p.LegalKeySizes[0].MinSize; i += 8)
{
kList.Add(kRaw[(i / 8) % kRaw.Length]);
}
byte[] k = kList.ToArray();
return k;
}
Please advice if anything is missing or if i have done something gross wrong ..
I have lost more than 2 days in searching.
You can do this easily with the AesManaged class. See:
http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged.aspx