Skip to content

.NET Password encryption example

The example below uses the BouncyCastle library

Aes encryption class

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
using System;
using System.Text;
using System.Linq;
using System.Text.RegularExpressions;

public class AesEncryptionClient 
{
    /**
 * Example results:
 *
 * Key: cf0138d58946c6849a5d972c50830f76, initialization vector: BVLdWx//evkFUt1bH/96+Q==, plaintext: P@ssword1, ciphertext: o/MCR6uS/RAmOse1+3ngU6gjf/+r8h4xWw==
 * Key: cf0138d58946c6849a5d972c50830f76, initialization vector: BVLdWx//evkFUt1bH/96+Q==, plaintext: P@ssword1P@ssword1P@ssword1P@ssword1, ciphertext: o/MCR6uS/RAm3AXKVisVZoxuGFgqpBMm6uGxBaZK1Pk/oIIfg+Yf0BkINfadXkSQBklXbQ==
 * Key: 4592d93c50f4fc7b57e6e67d4ddd0226, initialization vector: BVLdWx//evkFUt1bH/96+Q==, plaintext: P@ssword1, ciphertext: DJCDlVHLTEmv9+bckUGxSYMVRuesD3Imzw==
 * Key: 4592d93c50f4fc7b57e6e67d4ddd0226, initialization vector: BVLdWx//evkFUt1bH/96+Q==, plaintext: P@ssword1P@ssword1P@ssword1P@ssword1, ciphertext: DJCDlVHLTEmvl2XNByIvh5fF2t2oClfyT4/4k01vFgTJTT9Gf75K8TIKn3gSdLFYngjNRA==
 * Key: cf0138d58946c6849a5d972c50830f76, initialization vector: IvRBeADfn3+z6Yp8F0cAlw==, plaintext: P@ssword1, ciphertext: 4VxXjErxQ2+jMlCbKgXuiBRstBg6O9P6FA==
 * Key: 4592d93c50f4fc7b57e6e67d4ddd0226, initialization vector: IvRBeADfn3+z6Yp8F0cAlw==, plaintext: P@ssword1, ciphertext: sj0QVsoqkhk5YLWWvMIpdwiITRmq0unYiA==
 * Key: cf0138d58946c6849a5d972c50830f76, initialization vector: IvRBeADfn3+z6Yp8F0cAlw==, plaintext: P@ssword1P@ssword1P@ssword1P@ssword1, ciphertext: 4VxXjErxQ2+j+G5GgLzmfOidCYjxeKztyA1kx3iNJgZJImbrKqsWa5znwxTUQSK1XlGw8g==
 * Key: 4592d93c50f4fc7b57e6e67d4ddd0226, initialization vector: IvRBeADfn3+z6Yp8F0cAlw==, plaintext: P@ssword1P@ssword1P@ssword1P@ssword1, ciphertext: sj0QVsoqkhk5VbMf5H2gB+ywJPRLQfibgAyaDlAgQD/Ia81LLLQ64stXoz47IZVj2soRLg==

 */
    private static readonly String ALGORITHM = "AES";
    private static readonly String CIPHER = "AES/GCM/NoPadding";
    private readonly byte[] key;

    public AesEncryptionClient(byte[] key)
    {
        this.key = key;
    }

    public String GenerateIV()
    {
        byte[] randomInitializationVector = new byte[16];
        SecureRandom secureRandom = SecureRandom.GetInstance("SHA1PRNG");
        secureRandom.NextBytes(randomInitializationVector);
        return Encoding.UTF8.GetString(Base64.Encode(randomInitializationVector));
    }

    public String Encrypt(String plaintext, String iv)
    {
        byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
        IBufferedCipher cipher = CreateCipher(iv, true);
        byte[] ciphertextBytes = cipher.DoFinal(plaintextBytes);
        return Encoding.UTF8.GetString(Base64.Encode(ciphertextBytes));
    }

    public String Decrypt(String ciphertext, String iv)
    {
        byte[] ciphertextBytes = Base64.Decode(ciphertext);
        IBufferedCipher cipher = CreateCipher(iv, false);
        byte[] plaintextBytes = cipher.DoFinal(ciphertextBytes);
        return Encoding.UTF8.GetString(plaintextBytes);
    }

    private IBufferedCipher CreateCipher(String iv, bool encrypt)
    {
        KeyParameter keySpec = ParameterUtilities.CreateKeyParameter(ALGORITHM, key);
        ParametersWithIV ivSpec = new ParametersWithIV(keySpec, Base64.Decode(iv));

        IBufferedCipher cipher = CipherUtilities.GetCipher(CIPHER);
        cipher.Init(encrypt, ivSpec);
        return cipher;
    }
}

Test Class

using Onegini.Encryption;

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Text;

namespace Onegini.Encryption.Test
{
    [TestClass]
    public class AesPasswordEncryptionClientTest
    {
        public TestContext TestContext { get; set; }

        [TestMethod]
        public void TestDecrypt()
        {
            string ivBase64Encoded = "nnWnqJeS4v5eHScz";
            //C45B3B4E5CF954C50A654CA66190188E65305C514AF00934BCFDD965412338B4
            string key = "xFs7Tlz5VMUKZUymYZAYjmUwXFFK8Ak0vP3ZZUEjOLQ=";
            string plaintext = "Password!1";

            string plaintextBase64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(plaintext));

            TestContext.WriteLine("plaintext                    : {0}", plaintext);
            TestContext.WriteLine("plaintext (base64)           : {0}", plaintextBase64);
            TestContext.WriteLine("key (base64)                 : {0}", key);
            TestContext.WriteLine("iv (base64)                  : {0}", ivBase64Encoded);

            AesEncryptionClient aesEncryptionClient = new AesEncryptionClient(Convert.FromBase64String(key));
            string ciphertext = aesEncryptionClient.Encrypt(plaintext, ivBase64Encoded);
            string plaintextDecrypted = aesEncryptionClient.Decrypt(ciphertext, ivBase64Encoded);

            TestContext.WriteLine("ciphertext (base64)          : {0}", ciphertext);
            TestContext.WriteLine("plaintext (decrypted)        : {0}", plaintextDecrypted);

            Assert.AreEqual(plaintext, plaintextDecrypted);
        }
    }
}