Org.BouncyCastle.Crypto.Modes.CcmBlockCipher.Init C# (CSharp) Method

Init() public method

public Init ( bool forEncryption, ICipherParameters parameters ) : void
forEncryption bool
parameters ICipherParameters
return void
        public virtual void Init(
			bool				forEncryption,
			ICipherParameters	parameters)
        {
			this.forEncryption = forEncryption;

			if (parameters is AeadParameters)
			{
				AeadParameters param = (AeadParameters) parameters;

				nonce = param.GetNonce();
				associatedText = param.GetAssociatedText();
				macSize = param.MacSize / 8;
				keyParam = param.Key;
			}
			else if (parameters is ParametersWithIV)
			{
				ParametersWithIV param = (ParametersWithIV) parameters;

				nonce = param.GetIV();
				associatedText = null;
				macSize = macBlock.Length / 2;
				keyParam = param.Parameters;
			}
			else
			{
				throw new ArgumentException("invalid parameters passed to CCM");
			}
        }

Usage Example

        public string Encrypt(string data)
        {
            SecureRandom random = new SecureRandom();

            // Generate 256-bits AES key
            byte[] aesKey = new byte[32];
            random.NextBytes(aesKey);

            // Generate Initialization Vector
            byte[] IV = new byte[12];
            random.NextBytes(IV);

            // Apply RSA/None/PKCS1Padding encryption to the AES key
            byte[] encyptedAESKey = rsaCipher.DoFinal(aesKey);

            // Apply AES/CCM/NoPadding encryption to the data
            byte[] cipherText = System.Text.Encoding.UTF8.GetBytes(data);

            var ccmParameters = new CcmParameters(new KeyParameter(aesKey), 64, IV, new byte[] { });
            aesCipher = new CcmBlockCipher(new AesFastEngine());
            aesCipher.Init(true, ccmParameters);

            var encrypted = new byte[aesCipher.GetOutputSize(cipherText.Length)];
            var res = aesCipher.ProcessBytes(cipherText, 0, cipherText.Length, encrypted, 0);
            aesCipher.DoFinal(encrypted, res);

            // Merge 'IV' and 'encrypted' to 'result'
            byte[] result = new byte[IV.Length + encrypted.Length];
            System.Buffer.BlockCopy(IV, 0, result, 0, IV.Length);
            System.Buffer.BlockCopy(encrypted, 0, result, IV.Length, encrypted.Length);

            // Return encrypted data
            return Prefix + Version + Separator + System.Convert.ToBase64String(encyptedAESKey) + Separator + System.Convert.ToBase64String(result);
        }
All Usage Examples Of Org.BouncyCastle.Crypto.Modes.CcmBlockCipher::Init