8

Cross Platform AES 256 GCM Encryption / Decryption - CodeProject

 2 years ago
source link: https://www.codeproject.com/Articles/1265115/Cross-Platform-AES-256-GCM-Encryption-Decryption
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Introduction

While working in security, identity management and data protection fields for a while, I found a very few working examples in the public domain on cross platform encryption based on AES 256 GCM algorithm. This is the same algorithm used by Google when you access Gmail, etc.

This article may help you implement very strong cross platform encryption / decryption. The sample code is in C++, C# and Java. However, Java through JNI (Java Native Interface) and C# through COM, can call native C++ code, which in my testing appears to be much faster as compared to pure Java or C# implementations. Still there are times when one wants to do it without calling a native C++ layer.

For C#, to achieve AES 256 GCM encryption, I used Bouncy Castle cryptographic libraries. The code snippets available with this article work perfectly for encryption and decryption across various platforms. I tested it to be working on Linux (using Mono Framework) and Windows.

For C++ layer, I utilized Crypto++. This library is cross platform compatible (Windows, Linux and others like Solaris etc.). Crypto++ is a robust and very well implemented open source cryptographic library.

This article is not intended for beginners nor is it to teach AES GCM algorithm.

This article sort of provides you a sample code to implement with your own modifications.

C++ is a little complicated. Download Crypto++ source code. Create a console project and add existing Crypto++ project to solution. Then set your console project as startup project and set build dependency order.

Copy paste code from the article and correct header files paths (like pch.h) You can add source code directories in project properties as well to fix paths. In the same way, you can correct path to Crypto++ compiled library or add it to your project properties.

Another purpose of this article is to combine all three major programming languages sample code at one place. You don't have to search through thousands of individual samples, some of them do not work as intended. The code sample here works without any issue.

Background

Cross Platform AES 256 GCM Encryption and Decryption (C++, C# and Java)

You can also read more about Crypto++ AES GCM implementation or algorithm itself here and here.

Similarly, details about BouncyCastle can be found here.

BouncyCastle .NET used in C# code is here.

GitHub

C# Version
C++ Version
Java Version

Using the Code

For C#

Please add reference:

BouncyCastle.Crypto (BouncyCastle.Crypto.dll)

https://www.nuget.org/packages/BouncyCastle.Crypto.dll/

Image 1

C# Test Console Application

Shrink ▲   Copy Code
using System;
namespace TestAES_GCM_256
{
    class Program
    {
        static void Main(string[] args)
        {
            //Generate and dump KEY so we could use again
            //Console.WriteLine(AesGcm256.toHex(AesGcm256.NewKey()));

            //Generate and dump IV so we could use again
            //Console.WriteLine(AesGcm256.toHex(AesGcm256.NewIv()));

            //Console.ReadKey();


            //using above code these key and iv was generated
            string hexKey = "2192B39425BBD08B6E8E61C5D1F1BC9F428FC569FBC6F78C0BC48FCCDB0F42AE";
            string hexIV = "E1E592E87225847C11D948684F3B070D";

            string plainText = "Test encryption and decryption";
            Console.WriteLine("Plain Text: " + plainText);

            //encrypt - result base64 encoded string
            string encryptedText = AesGcm256.encrypt
                  (plainText, AesGcm256.HexToByte(hexKey), AesGcm256.HexToByte(hexIV));
            Console.WriteLine("Encrypted base64 encoded: " + encryptedText);

            //decrypt - result plain string
            string decryptedText = AesGcm256.decrypt
                  (encryptedText, AesGcm256.HexToByte(hexKey), AesGcm256.HexToByte(hexIV));
            Console.WriteLine("Decrypted Text: " + decryptedText);

            if (plainText.Equals(decryptedText))
            {
                Console.WriteLine("Test Passed");
            }
            else
            {
                Console.WriteLine("Test Failed");
            }

            /* Console Output
            Plain Text: Test encryption and decryption
            Encrypted base64 encoded: A/boAixWJKflKviHp2cfDl6l/xn1qw2MsHcKFkrOfm2XOVmawIFct4fS1w7wKw==
            Decrypted Text: Test encryption and decryption
            Test Passed
            Press any key to continue . . .
            */
        }
    }
}

C# Encryption / Decryption Class

Shrink ▲   Copy Code
using System;
using System.Text;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;

namespace TestAES_GCM_256
{
    public class AesGcm256
    {
        private static readonly SecureRandom Random = new SecureRandom();

        // Pre-configured Encryption Parameters
        public static readonly int NonceBitSize = 128;
        public static readonly int MacBitSize = 128;
        public static readonly int KeyBitSize = 256;

        private AesGcm256() { }

        public static byte[] NewKey()
        {
            var key = new byte[KeyBitSize / 8];
            Random.NextBytes(key);
            return key;
        }

        public static byte[] NewIv()
        {
            var iv = new byte[NonceBitSize / 8];
            Random.NextBytes(iv);
            return iv;
        }

        public static Byte[] HexToByte(string hexStr)
        {
            byte[] bArray = new byte[hexStr.Length / 2];
            for (int i = 0; i < (hexStr.Length / 2); i++)
            {
                byte firstNibble = Byte.Parse(hexStr.Substring((2 * i), 1), 
                                   System.Globalization.NumberStyles.HexNumber); // [x,y)
                byte secondNibble = Byte.Parse(hexStr.Substring((2 * i) + 1, 1), 
                                    System.Globalization.NumberStyles.HexNumber);
                int finalByte = (secondNibble) | (firstNibble << 4); // bit-operations 
                                                                     // only with numbers, not bytes.
                bArray[i] = (byte)finalByte;
            }
            return bArray;
        }

        public static string toHex(byte[] data)
        {
            string hex = string.Empty;
            foreach (byte c in data)
            {
                hex += c.ToString("X2");
            }
            return hex;
        }

        public static string toHex(string asciiString)
        {
            string hex = string.Empty;
            foreach (char c in asciiString)
            {
                int tmp = c;
                hex += string.Format("{0:x2}", System.Convert.ToUInt32(tmp.ToString()));
            }
            return hex;
        }

        public static string encrypt(string PlainText, byte[] key, byte[] iv)
        {
            string sR = string.Empty;
            try
            {
                byte[] plainBytes = Encoding.UTF8.GetBytes(PlainText);

                GcmBlockCipher cipher = new GcmBlockCipher(new AesFastEngine());
                AeadParameters parameters = 
                             new AeadParameters(new KeyParameter(key), 128, iv, null);

                cipher.Init(true, parameters);

                byte[] encryptedBytes = new byte[cipher.GetOutputSize(plainBytes.Length)];
                Int32 retLen = cipher.ProcessBytes
                               (plainBytes, 0, plainBytes.Length, encryptedBytes, 0);
                cipher.DoFinal(encryptedBytes, retLen);
                sR = Convert.ToBase64String(encryptedBytes, Base64FormattingOptions.None);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            return sR;
        }

        public static string decrypt(string EncryptedText, byte[] key, byte[] iv)
        {
            string sR = string.Empty;
            try
            {
                byte[] encryptedBytes = Convert.FromBase64String(EncryptedText);

                GcmBlockCipher cipher = new GcmBlockCipher(new AesFastEngine());
                AeadParameters parameters = 
                          new AeadParameters(new KeyParameter(key), 128, iv, null);
                //ParametersWithIV parameters = new ParametersWithIV(new KeyParameter(key), iv);

                cipher.Init(false, parameters);
                byte[] plainBytes = new byte[cipher.GetOutputSize(encryptedBytes.Length)];
                Int32 retLen = cipher.ProcessBytes
                               (encryptedBytes, 0, encryptedBytes.Length, plainBytes, 0);
                cipher.DoFinal(plainBytes, retLen);

                sR = Encoding.UTF8.GetString(plainBytes).TrimEnd("\r\n\0".ToCharArray());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            return sR;
        }
    }
}  

For Java

Please add the following JAR to your Java project or class path:

bcprov-jdk15on-160.jar

Image 2

Java Test Console Application

Shrink ▲   Copy Code
public class TestAes256GCM {

    public static void main(String[] args) {
            //Generate and dump KEY so we could use again
            //System.out.println(AesGcm256.toHex(AesGcm256.NewKey()));

            //Generate and dump IV so we could use again
            //System.out.println(AesGcm256.toHex(AesGcm256.NewIv()));

            //Console.ReadKey();

            //using above code these key and iv was generated
            String hexKey = "2192B39425BBD08B6E8E61C5D1F1BC9F428FC569FBC6F78C0BC48FCCDB0F42AE";
            String hexIV = "E1E592E87225847C11D948684F3B070D";

            String plainText = "Test encryption and decryption";
            System.out.println("Plain Text: " + plainText);

            //encrypt - result base64 encoded string
            String encryptedText = AesGcm256.encrypt
                    (plainText, AesGcm256.HexToByte(hexKey), AesGcm256.HexToByte(hexIV));
            System.out.println("Encrypted base64 encoded: " + encryptedText);

            //decrypt - result plain string
            String decryptedText = AesGcm256.decrypt
                    (encryptedText, AesGcm256.HexToByte(hexKey), AesGcm256.HexToByte(hexIV));
            System.out.println("Decrypted Text: " + decryptedText);

            if (plainText.equals(decryptedText))
            {
                System.out.println("Test Passed");
            }
            else
            {
                System.out.println("Test Failed");
            }

            /* Console Output
            Plain Text: Test encryption and decryption
            Encrypted base64 encoded: 
                   A/boAixWJKflKviHp2cfDl6l/xn1qw2MsHcKFkrOfm2XOVmawIFct4fS1w7wKw==
            Decrypted Text: Test encryption and decryption
            Test Passed
            Press any key to continue . . .
            */
    }    
}

Java Encryption / Decryption Class

Shrink ▲   Copy Code
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.util.Base64;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.AESFastEngine;
import org.bouncycastle.crypto.modes.GCMBlockCipher;
import org.bouncycastle.crypto.params.AEADParameters;
import org.bouncycastle.crypto.params.KeyParameter;

public class AesGcm256 {

    private static final SecureRandom SECURE_RANDOM = new SecureRandom();

    // Pre-configured Encryption Parameters
    public static int NonceBitSize = 128;
    public static int MacBitSize = 128;
    public static int KeyBitSize = 256;

    private AesGcm256() {
    }

    public static byte[] NewKey() {
        byte[] key = new byte[KeyBitSize / 8];
        SECURE_RANDOM.nextBytes(key);
        return key;
    }

    public static byte[] NewIv() {
        byte[] iv = new byte[NonceBitSize / 8];
        SECURE_RANDOM.nextBytes(iv);
        return iv;
    }

    public static byte[] HexToByte(String hexStr) {
        int len = hexStr.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2)
        {
            data[i / 2] = (byte) ((Character.digit(hexStr.charAt(i), 16) << 4)
                    + Character.digit(hexStr.charAt(i + 1), 16));
        }
        return data;
    }

    public static String toHex(byte[] data) {
        final StringBuilder builder = new StringBuilder();
        for (byte b : data) {
            builder.append(Integer.toString(b, 16));
        }
        return builder.toString();
    }

    public static String encrypt(String PlainText, byte[] key, byte[] iv) {
        String sR = "";
        try {
            byte[] plainBytes = PlainText.getBytes("UTF-8");

            GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
            AEADParameters parameters = 
                        new AEADParameters(new KeyParameter(key), MacBitSize, iv, null);

            cipher.init(true, parameters);

            byte[] encryptedBytes = new byte[cipher.getOutputSize(plainBytes.length)];
            int retLen = cipher.processBytes(plainBytes, 0, plainBytes.length, encryptedBytes, 0);
            cipher.doFinal(encryptedBytes, retLen);
            sR = Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (UnsupportedEncodingException | IllegalArgumentException | 
                 IllegalStateException | DataLengthException | InvalidCipherTextException ex) {
            System.out.println(ex.getMessage());
        }

        return sR;
    }

    public static String decrypt(String EncryptedText, byte[] key, byte[] iv) {
        String sR = "";
        try {
            byte[] encryptedBytes = Base64.getDecoder().decode(EncryptedText);

            GCMBlockCipher cipher = new GCMBlockCipher(new AESFastEngine());
            AEADParameters parameters = 
                     new AEADParameters(new KeyParameter(key), MacBitSize, iv, null);

            cipher.init(false, parameters);
            byte[] plainBytes = new byte[cipher.getOutputSize(encryptedBytes.length)];
            int retLen = cipher.processBytes
                         (encryptedBytes, 0, encryptedBytes.length, plainBytes, 0);
            cipher.doFinal(plainBytes, retLen);

            sR = new String(plainBytes, Charset.forName("UTF-8"));
        } catch (IllegalArgumentException | IllegalStateException | 
                         DataLengthException | InvalidCipherTextException ex) {
            System.out.println(ex.getMessage());
        }

        return sR;
    }
}

For C++

Please include Crypto++ Project in your test project.

Correct include and linked library paths:

Image 3

C++ Test Console Application

Shrink ▲   Copy Code
// TestAES_GCM_256_C.cpp : Defines the entry point for the console application.
//

#pragma once
#include "stdafx.h"

#ifndef _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_DEPRECATE 1
#endif

#ifndef CRYPTOPP_DEFAULT_NO_DLL
#define CRYPTOPP_DEFAULT_NO_DLL 1
#endif

#ifndef CRYPTOPP_ENABLE_NAMESPACE_WEAK
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#endif


#ifdef _DEBUG

#ifndef x64
#pragma comment(lib, "./../../../common/Crypto5.6.1/Win32/Output/Debug/cryptlib.lib")
#else
#pragma comment(lib, "./../../../common/Crypto5.6.1/x64/Output/Debug/cryptlib.lib")
#endif
#else
#ifndef x64
#pragma comment(lib, "./../../../common/Crypto5.6.1/Win32/Output/Release/cryptlib.lib")
#else
#pragma comment(lib, "./../../../common/Crypto5.6.1/x64/Output/Release/cryptlib.lib")
#endif
#endif

// Crypto++ Include

#include "./../../../common/Crypto5.6.1/pch.h"
#include "./../../../common/Crypto5.6.1/files.h"
#include "./../../../common/Crypto5.6.1/default.h"
#include "./../../../common/Crypto5.6.1/base64.h"
#include "./../../../common/Crypto5.6.1/osrng.h"

//AES
#include "./../../../common/Crypto5.6.1/hex.h"
using CryptoPP::HexEncoder;
using CryptoPP::HexDecoder;

#include "./../../../common/Crypto5.6.1/cryptlib.h"
using CryptoPP::BufferedTransformation;
using CryptoPP::AuthenticatedSymmetricCipher;

#include "./../../../common/Crypto5.6.1/filters.h"
using CryptoPP::StringSink;
using CryptoPP::StringSource;
using CryptoPP::AuthenticatedEncryptionFilter;
using CryptoPP::AuthenticatedDecryptionFilter;

#include "./../../../common/Crypto5.6.1/aes.h"
using CryptoPP::AES;

#include "./../../../common/Crypto5.6.1/gcm.h"
using CryptoPP::GCM;
using CryptoPP::GCM_TablesOption;

#include <iostream>
#include <string>

USING_NAMESPACE(CryptoPP)
USING_NAMESPACE(std)

static inline RandomNumberGenerator& PSRNG(void);
static inline RandomNumberGenerator& PSRNG(void)
{
	static AutoSeededRandomPool rng;
	rng.Reseed();
	return rng;
}

bool encrypt_aes256_gcm(const char *aesKey, const char *aesIV, 
                        const char *inPlainText, char **outEncryptedBase64, int &dataLength);
bool decrypt_aes256_gcm(const char *aesKey, const char *aesIV, 
                        const char *inBase64Text, char **outDecrypted, int &dataLength);
void Base64Decode(const std::string &inString, std::string &outString);
void HexDecode(const std::string &inString, std::string &outString);

static std::string m_ErrorMessage;

int main()
{
	//using above code these key and iv was generated
	std::string hexKey = "2192B39425BBD08B6E8E61C5D1F1BC9F428FC569FBC6F78C0BC48FCCDB0F42AE";
	std::string hexDecodedKey;
	HexDecode(hexKey, hexDecodedKey);

	std::string hexIV = "E1E592E87225847C11D948684F3B070D";
	std::string hexDecodedIv;
	HexDecode(hexIV, hexDecodedIv);

	std::string plainText = "Test encryption and decryption";
	std::string encryptedWithJava = "A/boAixWJKflKviHp2cfDl6l/xn1qw2MsHcKFkrOfm2XOVmawIFct4fS1w7wKw==";

	printf("%s%s\n", "Plain Text: " , plainText.c_str());

	//encrypt - result base64 encoded string
	char *outEncryptedText=NULL;
	int outDataLength=0;
	bool bR = encrypt_aes256_gcm(hexDecodedKey.c_str(), 
              hexDecodedIv.c_str(), plainText.c_str(), &outEncryptedText, outDataLength);
	printf("%s%s\n", "Encrypted base64 encoded: " , outEncryptedText);

	//decrypt - result plain string
	char* outDecryptedText=NULL;
	int outDecryptedDataLength=0;
	bR = decrypt_aes256_gcm(hexDecodedKey.c_str(), 
         hexDecodedIv.c_str(), encryptedWithJava.c_str(), &outDecryptedText, outDecryptedDataLength);
	printf("%s%s\n", "Decrypted Text Encrypted by Java: " , outDecryptedText);

	if (plainText == outDecryptedText)
	{
		printf("%s\n", "Test Passed");
	}
	else
	{
		printf("%s\n", "Test Failed");
	}

	return 0;
}

bool encrypt_aes256_gcm(const char *aesKey, const char *aesIV, 
                        const char *inPlainText, char **outEncryptedBase64, int &dataLength)
{
	bool bR = false;
	//const int TAG_SIZE = 12;
	std::string outText;
	std::string outBase64;

	if (strlen(aesKey)>31 && strlen(aesIV)>15)
	{
		try
		{
			GCM< AES >::Encryption aesEncryption;
			aesEncryption.SetKeyWithIV(reinterpret_cast<const byte*>(aesKey), 
             AES::MAX_KEYLENGTH, reinterpret_cast<const byte*>(aesIV), AES::BLOCKSIZE);
			StringSource(inPlainText, true, new AuthenticatedEncryptionFilter
                        (aesEncryption, new StringSink(outText)
			) // AuthenticatedEncryptionFilter
			); // StringSource

			CryptoPP::Base64Encoder *base64Encoder = new CryptoPP::Base64Encoder
                                                     (new StringSink(outBase64), false);
			base64Encoder->PutMessageEnd(reinterpret_cast<const char="" 
                           unsigned=""> (outText.data()), outText.length());
			delete base64Encoder;

			dataLength = outBase64.length();
			if (outBase64.length()>0)
			{
				if (*outEncryptedBase64) free(*outEncryptedBase64);
				*outEncryptedBase64 = (char*)malloc(dataLength + 1);
				memset(*outEncryptedBase64, '\0', dataLength + 1);
				memcpy(*outEncryptedBase64, outBase64.c_str(), dataLength);

				bR = true;
			}
			else
			{
				m_ErrorMessage.append("Encryption Failed");
			}

		}
		catch (CryptoPP::InvalidArgument& e)
		{
			m_ErrorMessage.append(e.what());
		}
		catch (CryptoPP::Exception& e)
		{
			m_ErrorMessage.append(e.what());
		}
	}
	else
	{
		m_ErrorMessage.append("AES Key or IV cannot be empty");
	}

	outText.clear();
	outBase64.clear();

	return bR;
}

bool decrypt_aes256_gcm(const char *aesKey, const char *aesIV, 
                        const char *inBase64Text, char **outDecrypted, int &dataLength)
{
	bool bR = false;
	std::string outText;
	std::string pszDecodedText;
	Base64Decode(inBase64Text, pszDecodedText);

	if (strlen(aesKey)>31 && strlen(aesIV)>15)
	{
		try
		{
			GCM< AES >::Decryption aesDecryption;
			aesDecryption.SetKeyWithIV(reinterpret_cast<const byte*>(aesKey), 
                AES::MAX_KEYLENGTH, reinterpret_cast<const byte*>(aesIV), AES::BLOCKSIZE);
			AuthenticatedDecryptionFilter df(aesDecryption, new StringSink(outText));

			StringSource(pszDecodedText, true,
				new Redirector(df /*, PASS_EVERYTHING */)
			); // StringSource

			bR = df.GetLastResult();

			dataLength = outText.length();
			if (outText.length()>0)
			{
				if (*outDecrypted) free(*outDecrypted);
				*outDecrypted = (char*)malloc(dataLength + 1);
				memset(*outDecrypted, '\0', dataLength + 1);
				memcpy(*outDecrypted, outText.c_str(), dataLength);

				bR = true;
			}
			else
			{
				m_ErrorMessage.append("Decryption Failed");
			}
		}
		catch (CryptoPP::HashVerificationFilter::HashVerificationFailed& e)
		{
			m_ErrorMessage.append(e.what());
		}
		catch (CryptoPP::InvalidArgument& e)
		{
			m_ErrorMessage.append(e.what());
		}
		catch (CryptoPP::Exception& e)
		{
			m_ErrorMessage.append(e.what());
		}
	}
	else
	{
		m_ErrorMessage.append("AES Key or IV cannot be empty");
	}

	return bR;
}

void Base64Decode(const std::string &inString, std::string &outString)
{
	StringSource(inString, true, new Base64Decoder(new StringSink(outString)));
}

void HexDecode(const std::string &inString, std::string &outString)
{
	StringSource(inString, true, new HexDecoder(new StringSink(outString)));
}

History

  • 29th October, 2018: First published

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK