Encrypt in C# and decrypt in Flex - c#

I need to decrypt some data in Flex that is encrypted in C# and written to a file.
I settled on blowfish for simplicity's sake using the as3crypto As3 library and Bruce Schneier C# library.
AS3 as3crypto link
Bruce Schneier C# blowfish link
I can get a short string to encrypt in C# and decrypt in Flex fine
however longer strings just fail to produce results and I do not know what I am missing?
C#:
string reportstring = "watson?";
BlowFish b = new BlowFish("04B915BA43FEB5B6");
string cipherText = b.Encrypt_ECB(reportstring);
String plainText = b.Decrypt_ECB(cipherText);
AS3:
var txt:String = "watson?";
var key:ByteArray = Hex.toArray("04B915BA43FEB5B6");
var blowfish:BlowFishKey = new BlowFishKey(key);
var dataBytes:ByteArray = new ByteArray();
dataBytes=Hex.toArray(Hex.fromString(txt));
blowfish.encrypt(dataBytes);
blowfish.decrypt(dataBytes);
Update, some samples
working
encrypt string = "watson?"
C# produces: 1514ea36fecfd5f5
AS3 produces: 1514ea36fecfd5f5
not working
encrypt string = "whats up watson?"
C# produces: 3ea9808a4b9f74aaa8e54fe682947673
AS3 produces: 3ea9808a4b9f74aa20776174736f6e3f
which is very similar but not matching
if I decrypt the AS3 cipher in C# I get :
whats up?`r???
if I decrypt the C# cipher in AS3 I get :
whats up¨åO悔vs

The AS3 code seems to be incorrect. Working example code:
import com.hurlant.util.Hex;
import com.hurlant.util.Base64;
import com.hurlant.crypto.Crypto;
import flash.utils.ByteArray;
import com.hurlant.crypto.symmetric.IPad;
import com.hurlant.crypto.symmetric.ICipher;
import com.hurlant.crypto.symmetric.NullPad;
import com.hurlant.crypto.symmetric.BlowFishKey;
function encrypt($text:String, $cryptKey:ByteArray):String
{
var iPad:IPad = new NullPad();
var crypt = Crypto.getCipher('blowfish-ecb',$cryptKey,iPad);
var cryptText:ByteArray = new ByteArray();
cryptText.writeUTFBytes( $text );
crypt.encrypt( cryptText );
trace( Hex.fromArray( cryptText ) );
return null;
}
var txt:String = "whats up watson?";
var key:ByteArray = Hex.toArray("04B915BA43FEB5B6");
encrypt(txt, key);

Answer to "how do I decrypt the string afterwards":
var encodedtxt:String = Hex.fromArray(cryptText);
cryptText = Hex.toArray(encodedtxt);
crypt.decrypt(cryptText);

package
{
import com.hurlant.crypto.Crypto;
import com.hurlant.crypto.prng.Random;
import com.hurlant.crypto.symmetric.ICipher;
import com.hurlant.util.Base64;
import com.hurlant.util.Hex;
import flash.utils.ByteArray;
import mx.utils.Base64Decoder;
import mx.utils.Base64Encoder;
public class EncryptionManager
{
public function EncryptionManager()
{
}
public function enCrypt(data:String, keyStr:String):String
{
var key:ByteArray;
var fileBytes:ByteArray = Hex.toArray(Hex.fromString(data));
key = Hex.toArray(Hex.fromString(keyStr));
var aes:ICipher = Crypto.getCipher("blowfish-ecb", key, Crypto.getPad("pkcs5"));
aes.encrypt(fileBytes);
var enc:Base64Encoder = new Base64Encoder();
enc.encodeBytes(fileBytes);
var result:String = enc.flush();
return result;
}
public function deCrypt(data:String, keyStr:String):String
{
var key:ByteArray;
var dec:Base64Decoder = new Base64Decoder();
dec.decode(data);
var fileBytes:ByteArray = dec.toByteArray();
key = Hex.toArray(Hex.fromString(keyStr));
var aes:ICipher = Crypto.getCipher("blowfish-ecb", key, Crypto.getPad("pkcs5"));
aes.decrypt(fileBytes);
return fileBytes.toString();
}
}
}
Try out this Class that might solve your problem.

Related

How to encrypt plain text using RSA asymmetric encryption

I am working on an application where I need to encrypt plain text using the RSA algorithm. I encrypt the plain text but it is not working as it gives Error Decoding Text. Basically, I am calling third-party API which gives me the error. When I encrypt my text using this link reference link it works perfectly fine so I think I am doing something wrong. Here is my code
public static string Encryption(string strText)
{
var publicKey = #"<RSAKeyValue><Modulus>MIIDSjCCAjKgAwIBAgIEWrJUKTANBgkqhkiG9w0BAQsFADBmMQswCQYDVQQGEwJE
RTEPMA0GA1UECAwGQmF5ZXJuMQ8wDQYDVQQHDAZNdW5pY2gxDzANBgNVBAoMBkxl
eGNvbTEkMCIGA1UEAwwbQWdyb3BhcnRzX0RNU19CYXNrZXRfVXBsb2FkMCAXDTE4
MDMyMTEyNDYzM1oY################################################
A1UECAwG########################################################
################################################################
WaOa0parvIrMk9/#################################################
NCIeGu+epwg8oUCr6Wd0BNATNjt8Tk64pgQvhdX9/KRDSC8V4QCJBiE3LQPHUVdN
nWRixrcOpucMo6m9PPegjnicn/rBKdFZLfJqLHHm+TrHrNCsEQIDAQABMA0GCSqG
SIb3DQEBCwUAA4IBAQBGwlNnDh2UaZphkEf70MPhySFVnTnLSxUFuwuWaDu8l7YP
zBMeJxcNk3HNiXPeba03GQBj+JqGAwDALJLityGeGEzlESfv/BsgQOONt+lAJUjs
b7+vr2e5REE/dpJZ1kQRQC##########################################
np+GstsdWjIWbL6L6VoqU18qLO5b0k8OoEMsP3akUTcj0w8JwD5V5iLqDhnv1aXK
kntkd/QmVCY6zlzH/dnTh8RNO2CfRtB1GEzNnkJB</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
var testData = Encoding.UTF8.GetBytes(strText);
using (var rsa = new RSACryptoServiceProvider(1024))
{
try
{
rsa.FromXmlString(publicKey);
byte[] data = Encoding.UTF8.GetBytes(strText);
byte[] cipherText = rsa.Encrypt(data,true);
var base64Encrypted = Convert.ToBase64String(cipherText);
return base64Encrypted;
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
}
}
}
Here is my public key. I am using an RSA certificate. I am passing the certificate key to the module tag here is my key. I think I might be using it wrong.
-----BEGIN CERTIFICATE-----
MIIDSjCCAjKgAwIBAgIEWrJUKTANBgkqhkiG9w0BAQsFADBmMQswCQYDVQQGEwJE
RTEPMA0GA1UECAwGQmF5ZXJuMQ8wDQYDVQQHDAZNdW5pY2gxDzANBgNVBAoMBkxl
eGNvbTEkMCIGA1UEAwwbQWdyb3BhcnRzX0RNU19CYXNrZXRfVXBsb2FkMCAXDTE4
MDMyMTEyNDYzM1oY################################################
A1UECAwG########################################################
################################################################
WaOa0parvIrMk9/#################################################
NCIeGu+epwg8oUCr6Wd0BNATNjt8Tk64pgQvhdX9/KRDSC8V4QCJBiE3LQPHUVdN
nWRixrcOpucMo6m9PPegjnicn/rBKdFZLfJqLHHm+TrHrNCsEQIDAQABMA0GCSqG
SIb3DQEBCwUAA4IBAQBGwlNnDh2UaZphkEf70MPhySFVnTnLSxUFuwuWaDu8l7YP
zBMeJxcNk3HNiXPeba03GQBj+JqGAwDALJLityGeGEzlESfv/BsgQOONt+lAJUjs
b7+vr2e5REE/dpJZ1kQRQC##########################################
np+GstsdWjIWbL6L6VoqU18qLO5b0k8OoEMsP3akUTcj0w8JwD5V5iLqDhnv1aXK
kntkd/QmVCY6zlzH/dnTh8RNO2CfRtB1GEzNnkJB
-----END CERTIFICATE-----
Any help would be highly appreciated. The encryption through this code is not working. But when I used the mentioned link above and pass this key it worked fine.
The answer to my question is here. I solved my problem and I am posting it because maybe someone in the future will have the same issue I am facing and what mistake I did to achieve my requirements.
Findings
I found during my research there is a difference between Public Key and Certificate. I miss understood the terminology I was passing a certificate instead of passing Public Key for encryption. So one of the community members #Topaco basically redirected me to the correct path which helps me to solve my problem. There are steps involved if you have a public key then you can achieve encryption but if you have a certificate then first you need to get the public key by using the method GetRSAPublicKey. When you got your public key in XML form then you pass it to encrypt method to get your result.
Here is the coding
Program.cs
var x509 = new X509Certificate2(File.ReadAllBytes(#"D:\xyz.cer"));
string xml = x509.GetRSAPublicKey().ToXmlString(false);
var result = EncryptUtil.Encryption("start01!", xml);
Utility Class
public static string Encryption(string strText, string publicKey)
{
using (var rsa = new RSACryptoServiceProvider(1024))
{
try
{
rsa.FromXmlString(publicKey);
byte[] data = Encoding.UTF8.GetBytes(strText);
byte[] cipherText = rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1);
var base64Encrypted = Convert.ToBase64String(cipherText);
return base64Encrypted;
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
}
So you can achieve encryption using the above code you need to pass RSAEncryptionPadding.Pkcs1 for encryption.
#happycoding #keephelping

C# ECKey analog on PHP

What will be analog of this code in PHP? I am not able to port this piece of code on PHP.
internal void GenerateKeyPair()
{
ecKey = new ECKey();
GeneratedPublicKey = new ECPublicKey()
{
X = ecKey.X,
Y = ecKey.Y,
CurveOId = ecKey.CurveOId
};
}
openssl_pkey_new() can generate a private key, see the Documentation for an example with private/public key usage.

RSA: Encrypt password in javascript but failed to decrypt that in C#

I want apply the RSA encryption to my project, but encountered some troubles:
First, I have download the JavaScripts library from
http://www.ohdave.com/rsa/ ,and add reference to my project;
Second, I have define the RSA object and code to initialize that:
internal RSACryptoServiceProvider Rsa
{
get
{
if (HttpContext.Cache["Rsa"] != null)
{
RSACryptoServiceProvider encryptKeys = (RSACryptoServiceProvider)HttpContext.Cache["Rsa"];
return encryptKeys;
}
else
{
return new RSACryptoServiceProvider(1024);
}
}
set
{
HttpContext.Cache.Remove("Rsa");
HttpContext.Cache.Insert("Rsa", value);
}
}
public ActionResult SignUp()
{
this.Rsa = Security.GetRsa();
RSAParameters param= this.Rsa.ExportParameters(true);
//this will bind to view
TempData["exponent"] = Util.BytesToHexString(param.Exponent);
TempData["key"] = Util.BytesToHexString(param.Modulus);
UserInfo user = new UserInfo();
user.Birthday = DateTime.Now.Date;
return View(user);
}
private RSACryptoServiceProvider GetRsa()
{
RSACryptoServiceProvider Rsa = new RSACryptoServiceProvider(1024);
return Rsa;
}
3.then, on JavaScript side , I have code, it encrypt the password user input and the bind it control:
var hash = document.getElementById("Pwd").value;
var exponent = document.getElementById("exponent").innerHTML;
var rsa_n = document.getElementById("key").innerHTML;
setMaxDigits(131);
var key = new RSAKeyPair(exponent, "", rsa_n);
hash = encryptedString(key, "111");
document.getElementById("Pwd").value = hash;
document.getElementById("Pwd2").value = hash;
document.getElementById("error").innerHTML = "";
document.getElementById("submit").click();
4.when user click submit, my C# code get the encrypted pwd string and try to decrypt it but failed with exception: bad data:
[HttpPost]
public ActionResult SignUp(UserInfo user)
{
user.UserId = user.UserId.ToLower(); //ignore case
user.UserGUID = Guid.NewGuid();
user.CreatedDate = DateTime.Now;
user.IsEnabled = false;
user.Pwd = Convert.ToBase64String(Rsa.Decrypt(Util.HexStringToBytes(user.Pwd), false));//Exception:Rsa.Decrypt throw bad data exception
who do you know how to fix it? thank you in advance.
I had a very similar problem in that most of the JavaScript based RSA encryption solutions wasn't "compatible" with .NET's implementation.
Almost all the implementations I found online had one or both of the following items causing the incompatibility with .NET's implementation.
The byte order encoding in JavaScript is different to the byte order that .NET used. This is a biggie as for example a string is represented with a different order of bytes in JS than it is in .NET so you'll need to convert before encrypting and after decrypting. I believe it's enough to just reverse the byte order to match .NET, but don't quote me on that.
Padding was different: .NET uses OAEP padding by default for RSA so the JS implementation of RSA should support the same padding too. I believe OAEP padding is also called PKCS#1 v2.0 padding, but don't quote me on that either.
Aside: I found an amazing JS library, called JavaScript.NET (from jocys.com) that mirrors tons of the .NET BCL functionality, including the RSA implementation, such that I could even use similar classes, properties and methods. Have a look at this. I can confirm it works with .NET RSA implementation. Give it a go - here are some links for it:
Jocys JS.NET Code Project demo
Jocys JS.NET Download
Hth

Can anyone give me an example of using BouncyCastle to import .pem public DSA key into c#?

I am trying co import a .pem key into c#, and I've found a library, which does that: BouncyCastle
I've created a code, which loads public key and is supposed to load the data into DSACryptoServiceProvider:
DSA dsa;
using (StreamReader rdr = new StreamReader(#"pubkey.pem"))
{
PemReader pr = new PemReader(rdr);
DsaPublicKeyParameters o = pr.ReadObject() as DsaPublicKeyParameters;
CspParameters prm = new CspParameters(13);
prm.Flags = System.Security.Cryptography.CspProviderFlags.UseMachineKeyStore;
//o.Parameters.
dsa = new DSACryptoServiceProvider(prm);
DSAParameters dp = new DSAParameters();
dp.G = o.Parameters.G.ToByteArray();
dp.P = o.Parameters.P.ToByteArray();
dp.Q = o.Parameters.Q.ToByteArray();
dp.Y = o.Y.ToByteArray();
if (o.Parameters.ValidationParameters != null)
{
dp.Counter = o.Parameters.ValidationParameters.Counter;
dp.Seed = o.Parameters.ValidationParameters.GetSeed();
}
//todo: missing: J, X?
dsa.ImportParameters(dp);
}
it crashes on dsa.ImportParameters(dp); with following exception: Cryptographic exception:bad data.
What should I change for this to work?
You need to use the ToByteArrayUnsigned method instead of plain ToByteArray one as otherwise there are cases where the byte array representation ends up with a leading zero byte which breaks everything :)

Convert SHA Hash Computation in Python to C#

Can someone please help me convert the following two lines of python to C#.
hash = hmac.new(secret, data, digestmod = hashlib.sha1)
key = hash.hexdigest()[:8]
The rest looks like this if you're intersted:
#!/usr/bin/env python
import hmac
import hashlib
secret = 'mySecret'
data = 'myData'
hash = hmac.new(secret, data, digestmod = hashlib.sha1)
key = hash.hexdigest()[:8]
print key
Thanks
You could use the HMACSHA1 class to compute the hash:
class Program
{
static void Main()
{
var secret = "secret";
var data = "data";
var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(secret));
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(data));
Console.WriteLine(BitConverter.ToString(hash));
}
}

Categories

Resources