Quantcast

Bouncy castle AES cipher implementation on cross platform, .net c# and codename one

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Bouncy castle AES cipher implementation on cross platform, .net c# and codename one

sweety.preety86
This post has NOT been accepted by the mailing list yet.
Hello,

I am facing the issue with implementing bouncy castle AES/CBC/PKCS7 algorithm on cross platform from .net c# and codename one. i am not able to encrypt/decrypt text on cross platform. it can works on same platform.

Any one please suggest me on this. what could be the issue ?

i am using bouncy castle 1.5 api from codename one and 1.7 dll from .net c#.

i m using below code in .net to encypt/decrypt

  public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] key, byte[] nonSecretPayload = null)
            {
               
                //User Error Checks
                if (key == null || key.Length != KeyBitSize / 8)
                    throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "key");

                if (secretMessage == null || secretMessage.Length == 0)
                    throw new ArgumentException("Secret Message Required!", "secretMessage");

                //Non-secret Payload Optional
                nonSecretPayload = nonSecretPayload ?? new byte[] { };

                //Using random nonce large enough not to repeat
                var nonce = new byte[NonceBitSize / 8];
                Random.NextBytes(nonce, 0, nonce.Length);

                 
                //var cipher = new GcmBlockCipher(new AesFastEngine());
               
                PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine()));

                KeyParameter kp = new KeyParameter(key);
                ParametersWithIV piv = new ParametersWithIV(kp, new byte[16]);

                //var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload);

                cipher.Init(true, piv);

                //Generate Cipher Text With Auth Tag
                var cipherText = new byte[cipher.GetOutputSize(secretMessage.Length)];
                var len = cipher.ProcessBytes(secretMessage, 0, secretMessage.Length, cipherText, 0);
                cipher.DoFinal(cipherText, len);

                ////Assemble Message
                using (var combinedStream = new MemoryStream())
                {
                    using (var binaryWriter = new BinaryWriter(combinedStream))
                    {
                        //Prepend Authenticated Payload
                        binaryWriter.Write(nonSecretPayload);
                        //Prepend Nonce
                        binaryWriter.Write(nonce);
                        //Write Cipher Text
                        binaryWriter.Write(cipherText);
                    }
                    return combinedStream.ToArray();
                }

               
            }

            public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] key, int nonSecretPayloadLength = 0)
            {
                //User Error Checks
                if (key == null || key.Length != KeyBitSize / 8)
                    throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "key");

                if (encryptedMessage == null || encryptedMessage.Length == 0)
                    throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");

                using (var cipherStream = new MemoryStream(encryptedMessage))
                using (var cipherReader = new BinaryReader(cipherStream))
                {
                    //Grab Payload
                    var nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength);

                    //Grab Nonce
                    var nonce = cipherReader.ReadBytes(NonceBitSize / 8);

                    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine()));

                    //var cipher = new GcmBlockCipher(new AesFastEngine());
                    //var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload);

                    KeyParameter kp = new KeyParameter(key);
                    ParametersWithIV piv = new ParametersWithIV(kp, new byte[16]);

                    cipher.Init(false, piv);

                    //Decrypt Cipher Text
                    var cipherText = cipherReader.ReadBytes(encryptedMessage.Length - nonSecretPayloadLength - nonce.Length);
                    var plainText = new byte[cipher.GetOutputSize(cipherText.Length)];

                    try
                    {
                        var len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0);
                        cipher.DoFinal(plainText, len);

                    }
                    catch (InvalidCipherTextException)
                    {
                        //Return null if it doesn't authenticate
                        return null;
                    }

                    return plainText;
                }

            }

var PlainText = "Hello How are you !2#&*()% 123456@";
var EncryptionKey = "MAKV2SPBNI992122";
var cypherCBC = SimpleEncrypt(PlainText, EncryptionKey);
var decryptCBC = SimpleDecrypt(cypherCBC, EncryptionKey);


and using below code in java:


import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.CryptoException;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Base64;


public class Test
{
    private static PaddedBufferedBlockCipher cipher = null;
    public static void main(String[] args)
    {
        try
        {
            byte key[] = "MAKV2SPBNI992122".getBytes("UTF-8");
            byte[] iv = new byte[16];

            PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
                    new CBCBlockCipher(
                    new AESEngine()) );

            //Encryption
            String plainText = "Hello How are you !2#&*()% 123456@";
            byte[] plainData = plainText.getBytes("UTF-8");
            KeyParameter keyParam = new KeyParameter(key);
            CipherParameters ivAndKey = new ParametersWithIV(keyParam, iv);
            cipher.init(true, ivAndKey);
            byte[] ciptherBytes = cipherData(plainData); //48
            String cipherText = new String(Base64.encode(ciptherBytes), "UTF-8");//FileUtil.getStringFromByteArray(Base64.encode(ciptherBytes));


            System.out.println("encrypted >> "+cipherText);
            //Decryption

            byte[] cipherData = Base64.decode(cipherText);
            ivAndKey = new ParametersWithIV(keyParam, iv);
            cipher.init(false, ivAndKey);
            plainText = new String(cipherData(cipherData), "UTF-8");//FileUtil.getStringFromByteArray(cipherData(cipherData));

            System.out.println("decrypted >> "+plainText);


        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    private static byte[] cipherData(byte[] data)
            throws CryptoException
    {
        int minSize = cipher.getOutputSize(data.length);
        byte[] outBuf = new byte[minSize];
        int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
        int length2 = cipher.doFinal(outBuf, length1);
        int actualLength = length1 + length2;
        byte[] result = new byte[actualLength];
        System.arraycopy(outBuf, 0, result, 0, result.length);
        return result;
    }

can any one please help me out to find issue ?

Thanks in adv.



Loading...