1

We want to use Cipher encryption/decryption in windows phone 7. We have done for android using java. But when we try to develop in c# we struggling.

Our Java code:

public AES()
    {
        try
        {
            Security.addProvider(new BouncyCastleProvider());
            cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");

        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }


    public String doDecrypt(String key, String cipherText)
    {
        try
        {
            byte[] raw = key.getBytes(Charset.forName("UTF-8"));
            SecretKeySpec skey = new SecretKeySpec(raw, "AES");
            cipher.init(Cipher.DECRYPT_MODE, skey );
            return new String(cipher.doFinal(Base64.decode(cipherText,Base64.DEFAULT)), Charset.forName("UTF-8"));

        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String doEncrypt(String key, String plainText)
    {
        try
        {
            byte[] raw = key.getBytes(Charset.forName("UTF-8"));
            SecretKeySpec skey = new SecretKeySpec(raw, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, skey );
            return Base64.encodeToString(cipher.doFinal(plainText.getBytes(Charset.forName("UTF-8"))),Base64.DEFAULT);

        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Here we can encrypt and decryption.

Our C# code is:

public static byte[] EncryptWithAES(string dataToEncrypt, String Key)
        {

            byte[] encryptedData;

            byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes(Key);


            using (AesManaged aesEnc = new AesManaged())
            {
                aesEnc.Key = keyBytes;
                aesEnc.IV = new byte[16];

                //Create encryptor for converting
                ICryptoTransform encryptor = aesEnc.CreateEncryptor(aesEnc.Key, aesEnc.IV);


                using (MemoryStream memStream = new MemoryStream())
                {
                    using (CryptoStream crypStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter srmWriter = new StreamWriter(crypStream))
                        {

                            srmWriter.Write(dataToEncrypt);
                        }
                        encryptedData = memStream.ToArray();
                    }
                }
            }
            return encryptedData;
        }

But here we receive different output.

Java OP:-

OYbW6pI8mgqU5xOcfG8N92e28T9GUObtcea4XWqU0yQyJRULSLV/yjAzDh8gq9Hgj5K5OubZfdm/ /ts66eQMJYH4TBX0/hN5zPwQbdTWmfVU3dDyU2SyQek5zYcWW+OgnppL9jcMcJZg4pv2+q6x8w==

C# OP:-

OYbW6pI8mgqU5xOcfG8N9wXs2/gWMc6dcUSEoLXm3L5v9Ih9eN63xO31mXmEDLprIzusXaOS1rNNtBPi5I8FG3IukVgicagrkLul1vfa142z+XDULJXFmg5rxPa6iJzXqeZ6x3wxbfI3T/ZqGwxqbg==

We can not get the exact encrypted data like java. Please suggest or provide any links for Cipher encryption/decryption in windows phone 7.

Community
  • 1
  • 1
Vijay
  • 2,270
  • 3
  • 18
  • 33
  • Hi Alex.. It's working. But It showing different answer compare with android code. – Vijay Jan 08 '15 at 12:55
  • possible duplicate of [Encrypt/Decrypt using Bouncy Castle in C#](http://stackoverflow.com/questions/5910454/encrypt-decrypt-using-bouncy-castle-in-c-sharp) - per OP comment below. – Javier Feb 23 '15 at 11:21
  • @Javier.. Yes. I got solution from this link only. And I provide that link in my answer. – Vijay Feb 25 '15 at 11:20

2 Answers2

0

It works for me using LINQPad:

Console.Write(String.Join(" ", EncryptWithAES("hello", "AAECAwQFBgcICQoLDA0ODw==")));

yields:

91 209 208 157 151 41 81 76 99 8 248 231 34 62 204 1

Perhaps it's something specific for Window Phone 7 that is causing it not to work?

Key from https://stackoverflow.com/a/2919565/1185053

Community
  • 1
  • 1
dav_i
  • 25,285
  • 17
  • 94
  • 128
  • Yes.. It is working. But the encrypted values are differ. Our android/java code give different out put.. – Vijay Jan 08 '15 at 12:21
  • Android op is **VoJ5wW5GdGiM0ceMzmbz7Y+zGFExbm+XdSfnFvqBOkQWGaEGeMIn0ime4zXGTI97Ne imCbQa7tyPY/YKMJ6JBlPBZKan/FfII=** – Vijay Jan 08 '15 at 12:22
  • Take a look at http://stackoverflow.com/a/8126022/1185053, they seemed to have a similar problem. – dav_i Jan 08 '15 at 12:23
0

Finally I got solution from stackoverflow. I found the solution from here.. It is working fine..

The Solution is:-

Crypt Class:-

public class BCEngine
    {
        private Encoding _encoding;
        private IBlockCipher _blockCipher;
        private PaddedBufferedBlockCipher _cipher;
        private IBlockCipherPadding _padding;

        Pkcs7Padding pkcs = new Pkcs7Padding();

        public BCEngine(IBlockCipher blockCipher, Encoding encoding)
        {
            _blockCipher = blockCipher;
            _encoding = encoding;
        }

        public string Encrypt(string plain, string key)
        {
            byte[] result = BouncyCastleCrypto(true, _encoding.GetBytes(plain), key);
            return Convert.ToBase64String(result);
        }

        public string Decrypt(string cipher, string key)
        {
            byte[] result = BouncyCastleCrypto(false, Convert.FromBase64String(cipher), key);
            return _encoding.GetString(result, 0, result.Length);
        }

        private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, string key)
        {
            try
            {                                                                                   
                _cipher = _padding == null ? new PaddedBufferedBlockCipher(_blockCipher) : new PaddedBufferedBlockCipher(_blockCipher, _padding);
                byte[] keyByte = _encoding.GetBytes(key);
                _cipher.Init(forEncrypt, new KeyParameter(keyByte));
                return _cipher.DoFinal(input);
            }
            catch (Org.BouncyCastle.Crypto.CryptoException ex)
            {
                throw new CryptoException(ex.Message);
            }
        }

        public string AESEncryption(string plain, string key)
        {

            return Encrypt(plain, key);
        }

        public string AESDecryption(string cipher, string key)
        {
            return Decrypt(cipher, key);
        }

        public BCEngine()
        {
            _blockCipher = new AesEngine();
            _encoding = Encoding.UTF8;
            pkcs = new Pkcs7Padding();
            _padding = pkcs;
        }
    }

Now I can Call from anywhere to encrypt/decrypt the text.

Example:-

public partial class AesExample : PhoneApplicationPage
    {
        public AesExample()
        {
            InitializeComponent();
           string key = "b09f72a0lkb1lktb";

            string plainText = "Text To Encrypt";

            BCEngine bcEngine = new BCEngine();
            string encryptedString= bcEngine.Encrypt(plainText, key);
            Console.WriteLine("\n\nEncrypted String==> " + encryptedString);

            BCEngine bcEnginenew = new BCEngine();
            string decryptedString = bcEnginenew.Decrypt(encryptedString, key);
            Console.WriteLine("\n\nDecrypted String==> " + decryptedString);
        }
    }
Community
  • 1
  • 1
Vijay
  • 2,270
  • 3
  • 18
  • 33