Exemple #1
0
        public static byte[] EncryptDES(byte[] data, byte[] derivedKey)
        {
            byte[] output = null;
            try
            {
                KeyParameter    keyparam = ParameterUtilities.CreateKeyParameter("DES", derivedKey);
                IBufferedCipher cipher   = CipherUtilities.GetCipher("DES/ECB/ISO7816_4PADDING");
                cipher.Init(true, keyparam);
                try
                {
                    output = cipher.DoFinal(data);
                    return(output);
                }
                catch (System.Exception ex)
                {
                    throw new CryptoException(ex.Message);
                }
            }
            catch (Exception ex)
            {
            }

            return(output);
        }
Exemple #2
0
        protected internal virtual AlgorithmIdentifier GetAlgorithmIdentifier(
            string encryptionOid,
            KeyParameter encKey,
            Asn1Encodable asn1Params,
            out ICipherParameters cipherParameters)
        {
            Asn1Object asn1Object;

            if (asn1Params != null)
            {
                asn1Object       = asn1Params.ToAsn1Object();
                cipherParameters = ParameterUtilities.GetCipherParameters(
                    encryptionOid, encKey, asn1Object);
            }
            else
            {
                asn1Object       = DerNull.Instance;
                cipherParameters = encKey;
            }

            return(new AlgorithmIdentifier(
                       new DerObjectIdentifier(encryptionOid),
                       asn1Object));
        }
Exemple #3
0
        private void doTestAlgorithm(
            string name,
            byte[]  keyBytes,
            byte[]  iv,
            byte[]  plainText,
            byte[]  cipherText)
        {
            KeyParameter key = ParameterUtilities.CreateKeyParameter(name, keyBytes);

            IBufferedCipher inCipher  = CipherUtilities.GetCipher(name);
            IBufferedCipher outCipher = CipherUtilities.GetCipher(name);

            if (iv != null)
            {
                inCipher.Init(true, new ParametersWithIV(key, iv));
                outCipher.Init(false, new ParametersWithIV(key, iv));
            }
            else
            {
                inCipher.Init(true, key);
                outCipher.Init(false, key);
            }

            byte[] enc = inCipher.DoFinal(plainText);
            if (!AreEqual(enc, cipherText))
            {
                Fail(name + ": cipher text doesn't match");
            }

            byte[] dec = outCipher.DoFinal(enc);

            if (!AreEqual(dec, plainText))
            {
                Fail(name + ": plain text doesn't match");
            }
        }
Exemple #4
0
        private void aliasTest(
            KeyParameter key,
            string primary,
            params string[] aliases)
        {
            IMac mac = MacUtilities.GetMac(primary);

            //
            // standard DAC - zero IV
            //
            mac.Init(key);

            mac.BlockUpdate(input, 0, input.Length);

            byte[] refBytes = new byte[mac.GetMacSize()];
            mac.DoFinal(refBytes, 0);

            for (int i = 0; i != aliases.Length; i++)
            {
                mac = MacUtilities.GetMac(aliases[i]);

                mac.Init(key);

                mac.BlockUpdate(input, 0, input.Length);

                byte[] outBytes = new byte[mac.GetMacSize()];
                mac.DoFinal(outBytes, 0);

                if (!AreEqual(outBytes, refBytes))
                {
                    Fail("Failed - expected "
                         + Hex.ToHexString(refBytes) + " got "
                         + Hex.ToHexString(outBytes));
                }
            }
        }
Exemple #5
0
        /**
         * initialise a RC2 cipher.
         *
         * @param forEncryption whether or not we are for encryption.
         * @param parameters the parameters required to set up the cipher.
         * @exception ArgumentException if the parameters argument is
         * inappropriate.
         */
        public void Init(
            bool forEncryption,
            ICipherParameters parameters)
        {
            this.encrypting = forEncryption;

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

                workingKey = GenerateWorkingKey(param.GetKey(), param.EffectiveKeyBits);
            }
            else if (parameters is KeyParameter)
            {
                KeyParameter param = (KeyParameter)parameters;
                byte[]       key   = param.GetKey();

                workingKey = GenerateWorkingKey(key, key.Length * 8);
            }
            else
            {
                throw new ArgumentException("invalid parameter passed to RC2 init - " + parameters.GetType().Name);
            }
        }
        private static void hmac_hash(IDigest digest, byte[] secret, byte[] seed, byte[] output)
        {
            HMac         mac   = new HMac(digest);
            KeyParameter param = new KeyParameter(secret);

            byte[] a          = seed;
            int    size       = digest.GetDigestSize();
            int    iterations = (output.Length + size - 1) / size;

            byte[] buf  = new byte[mac.GetMacSize()];
            byte[] buf2 = new byte[mac.GetMacSize()];
            for (int i = 0; i < iterations; i++)
            {
                mac.Init(param);
                mac.BlockUpdate(a, 0, a.Length);
                mac.DoFinal(buf, 0);
                a = buf;
                mac.Init(param);
                mac.BlockUpdate(a, 0, a.Length);
                mac.BlockUpdate(seed, 0, seed.Length);
                mac.DoFinal(buf2, 0);
                Array.Copy(buf2, 0, output, (size * i), System.Math.Min(size, output.Length - (size * i)));
            }
        }
        /// <exception cref="IOException"></exception>
        public virtual byte[] DecodeCiphertext(long seqNo, byte type, byte[] ciphertext, int offset, int len)
        {
            if (GetPlaintextLimit(len) < 0)
            {
                throw new TlsFatalAlert(AlertDescription.decode_error);
            }

            KeyParameter macKey = InitRecord(decryptCipher, false, seqNo, decryptIV);

            int plaintextLength = len - 16;

            byte[] additionalData = GetAdditionalData(seqNo, type, plaintextLength);
            byte[] calculatedMac  = CalculateRecordMac(macKey, additionalData, ciphertext, offset, plaintextLength);
            byte[] receivedMac    = Arrays.CopyOfRange(ciphertext, offset + plaintextLength, offset + len);

            if (!Arrays.ConstantTimeAreEqual(calculatedMac, receivedMac))
            {
                throw new TlsFatalAlert(AlertDescription.bad_record_mac);
            }

            byte[] output = new byte[plaintextLength];
            decryptCipher.ProcessBytes(ciphertext, offset, plaintextLength, output, 0);
            return(output);
        }
        private Asn1Object CreateDERForRecipient(byte[] inp, X509Certificate cert)
        {
            String s = "1.2.840.113549.3.2";

            byte[] outp = new byte[100];
            DerObjectIdentifier derob = new DerObjectIdentifier(s);

            byte[]          keyp = IVGenerator.GetIV(16);
            IBufferedCipher cf   = CipherUtilities.GetCipher(derob);
            KeyParameter    kp   = new KeyParameter(keyp);

            byte[]           iv  = IVGenerator.GetIV(cf.GetBlockSize());
            ParametersWithIV piv = new ParametersWithIV(kp, iv);

            cf.Init(true, piv);
            int len = cf.DoFinal(inp, outp, 0);

            byte[] abyte1 = new byte[len];
            System.Array.Copy(outp, 0, abyte1, 0, len);
            DerOctetString        deroctetstring        = new DerOctetString(abyte1);
            KeyTransRecipientInfo keytransrecipientinfo = ComputeRecipientInfo(cert, keyp);
            DerSet derset          = new DerSet(new RecipientInfo(keytransrecipientinfo));
            Asn1EncodableVector ev = new Asn1EncodableVector();

            ev.Add(new DerInteger(58));
            ev.Add(new DerOctetString(iv));
            DerSequence          seq = new DerSequence(ev);
            AlgorithmIdentifier  algorithmidentifier  = new AlgorithmIdentifier(derob, seq);
            EncryptedContentInfo encryptedcontentinfo =
                new EncryptedContentInfo(PkcsObjectIdentifiers.Data, algorithmidentifier, deroctetstring);
            EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, null);

            Org.BouncyCastle.Asn1.Cms.ContentInfo contentinfo =
                new Org.BouncyCastle.Asn1.Cms.ContentInfo(PkcsObjectIdentifiers.EnvelopedData, env);
            return(contentinfo.ToAsn1Object());
        }
        private static void decrypt(String privateKeyPath,
                                    String encryptedCEK,
                                    String iv,
                                    String encryptedRecordingPath,
                                    String decryptedRecordingPath)
        {
            // 2) Retrieve customer private key corresponding to public_key_sid and use it to decrypt base 64 decoded
            // encrypted_cek via RSAES-OAEP-SHA256-MGF1
            Object pemObject;

            using (var txtreader = File.OpenText(@privateKeyPath))
                pemObject = new PemReader(txtreader).ReadObject();

            var privateKey = (RsaPrivateCrtKeyParameters)((pemObject.GetType() == typeof(AsymmetricCipherKeyPair)) ?
                                                          ((AsymmetricCipherKeyPair)pemObject).Private : pemObject);

            var rsaDecryptEngine = CipherUtilities.GetCipher("RSA/ECB/OAEPWITHSHA256ANDMGF1PADDING");

            rsaDecryptEngine.Init(false, privateKey);
            var encryptedCekArr = Convert.FromBase64String(encryptedCEK);
            var decryptedCekArr = rsaDecryptEngine.DoFinal(encryptedCekArr);

            // 3) Initialize a AES256-GCM SecretKey object with decrypted CEK and base 64 decoded iv
            var               aesDecryptEngine = CipherUtilities.GetCipher("AES/GCM/NOPADDING");
            KeyParameter      keyParameter     = ParameterUtilities.CreateKeyParameter("AES", decryptedCekArr);
            ICipherParameters cipherParameters = new ParametersWithIV(keyParameter, Convert.FromBase64String(iv));

            aesDecryptEngine.Init(false, cipherParameters);

            // 4) Decrypt encrypted recording using the SecretKey
            var          decryptedFile = File.Create(@decryptedRecordingPath);
            CipherStream cipherStream  = new CipherStream(File.OpenRead(@encryptedRecordingPath), aesDecryptEngine, null);

            cipherStream.CopyTo(decryptedFile);
            decryptedFile.Close();
        }
Exemple #10
0
        public void Init(ICipherParameters parameters)
        {
            //IL_001c: Unknown result type (might be due to invalid IL or missing references)
            //IL_0045: Unknown result type (might be due to invalid IL or missing references)
            byte[] nonce = null;
            if (cipher != null)
            {
                if (!(parameters is ParametersWithIV))
                {
                    throw new ArgumentException("Poly1305 requires an IV when used with a block cipher.", "parameters");
                }
                ParametersWithIV parametersWithIV = (ParametersWithIV)parameters;
                nonce      = parametersWithIV.GetIV();
                parameters = parametersWithIV.Parameters;
            }
            if (!(parameters is KeyParameter))
            {
                throw new ArgumentException("Poly1305 requires a key.");
            }
            KeyParameter keyParameter = (KeyParameter)parameters;

            SetKey(keyParameter.GetKey(), nonce);
            Reset();
        }
Exemple #11
0
        /**
         * decrypt the content and return an input stream.
         */
        public override CmsTypedStream GetContentStream(
            ICipherParameters key)
        {
            try
            {
                byte[]   encryptedKey = info.EncryptedKey.GetOctets();
                IWrapper keyWrapper   = WrapperUtilities.GetWrapper(keyEncAlg.ObjectID.Id);

                keyWrapper.Init(false, key);

                KeyParameter sKey = ParameterUtilities.CreateKeyParameter(
                    GetContentAlgorithmName(), keyWrapper.Unwrap(encryptedKey, 0, encryptedKey.Length));

                return(GetContentFromSessionKey(sKey));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
        }
Exemple #12
0
        private void F(
            byte[]  P,
            byte[]  S,
            int c,
            byte[]  iBuf,
            byte[]  outBytes,
            int outOff)
        {
            byte[]            state = new byte[hMac.GetMacSize()];
            ICipherParameters param = new KeyParameter(P);

            hMac.Init(param);

            if (S != null)
            {
                hMac.BlockUpdate(S, 0, S.Length);
            }

            hMac.BlockUpdate(iBuf, 0, iBuf.Length);

            hMac.DoFinal(state, 0);

            Array.Copy(state, 0, outBytes, outOff, state.Length);

            for (int count = 1; count != c; count++)
            {
                hMac.Init(param);
                hMac.BlockUpdate(state, 0, state.Length);
                hMac.DoFinal(state, 0);

                for (int j = 0; j != state.Length; j++)
                {
                    outBytes[outOff + j] ^= state[j];
                }
            }
        }
Exemple #13
0
        /**
         * initialise a Salsa20 cipher.
         *
         * @param forEncryption whether or not we are for encryption.
         * @param params the parameters required to set up the cipher.
         * @exception ArgumentException if the params argument is
         * inappropriate.
         */
        public void Init(
            bool forEncryption,
            ICipherParameters parameters)
        {
            /*
             * Salsa20 encryption and decryption is completely
             * symmetrical, so the 'forEncryption' is
             * irrelevant. (Like 90% of stream ciphers)
             */

            ParametersWithIV ivParams = parameters as ParametersWithIV;

            if (ivParams == null)
            {
                throw new ArgumentException("Salsa20 Init requires an IV", "parameters");
            }

            byte[] iv = ivParams.GetIV();

            if (iv == null || iv.Length != 8)
            {
                throw new ArgumentException("Salsa20 requires exactly 8 bytes of IV");
            }

            KeyParameter key = ivParams.Parameters as KeyParameter;

            if (key == null)
            {
                throw new ArgumentException("Salsa20 Init requires a key", "parameters");
            }

            workingKey = key.GetKey();
            workingIV  = iv;

            setKey(workingKey, workingIV);
        }
        public override void Init(Byte[] keyMaterial)
        {
            if (this.Mode != CipherMode.Cbc)
            {
                return;
            }

            /* client part */
            this._clientIv = new Byte[this.IvLength];
            Array.Copy(keyMaterial, this.MacKeyLength * 2 + this.KeyLength * 2, this._clientIv, 0, this.IvLength);
            this._clientKey = new KeyParameter(keyMaterial, this.MacKeyLength * 2, this.KeyLength);
            //Console.WriteLine("Client Key : "+ BitConverter.ToString(_clientKey.GetKey()));

            var keyAndIv = new ParametersWithIV(this._clientKey, this._clientIv, 0, this.IvLength);

            if (this.Mode == CipherMode.Cbc) // AEAD mode is initialized by other function
            {
                this.Ccipher.Reset();
                this.Ccipher.Init(false, keyAndIv);
            }

            /* server part */
            this._serverIv = new Byte[this.IvLength];
            Array.Copy(keyMaterial, this.MacKeyLength * 2 + this.KeyLength * 2 + this.IvLength, this._serverIv, 0, this.IvLength);
            this._serverKey = new KeyParameter(keyMaterial, this.MacKeyLength * 2 + this.KeyLength, this.KeyLength);

            //Console.WriteLine("Server Key : " + BitConverter.ToString(_serverKey.GetKey()));

            keyAndIv = new ParametersWithIV(this._serverKey, this._serverIv, 0, this.IvLength);

            if (this.Mode == CipherMode.Cbc)
            {
                this.Scipher.Reset();
                this.Scipher.Init(false, keyAndIv);
            }
        }
Exemple #15
0
        internal static void Receive(DHHandshakeContext context, BufLen data)
        {
            var reader = new BufRefLen(data);

            context.Y    = new I2PPublicKey(reader, context.RemoteRI.Certificate);
            context.YBuf = context.Y.Key;

            var sharedkey = BufUtils.DHI2PToByteArray(context.Y.ToBigInteger().ModPow(context.PrivateKey.ToBigInteger(), I2PConstants.ElGamalP));

            context.SessionKey = new I2PSessionKey(sharedkey);

            var key = new KeyParameter(context.SessionKey.Key.ToByteArray());

            var enciv = new BufLen(context.HXxorHI.BaseArray, context.HXxorHI.Length - 16, 16);
            var deciv = new BufLen(context.YBuf, context.YBuf.Length - 16, 16);

            context.Encryptor = new CbcBlockCipher(new AesEngine());
            context.Encryptor.Init(true, new ParametersWithIV(key, enciv.BaseArray, enciv.BaseArrayOffset, enciv.Length));

            context.Dectryptor = new CbcBlockCipher(new AesEngine());
            context.Dectryptor.Init(false, new ParametersWithIV(key, deciv.BaseArray, deciv.BaseArrayOffset, deciv.Length));

            var encrbuf = new BufLen(reader, 0, 32 + 4 + 12);

            context.Dectryptor.ProcessBytes(encrbuf);

            context.HXY        = reader.ReadBufLen(32);
            context.TimestampB = reader.ReadFlip32();

            var checkhash = I2PHashSHA256.GetHash(context.XBuf, context.YBuf);

            if (!context.HXY.Equals(checkhash))
            {
                throw new ChecksumFailureException("NTCP SessionCreated received HXY check failed!");
            }
        }
Exemple #16
0
        private void doTest(
            string algorithm,
            byte[]      input,
            byte[]      output)
        {
            KeyParameter       key = null;
            CipherKeyGenerator keyGen;
            SecureRandom       rand;
            IBufferedCipher    inCipher = null, outCipher = null;

            byte[]       iv = null;
            CipherStream cIn, cOut;
            MemoryStream bIn, bOut;

            rand = new FixedSecureRandom();

            string[] parts = algorithm.ToUpper(CultureInfo.InvariantCulture).Split('/');
            string   baseAlgorithm = parts[0];
            string   mode  = parts.Length > 1 ? parts[1] : null;

#if !INCLUDE_IDEA
            if (baseAlgorithm.Equals("IDEA"))
            {
                return;
            }
#endif

            try
            {
                keyGen = GeneratorUtilities.GetKeyGenerator(baseAlgorithm);

                // TODO Add Algorithm property to CipherKeyGenerator?
//				if (!keyGen.getAlgorithm().Equals(baseAlgorithm))
//				{
//					Fail("wrong key generator returned!");
//				}

                // TODO Add new Init method to CipherKeyGenerator?
//				keyGen.Init(rand);
                keyGen.Init(new KeyGenerationParameters(rand, keyGen.DefaultStrength));

                byte[] keyBytes = keyGen.GenerateKey();

                if (algorithm.StartsWith("RC5"))
                {
                    key = new RC5Parameters(keyBytes, rc5Rounds);
                }
                else
                {
                    key = ParameterUtilities.CreateKeyParameter(baseAlgorithm, keyBytes);
                }

                inCipher  = CipherUtilities.GetCipher(algorithm);
                outCipher = CipherUtilities.GetCipher(algorithm);

                if (!inCipher.AlgorithmName.ToUpper(CultureInfo.InvariantCulture).StartsWith(baseAlgorithm))
                {
                    Fail("wrong cipher returned!");
                }

                ICipherParameters parameters = key;

                int ivLength = GetIVLength(algorithm);

                if (ivLength > 0)
                {
                    if (baseAlgorithm == "RC2")
                    {
                        iv = rc2IV;
                    }
                    else if (baseAlgorithm == "RC5")
                    {
                        iv = rc5IV;
                    }
                    else if (baseAlgorithm == "RC5-64")
                    {
                        iv = rc564IV;
                    }
                    else
                    {
                        // NB: rand always generates same values each test run
                        iv = rand.GenerateSeed(ivLength);
                    }

                    parameters = new ParametersWithIV(key, iv);
                }

                // NB: 'rand' still needed e.g. for some paddings
                parameters = new ParametersWithRandom(parameters, rand);

                outCipher.Init(true, parameters);
            }
            catch (Exception e)
            {
                Fail("" + algorithm + " failed initialisation - " + e.ToString(), e);
            }

            //
            // grab the iv if there is one
            //
            try
            {
                // The Java version set this implicitly, but we set it explicity
                //byte[] iv = outCipher.getIV();

                if (iv != null)
                {
                    // TODO Examine short IV handling for these FIPS-compliant modes in Java build
                    if (mode.StartsWith("CFB") ||
                        mode.StartsWith("GOFB") ||
                        mode.StartsWith("OFB") ||
                        mode.StartsWith("OPENPGPCFB"))
                    {
                        // These modes automatically pad out the IV if it is short
                    }
                    else
                    {
                        try
                        {
                            byte[] nIv = new byte[iv.Length - 1];
                            inCipher.Init(false, new ParametersWithIV(key, nIv));
                            Fail("failed to pick up short IV");
                        }
                        //catch (InvalidAlgorithmParameterException e)
                        catch (ArgumentException)
                        {
                            // ignore - this is what we want...
                        }
                    }

                    //IvParameterSpec spec = new IvParameterSpec(iv);
                    inCipher.Init(false, new ParametersWithIV(key, iv));
                }
                else
                {
                    inCipher.Init(false, key);
                }
            }
            catch (Exception e)
            {
                Fail("" + algorithm + " failed initialisation - " + e.ToString());
            }

            //
            // encryption pass
            //
            bOut = new MemoryStream();
            cOut = new CipherStream(bOut, null, outCipher);

            try
            {
                for (int i = 0; i != input.Length / 2; i++)
                {
                    cOut.WriteByte(input[i]);
                }
                cOut.Write(input, input.Length / 2, input.Length - input.Length / 2);
                cOut.Close();
            }
            catch (IOException e)
            {
                Fail("" + algorithm + " failed encryption - " + e.ToString());
            }

            byte[] bytes = bOut.ToArray();

            if (!AreEqual(bytes, output))
            {
                Fail("" + algorithm + " failed encryption - expected "
                     + Hex.ToHexString(output) + " got "
                     + Hex.ToHexString(bytes));
            }

            //
            // decryption pass
            //
            bIn = new MemoryStream(bytes, false);
            cIn = new CipherStream(bIn, inCipher, null);

            try
            {
                BinaryReader dIn = new BinaryReader(cIn);

                bytes = new byte[input.Length];

                for (int i = 0; i != input.Length / 2; i++)
                {
                    bytes[i] = dIn.ReadByte();
                }

                int    remaining = bytes.Length - input.Length / 2;
                byte[] extra     = dIn.ReadBytes(remaining);
                if (extra.Length < remaining)
                {
                    throw new EndOfStreamException();
                }
                extra.CopyTo(bytes, input.Length / 2);
            }
            catch (Exception e)
            {
                Fail("" + algorithm + " failed decryption - " + e.ToString());
            }

            if (!AreEqual(bytes, input))
            {
                Fail("" + algorithm + " failed decryption - expected "
                     + Hex.ToHexString(input) + " got "
                     + Hex.ToHexString(bytes));
            }
        }
        private void doRunTest(
            string name,
            int ivLength)
        {
            string lCode = "ABCDEFGHIJKLMNOPQRSTUVWXY0123456789";

            string baseName = name;

            if (name.IndexOf('/') >= 0)
            {
                baseName = name.Substring(0, name.IndexOf('/'));
            }

            CipherKeyGenerator kGen = GeneratorUtilities.GetKeyGenerator(baseName);

            IBufferedCipher inCipher  = CipherUtilities.GetCipher(name);
            IBufferedCipher outCipher = CipherUtilities.GetCipher(name);
            KeyParameter    key       = ParameterUtilities.CreateKeyParameter(baseName, kGen.GenerateKey());
            MemoryStream    bIn       = new MemoryStream(Encoding.ASCII.GetBytes(lCode), false);
            MemoryStream    bOut      = new MemoryStream();

            // In the Java build, this IV would be implicitly created and then retrieved with getIV()
            ICipherParameters cipherParams = key;

            if (ivLength > 0)
            {
                cipherParams = new ParametersWithIV(cipherParams, new byte[ivLength]);
            }

            inCipher.Init(true, cipherParams);

            // TODO Should we provide GetIV() method on IBufferedCipher?
            //if (inCipher.getIV() != null)
            //{
            //	outCipher.Init(false, new ParametersWithIV(key, inCipher.getIV()));
            //}
            //else
            //{
            //	outCipher.Init(false, key);
            //}
            outCipher.Init(false, cipherParams);

            CipherStream cIn  = new CipherStream(bIn, inCipher, null);
            CipherStream cOut = new CipherStream(bOut, null, outCipher);

            int c;

            while ((c = cIn.ReadByte()) >= 0)
            {
                cOut.WriteByte((byte)c);
            }

            cIn.Close();

            cOut.Flush();
            cOut.Close();

            byte[] bs  = bOut.ToArray();
            string res = Encoding.ASCII.GetString(bs, 0, bs.Length);

            if (!res.Equals(lCode))
            {
                Fail("Failed - decrypted data doesn't match.");
            }
        }
        private void doTestException(
            string name,
            int ivLength)
        {
            try
            {
                byte[] key128 =
                {
                    (byte)128, (byte)131, (byte)133, (byte)134,
                    (byte)137, (byte)138, (byte)140, (byte)143,
                    (byte)128, (byte)131, (byte)133, (byte)134,
                    (byte)137, (byte)138, (byte)140, (byte)143
                };

                byte[] key256 =
                {
                    (byte)128, (byte)131, (byte)133, (byte)134,
                    (byte)137, (byte)138, (byte)140, (byte)143,
                    (byte)128, (byte)131, (byte)133, (byte)134,
                    (byte)137, (byte)138, (byte)140, (byte)143,
                    (byte)128, (byte)131, (byte)133, (byte)134,
                    (byte)137, (byte)138, (byte)140, (byte)143,
                    (byte)128, (byte)131, (byte)133, (byte)134,
                    (byte)137, (byte)138, (byte)140, (byte)143
                };

                byte[] keyBytes;
                if (name.Equals("HC256"))
                {
                    keyBytes = key256;
                }
                else
                {
                    keyBytes = key128;
                }

                KeyParameter cipherKey = ParameterUtilities.CreateKeyParameter(name, keyBytes);

                ICipherParameters cipherParams = cipherKey;
                if (ivLength > 0)
                {
                    cipherParams = new ParametersWithIV(cipherParams, new byte[ivLength]);
                }

                IBufferedCipher ecipher = CipherUtilities.GetCipher(name);
                ecipher.Init(true, cipherParams);

                byte[] cipherText = new byte[0];
                try
                {
                    // According specification Method engineUpdate(byte[] input,
                    // int inputOffset, int inputLen, byte[] output, int
                    // outputOffset)
                    // throws ShortBufferException - if the given output buffer is
                    // too
                    // small to hold the result
                    ecipher.ProcessBytes(new byte[20], 0, 20, cipherText, 0);

//					Fail("failed exception test - no ShortBufferException thrown");
                    Fail("failed exception test - no DataLengthException thrown");
                }
//				catch (ShortBufferException e)
                catch (DataLengthException)
                {
                    // ignore
                }

                // NB: The lightweight engine doesn't take public/private keys
//				try
//				{
//					IBufferedCipher c = CipherUtilities.GetCipher(name);
//
//					//                Key k = new PublicKey()
//					//                {
//					//
//					//                    public string getAlgorithm()
//					//                    {
//					//                        return "STUB";
//					//                    }
//					//
//					//                    public string getFormat()
//					//                    {
//					//                        return null;
//					//                    }
//					//
//					//                    public byte[] getEncoded()
//					//                    {
//					//                        return null;
//					//                    }
//					//
//					//                };
//					AsymmetricKeyParameter k = new AsymmetricKeyParameter(false);
//					c.Init(true, k);
//
//					Fail("failed exception test - no InvalidKeyException thrown for public key");
//				}
//				catch (InvalidKeyException)
//				{
//					// okay
//				}
//
//				try
//				{
//					IBufferedCipher c = CipherUtilities.GetCipher(name);
//
//					//				Key k = new PrivateKey()
//					//                {
//					//
//					//                    public string getAlgorithm()
//					//                    {
//					//                        return "STUB";
//					//                    }
//					//
//					//                    public string getFormat()
//					//                    {
//					//                        return null;
//					//                    }
//					//
//					//                    public byte[] getEncoded()
//					//                    {
//					//                        return null;
//					//                    }
//					//
//					//                };
//
//					AsymmetricKeyParameter k = new AsymmetricKeyParameter(true);
//					c.Init(false, k);
//
//					Fail("failed exception test - no InvalidKeyException thrown for private key");
//				}
//				catch (InvalidKeyException)
//				{
//					// okay
//				}
            }
            catch (Exception e)
            {
                Fail("unexpected exception.", e);
            }
        }
        // Token: 0x060000E0 RID: 224 RVA: 0x00007CA0 File Offset: 0x00005EA0
        public virtual void Init(bool forEncryption, ICipherParameters parameters)
        {
            this.forEncryption = forEncryption;
            this.macBlock      = null;
            this.initialised   = true;
            if (!(parameters is AeadParameters))
            {
                throw new ArgumentException("invalid parameters passed to GCM");
            }
            AeadParameters aeadParameters = (AeadParameters)parameters;

            byte[] array = aeadParameters.GetNonce();
            this.initialAssociatedText = aeadParameters.GetAssociatedText();
            int num = aeadParameters.MacSize;

            if (num < 32 || num > 128 || num % 8 != 0)
            {
                throw new ArgumentException("Invalid value for MAC size: " + num);
            }
            this.macSize = num / 8;
            KeyParameter key  = aeadParameters.Key;
            int          num2 = forEncryption ? 16 : (16 + this.macSize);

            this.bufBlock = new byte[num2];
            if (array == null || array.Length < 1)
            {
                throw new ArgumentException("IV must be at least 1 byte");
            }
            if (forEncryption && this.nonce != null && Arrays.AreEqual(this.nonce, array))
            {
                if (key == null)
                {
                    throw new ArgumentException("cannot reuse nonce for GCM encryption");
                }
                if (this.lastKey != null && Arrays.AreEqual(this.lastKey, key.GetKey()))
                {
                    throw new ArgumentException("cannot reuse nonce for GCM encryption");
                }
            }
            this.nonce = array;
            if (key != null)
            {
                this.lastKey = key.GetKey();
            }
            if (key != null)
            {
                this.cipher.Init(true, key);
                this.H = new byte[16];
                this.cipher.ProcessBlock(this.H, 0, this.H, 0);
                this.multiplier.Init(this.H);
                this.exp = null;
            }
            else if (this.H == null)
            {
                throw new ArgumentException("Key must be specified in initial init");
            }
            this.J0 = new byte[16];
            if (this.nonce.Length == 12)
            {
                Array.Copy(this.nonce, 0, this.J0, 0, this.nonce.Length);
                this.J0[15] = 1;
            }
            else
            {
                this.gHASH(this.J0, this.nonce, this.nonce.Length);
                byte[] array2 = new byte[16];
                Pack.UInt64_To_BE((ulong)((long)this.nonce.Length * 8L), array2, 8);
                this.gHASHBlock(this.J0, array2);
            }
            this.S               = new byte[16];
            this.S_at            = new byte[16];
            this.S_atPre         = new byte[16];
            this.atBlock         = new byte[16];
            this.atBlockPos      = 0;
            this.atLength        = 0UL;
            this.atLengthPre     = 0UL;
            this.counter         = Arrays.Clone(this.J0);
            this.blocksRemaining = 4294967294U;
            this.bufOff          = 0;
            this.totalLength     = 0UL;
            if (this.initialAssociatedText != null)
            {
                this.ProcessAadBytes(this.initialAssociatedText, 0, this.initialAssociatedText.Length);
            }
        }
Exemple #20
0
        public override CmsTypedStream GetContentStream(ICipherParameters key)
        {
            KeyParameter sKey = this.UnwrapKey(key);

            return(base.GetContentFromSessionKey(sKey));
        }
Exemple #21
0
        private static Stream emitAesBackupHeader(StringBuilder headerbuf, Stream ofstream,
                                                  String encryptionPassword, bool useUtf8)
        {
            //  User key will be used to encrypt the master key.
            byte[] newUserSalt = AndroidBackup.randomBytes(PBKDF2_SALT_SIZE);
            byte[] userKey     = AndroidBackup.buildPasswordKey(encryptionPassword, newUserSalt, PBKDF2_HASH_ROUNDS, useUtf8);
            //  the master key is random for each backup
            byte[] masterPw = new byte[(MASTER_KEY_SIZE / 8)];
            random.NextBytes(masterPw);
            byte[] checksumSalt = AndroidBackup.randomBytes(PBKDF2_SALT_SIZE);


            ////  primary encryption of the datastream with the random key
            //IBufferedCipher c = CipherUtilities.GetCipher("AES");
            //AesEngine aes = new AesEngine();

            //var spec1 = ParameterUtilities.CreateKeyParameter("AES256", masterPw);
            ////var parameters1 = new ParametersWithIV(spec1, new byte[128]); // Block size  == IV size == 16 in BouncyCastle for AES
            //c.Init(true, spec1);

            AesEngine      engine      = new AesEngine();
            CbcBlockCipher blockCipher = new CbcBlockCipher(engine);                       //CBC

            PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher); //Default scheme is PKCS5/PKCS7

            KeyParameter     keyParam       = new KeyParameter(masterPw);
            ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, AndroidBackup.randomBytes(blockCipher.GetBlockSize() * 8), 0, blockCipher.GetBlockSize());

            // Encrypt
            cipher.Init(true, keyParamWithIV);

            Stream finalOutput = new CipherStream(ofstream, null, cipher);

            //  line 4: name of encryption algorithm
            headerbuf.Append(ENCRYPTION_ALGORITHM_NAME);
            headerbuf.Append('\n');
            //  line 5: user password salt [hex]
            headerbuf.Append(AndroidBackup.toHex(newUserSalt));
            headerbuf.Append('\n');
            //  line 6: master key checksum salt [hex]
            headerbuf.Append(AndroidBackup.toHex(checksumSalt));
            headerbuf.Append('\n');
            //  line 7: number of PBKDF2 rounds used [decimal]
            headerbuf.Append(PBKDF2_HASH_ROUNDS);
            headerbuf.Append('\n');
            //  line 8: IV of the user key [hex]
            //IBufferedCipher mkC = CipherUtilities.GetCipher(ENCRYPTION_MECHANISM);
            //Cipher mkC = Cipher.getInstance(ENCRYPTION_MECHANISM);
            //mkC.init(Cipher.ENCRYPT_MODE, userKey);


            AesEngine                 engine2         = new AesEngine();
            CbcBlockCipher            blockCipher2    = new CbcBlockCipher(engine2);                 //CBC
            PaddedBufferedBlockCipher mkC             = new PaddedBufferedBlockCipher(blockCipher2); //Default scheme is PKCS5/PKCS7
            KeyParameter              keyParam2       = new KeyParameter(userKey);
            ParametersWithIV          keyParamWithIV2 = new ParametersWithIV(keyParam2, AndroidBackup.randomBytes(blockCipher.GetBlockSize() * 8), 0, blockCipher2.GetBlockSize());

            // Encrypt
            mkC.Init(true, keyParamWithIV2);


            byte[] IV = keyParamWithIV2.GetIV();



            headerbuf.Append(AndroidBackup.toHex(IV));
            headerbuf.Append('\n');
            //  line 9: master IV + key blob, encrypted by the user key [hex]. Blob
            //  format:
            //  [byte] IV Length = Niv
            //  [array of Niv bytes] IV itself
            //  [byte] master key Length = Nmk
            //  [array of Nmk bytes] master key itself
            //  [byte] MK checksum hash Length = Nck
            //  [array of Nck bytes] master key checksum hash
            //
            //  The checksum is the (master key + checksum salt), run through the
            //  stated number of PBKDF2 rounds
            IV = keyParamWithIV.GetIV();
            byte[] mk       = keyParam.GetKey();
            byte[] checksum = AndroidBackup.makeKeyChecksum(mk, checksumSalt, PBKDF2_HASH_ROUNDS,
                                                            useUtf8);



            MemoryStream mkOut = new MemoryStream(IV.Length + (mk.Length + (checksum.Length + 3)));

            //DataOutputStream mkOut = new DataOutputStream(blob);

            mkOut.WriteByte((byte)IV.Length);
            mkOut.Write(IV, 0, IV.Length);
            mkOut.WriteByte((byte)mk.Length);
            mkOut.Write(mk, 0, mk.Length);
            mkOut.WriteByte((byte)checksum.Length);
            mkOut.Write(checksum, 0, checksum.Length);
            mkOut.Flush();
            byte[] encryptedMk = mkC.DoFinal(mkOut.GetBuffer());
            headerbuf.Append(AndroidBackup.toHex(encryptedMk));
            headerbuf.Append('\n');
            return(finalOutput);
        }
Exemple #22
0
        public override void PerformTest()
        {
            IBlockCipher cipher = new AesEngine();
            IMac         mac    = new CMac(cipher, 128);

            //128 bytes key

            KeyParameter key = new KeyParameter(keyBytes128);

            // 0 bytes message - 128 bytes key
            mac.Init(key);

            mac.BlockUpdate(input0, 0, input0.Length);

            byte[] outBytes = new byte[16];

            mac.DoFinal(outBytes, 0);

            if (!AreEqual(outBytes, output_k128_m0))
            {
                Fail("Failed - expected "
                     + Hex.ToHexString(output_k128_m0) + " got "
                     + Hex.ToHexString(outBytes));
            }

            // 16 bytes message - 128 bytes key
            mac.Init(key);

            mac.BlockUpdate(input16, 0, input16.Length);

            outBytes = new byte[16];

            mac.DoFinal(outBytes, 0);

            if (!AreEqual(outBytes, output_k128_m16))
            {
                Fail("Failed - expected "
                     + Hex.ToHexString(output_k128_m16) + " got "
                     + Hex.ToHexString(outBytes));
            }

            // 40 bytes message - 128 bytes key
            mac.Init(key);

            mac.BlockUpdate(input40, 0, input40.Length);

            outBytes = new byte[16];

            mac.DoFinal(outBytes, 0);

            if (!AreEqual(outBytes, output_k128_m40))
            {
                Fail("Failed - expected "
                     + Hex.ToHexString(output_k128_m40) + " got "
                     + Hex.ToHexString(outBytes));
            }

            // 64 bytes message - 128 bytes key
            mac.Init(key);

            mac.BlockUpdate(input64, 0, input64.Length);

            outBytes = new byte[16];

            mac.DoFinal(outBytes, 0);

            if (!AreEqual(outBytes, output_k128_m64))
            {
                Fail("Failed - expected "
                     + Hex.ToHexString(output_k128_m64) + " got "
                     + Hex.ToHexString(outBytes));
            }

            //192 bytes key
            key = new KeyParameter(keyBytes192);

            // 0 bytes message - 192 bytes key
            mac.Init(key);

            mac.BlockUpdate(input0, 0, input0.Length);

            outBytes = new byte[16];

            mac.DoFinal(outBytes, 0);

            if (!AreEqual(outBytes, output_k192_m0))
            {
                Fail("Failed - expected "
                     + Hex.ToHexString(output_k192_m0) + " got "
                     + Hex.ToHexString(outBytes));
            }

            // 16 bytes message - 192 bytes key
            mac.Init(key);

            mac.BlockUpdate(input16, 0, input16.Length);

            outBytes = new byte[16];

            mac.DoFinal(outBytes, 0);

            if (!AreEqual(outBytes, output_k192_m16))
            {
                Fail("Failed - expected "
                     + Hex.ToHexString(output_k192_m16) + " got "
                     + Hex.ToHexString(outBytes));
            }

            // 40 bytes message - 192 bytes key
            mac.Init(key);

            mac.BlockUpdate(input40, 0, input40.Length);

            outBytes = new byte[16];

            mac.DoFinal(outBytes, 0);

            if (!AreEqual(outBytes, output_k192_m40))
            {
                Fail("Failed - expected "
                     + Hex.ToHexString(output_k192_m40) + " got "
                     + Hex.ToHexString(outBytes));
            }

            // 64 bytes message - 192 bytes key
            mac.Init(key);

            mac.BlockUpdate(input64, 0, input64.Length);

            outBytes = new byte[16];

            mac.DoFinal(outBytes, 0);

            if (!AreEqual(outBytes, output_k192_m64))
            {
                Fail("Failed - expected "
                     + Hex.ToHexString(output_k192_m64) + " got "
                     + Hex.ToHexString(outBytes));
            }

            //256 bytes key

            key = new KeyParameter(keyBytes256);

            // 0 bytes message - 256 bytes key
            mac.Init(key);

            mac.BlockUpdate(input0, 0, input0.Length);

            outBytes = new byte[16];

            mac.DoFinal(outBytes, 0);

            if (!AreEqual(outBytes, output_k256_m0))
            {
                Fail("Failed - expected "
                     + Hex.ToHexString(output_k256_m0) + " got "
                     + Hex.ToHexString(outBytes));
            }

            // 16 bytes message - 256 bytes key
            mac.Init(key);

            mac.BlockUpdate(input16, 0, input16.Length);

            outBytes = new byte[16];

            mac.DoFinal(outBytes, 0);

            if (!AreEqual(outBytes, output_k256_m16))
            {
                Fail("Failed - expected "
                     + Hex.ToHexString(output_k256_m16) + " got "
                     + Hex.ToHexString(outBytes));
            }

            // 40 bytes message - 256 bytes key
            mac.Init(key);

            mac.BlockUpdate(input40, 0, input40.Length);

            outBytes = new byte[16];

            mac.DoFinal(outBytes, 0);

            if (!AreEqual(outBytes, output_k256_m40))
            {
                Fail("Failed - expected "
                     + Hex.ToHexString(output_k256_m40) + " got "
                     + Hex.ToHexString(outBytes));
            }

            // 64 bytes message - 256 bytes key
            mac.Init(key);

            mac.BlockUpdate(input64, 0, input64.Length);

            outBytes = new byte[16];

            mac.DoFinal(outBytes, 0);

            if (!AreEqual(outBytes, output_k256_m64))
            {
                Fail("Failed - expected "
                     + Hex.ToHexString(output_k256_m64) + " got "
                     + Hex.ToHexString(outBytes));
            }

            TestExceptions();
        }
        private static AlgorithmIdentifier DetermineKeyEncAlg(
            string algorithm, KeyParameter key)
        {
            if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(algorithm, "DES"))
            {
                return(new AlgorithmIdentifier(
                           PkcsObjectIdentifiers.IdAlgCms3DesWrap,
                           DerNull.Instance));
            }
            else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(algorithm, "RC2"))
            {
                return(new AlgorithmIdentifier(
                           PkcsObjectIdentifiers.IdAlgCmsRC2Wrap,
                           new DerInteger(58)));
            }
            else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(algorithm, "AES"))
            {
                int length = key.GetKey().Length * 8;
                DerObjectIdentifier wrapOid;

                if (length == 128)
                {
                    wrapOid = NistObjectIdentifiers.IdAes128Wrap;
                }
                else if (length == 192)
                {
                    wrapOid = NistObjectIdentifiers.IdAes192Wrap;
                }
                else if (length == 256)
                {
                    wrapOid = NistObjectIdentifiers.IdAes256Wrap;
                }
                else
                {
                    throw new ArgumentException("illegal keysize in AES");
                }

                return(new AlgorithmIdentifier(wrapOid));                 // parameters absent
            }
            else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(algorithm, "SEED"))
            {
                // parameters absent
                return(new AlgorithmIdentifier(KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap));
            }
            else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(algorithm, "CAMELLIA"))
            {
                int length = key.GetKey().Length * 8;
                DerObjectIdentifier wrapOid;

                if (length == 128)
                {
                    wrapOid = NttObjectIdentifiers.IdCamellia128Wrap;
                }
                else if (length == 192)
                {
                    wrapOid = NttObjectIdentifiers.IdCamellia192Wrap;
                }
                else if (length == 256)
                {
                    wrapOid = NttObjectIdentifiers.IdCamellia256Wrap;
                }
                else
                {
                    throw new ArgumentException("illegal keysize in Camellia");
                }

                return(new AlgorithmIdentifier(wrapOid));                // parameters must be absent
            }
            else
            {
                throw new ArgumentException("unknown algorithm");
            }
        }
Exemple #24
0
        /// <summary>
        /// Encrypt scoped PDU using DES encryption protocol
        /// </summary>
        /// <param name="unencryptedData">Unencrypted scoped PDU byte array</param>
        /// <param name="key">Encryption key. Key has to be at least 32 bytes is length</param>
        /// <param name="privacyParameters">Privacy parameters out buffer. This field will be filled in with information
        /// required to decrypt the information. Output length of this field is 8 bytes and space has to be reserved
        /// in the USM header to store this information</param>
        /// <returns>Encrypted byte array</returns>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when encryption key is null or length of the encryption key is too short.</exception>
        public static byte[] Encrypt(byte[] unencryptedData, byte[] key, byte[] privacyParameters)
        {
            if (unencryptedData == null)
            {
                throw new ArgumentNullException(nameof(unencryptedData));
            }

            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (privacyParameters == null)
            {
                throw new ArgumentNullException(nameof(privacyParameters));
            }

            if (key.Length < MinimumKeyLength)
            {
                throw new ArgumentException($"Encryption key length has to 32 bytes or more. Current: {key.Length}.", nameof(key));
            }

            var iv = GetIV(key, privacyParameters);

            // DES uses 8 byte keys but we need 16 to encrypt ScopedPdu. Get first 8 bytes and use them as encryption key
            var outKey = GetKey(key);

            var div = (int)Math.Floor(unencryptedData.Length / 8.0);

            if ((unencryptedData.Length % 8) != 0)
            {
                div += 1;
            }

            var newLength = div * 8;
            var result    = new byte[newLength];
            var buffer    = new byte[newLength];

            var inbuffer   = new byte[8];
            var outbuffer  = new byte[16];
            var cipherText = iv;
            var posIn      = 0;
            var posResult  = 0;

            Buffer.BlockCopy(unencryptedData, 0, buffer, 0, unencryptedData.Length);

            // Encrypt using BouncyCastle
            var blockCipher      = new DesEngine();
            var paddedCipher     = new PaddedBufferedBlockCipher(blockCipher, new ZeroBytePadding());
            var cipherParameters = new KeyParameter(outKey);

            paddedCipher.Init(true, cipherParameters);

            for (var b = 0; b < div; b++)
            {
                for (var i = 0; i < 8; i++)
                {
                    inbuffer[i] = (byte)(buffer[posIn] ^ cipherText[i]);
                    posIn++;
                }

                paddedCipher.DoFinal(inbuffer, outbuffer, 0);
                Buffer.BlockCopy(outbuffer, 0, cipherText, 0, cipherText.Length);
                Buffer.BlockCopy(cipherText, 0, result, posResult, cipherText.Length);
                posResult += cipherText.Length;
            }

            return(result);
        }
        public virtual void Init(
            bool forEncryption,
            ICipherParameters parameters)
        {
            this.forEncryption = forEncryption;
            this.macSize       = 16;       // TODO Make configurable?
            this.macBlock      = null;

            // TODO If macSize limitation is removed, be very careful about bufBlock
            int bufLength = forEncryption ? BlockSize : (BlockSize + macSize);

            this.bufBlock = new byte[bufLength];

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

                nonce = param.GetNonce();
                A     = param.GetAssociatedText();
                //            macSize = param.getMacSize() / 8;
                if (param.MacSize != 128)
                {
                    // TODO Make configurable?
                    throw new ArgumentException("only 128-bit MAC supported currently");
                }
                keyParam = param.Key;
            }
            else if (parameters is ParametersWithIV)
            {
                ParametersWithIV param = (ParametersWithIV)parameters;

                nonce    = param.GetIV();
                A        = null;
                keyParam = (KeyParameter)param.Parameters;
            }
            else
            {
                throw new ArgumentException("invalid parameters passed to GCM");
            }

            if (nonce == null || nonce.Length < 1)
            {
                throw new ArgumentException("IV must be at least 1 byte");
            }

            if (A == null)
            {
                // Avoid lots of null checks
                A = new byte[0];
            }

            // Cipher always used input forward mode
            cipher.Init(true, keyParam);

            // TODO This should be configurable by Init parameters
            // (but must be 16 if nonce length not 12) (BlockSize?)
            //        this.tagLength = 16;

            byte[] h = new byte[BlockSize];
            cipher.ProcessBlock(Zeroes, 0, h, 0);
            //trace("H: " + new string(Hex.encode(h)));
            this.H     = new BigInteger(1, h);
            this.initS = gHASH(A, false);

            if (nonce.Length == 12)
            {
                this.J0 = new byte[16];
                Array.Copy(nonce, 0, J0, 0, nonce.Length);
                this.J0[15] = 0x01;
            }
            else
            {
                BigInteger N = gHASH(nonce, true);
                BigInteger X = BigInteger.ValueOf(nonce.Length * 8);
                //trace("len({})||len(IV): " + dumpBigInt(X));

                N = multiply(N.Xor(X), H);
                //trace("GHASH(H,{},IV): " + dumpBigInt(N));
                this.J0 = asBlock(N);
            }

            this.S       = initS;
            this.counter = Arrays.Clone(J0);
            //trace("Y" + yCount + ": " + new string(Hex.encode(counter)));
            this.bufOff      = 0;
            this.totalLength = 0;
        }
        /// <exception cref="IOException"></exception>
        public TlsStreamCipher(TlsContext context, IStreamCipher clientWriteCipher,
                               IStreamCipher serverWriteCipher, IDigest clientWriteDigest, IDigest serverWriteDigest,
                               int cipherKeySize, bool usesNonce)
        {
            bool isServer = context.IsServer;

            this.context   = context;
            this.usesNonce = usesNonce;

            this.encryptCipher = clientWriteCipher;
            this.decryptCipher = serverWriteCipher;

            int key_block_size = (2 * cipherKeySize) + clientWriteDigest.GetDigestSize()
                                 + serverWriteDigest.GetDigestSize();

            byte[] key_block = TlsUtilities.CalculateKeyBlock(context, key_block_size);

            int offset = 0;

            // Init MACs
            TlsMac clientWriteMac = new TlsMac(context, clientWriteDigest, key_block, offset,
                                               clientWriteDigest.GetDigestSize());

            offset += clientWriteDigest.GetDigestSize();
            TlsMac serverWriteMac = new TlsMac(context, serverWriteDigest, key_block, offset,
                                               serverWriteDigest.GetDigestSize());

            offset += serverWriteDigest.GetDigestSize();

            // Build keys
            KeyParameter clientWriteKey = new KeyParameter(key_block, offset, cipherKeySize);

            offset += cipherKeySize;
            KeyParameter serverWriteKey = new KeyParameter(key_block, offset, cipherKeySize);

            offset += cipherKeySize;

            if (offset != key_block_size)
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            ICipherParameters encryptParams, decryptParams;

            if (isServer)
            {
                this.writeMac      = serverWriteMac;
                this.readMac       = clientWriteMac;
                this.encryptCipher = serverWriteCipher;
                this.decryptCipher = clientWriteCipher;
                encryptParams      = serverWriteKey;
                decryptParams      = clientWriteKey;
            }
            else
            {
                this.writeMac      = clientWriteMac;
                this.readMac       = serverWriteMac;
                this.encryptCipher = clientWriteCipher;
                this.decryptCipher = serverWriteCipher;
                encryptParams      = clientWriteKey;
                decryptParams      = serverWriteKey;
            }

            if (usesNonce)
            {
                byte[] dummyNonce = new byte[8];
                encryptParams = new ParametersWithIV(encryptParams, dummyNonce);
                decryptParams = new ParametersWithIV(decryptParams, dummyNonce);
            }

            this.encryptCipher.Init(true, encryptParams);
            this.decryptCipher.Init(false, decryptParams);
        }
        public static void SendKeyDown(IntPtr windowHandle, byte virtualKey)
        {
            var scanCode = GetScanCode(virtualKey);
              var keyParameter = new KeyParameter(1, scanCode, false, false, false, false);

              NativeMethods.PostMessage(windowHandle, (uint)KeyboardCommand.KeyDown, new UIntPtr(virtualKey), keyParameter.ToLParam());
        }
Exemple #28
0
        /// <exception cref="IOException"></exception>
        public TlsBlockCipher(TlsContext context, IBlockCipher clientWriteCipher, IBlockCipher serverWriteCipher,
                              IDigest clientWriteDigest, IDigest serverWriteDigest, int cipherKeySize)
        {
            this.context = context;

            this.randomData = new byte[256];
            context.NonceRandomGenerator.NextBytes(randomData);

            this.useExplicitIV  = TlsUtilities.IsTlsV11(context);
            this.encryptThenMac = context.SecurityParameters.encryptThenMac;

            int key_block_size = (2 * cipherKeySize) + clientWriteDigest.GetDigestSize()
                                 + serverWriteDigest.GetDigestSize();

            // From TLS 1.1 onwards, block ciphers don't need client_write_IV
            if (!useExplicitIV)
            {
                key_block_size += clientWriteCipher.GetBlockSize() + serverWriteCipher.GetBlockSize();
            }

            byte[] key_block = TlsUtilities.CalculateKeyBlock(context, key_block_size);

            int offset = 0;

            TlsMac clientWriteMac = new TlsMac(context, clientWriteDigest, key_block, offset,
                                               clientWriteDigest.GetDigestSize());

            offset += clientWriteDigest.GetDigestSize();
            TlsMac serverWriteMac = new TlsMac(context, serverWriteDigest, key_block, offset,
                                               serverWriteDigest.GetDigestSize());

            offset += serverWriteDigest.GetDigestSize();

            KeyParameter client_write_key = new KeyParameter(key_block, offset, cipherKeySize);

            offset += cipherKeySize;
            KeyParameter server_write_key = new KeyParameter(key_block, offset, cipherKeySize);

            offset += cipherKeySize;

            byte[] client_write_IV, server_write_IV;
            if (useExplicitIV)
            {
                client_write_IV = new byte[clientWriteCipher.GetBlockSize()];
                server_write_IV = new byte[serverWriteCipher.GetBlockSize()];
            }
            else
            {
                client_write_IV = Arrays.CopyOfRange(key_block, offset, offset + clientWriteCipher.GetBlockSize());
                offset         += clientWriteCipher.GetBlockSize();
                server_write_IV = Arrays.CopyOfRange(key_block, offset, offset + serverWriteCipher.GetBlockSize());
                offset         += serverWriteCipher.GetBlockSize();
            }

            if (offset != key_block_size)
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            ICipherParameters encryptParams, decryptParams;

            if (context.IsServer)
            {
                this.mWriteMac     = serverWriteMac;
                this.mReadMac      = clientWriteMac;
                this.encryptCipher = serverWriteCipher;
                this.decryptCipher = clientWriteCipher;
                encryptParams      = new ParametersWithIV(server_write_key, server_write_IV);
                decryptParams      = new ParametersWithIV(client_write_key, client_write_IV);
            }
            else
            {
                this.mWriteMac     = clientWriteMac;
                this.mReadMac      = serverWriteMac;
                this.encryptCipher = clientWriteCipher;
                this.decryptCipher = serverWriteCipher;
                encryptParams      = new ParametersWithIV(client_write_key, client_write_IV);
                decryptParams      = new ParametersWithIV(server_write_key, server_write_IV);
            }

            this.encryptCipher.Init(true, encryptParams);
            this.decryptCipher.Init(false, decryptParams);
        }
        private void checkVectors(
            int count,
            CcmBlockCipher ccm,
            string additionalDataType,
            byte[] k,
            int macSize,
            byte[] n,
            byte[] a,
            byte[] sa,
            byte[] p,
            byte[] t,
            byte[] c)
        {
            KeyParameter keyParam = (k == null) ? null : new KeyParameter(k);

            ccm.Init(true, new AeadParameters(keyParam, macSize, n, a));

            byte[] enc = new byte[c.Length];

            if (sa != null)
            {
                ccm.ProcessAadBytes(sa, 0, sa.Length);
            }

            int len = ccm.ProcessBytes(p, 0, p.Length, enc, 0);

            len += ccm.DoFinal(enc, len);

//			ccm.Init(true, new AeadParameters(new KeyParameter(k), macSize, n, a));
//
//			byte[] enc = ccm.ProcessPacket(p, 0, p.Length);

            if (!AreEqual(c, enc))
            {
                Fail("encrypted stream fails to match in test " + count + " with " + additionalDataType);
            }

//			ccm.Init(false, new AeadParameters(new KeyParameter(k), macSize, n, a));
//
//			byte[] dec = ccm.ProcessPacket(enc, 0, enc.Length);

            ccm.Init(false, new AeadParameters(new KeyParameter(k), macSize, n, a));

            byte[] tmp = new byte[enc.Length];

            if (sa != null)
            {
                ccm.ProcessAadBytes(sa, 0, sa.Length);
            }

            len = ccm.ProcessBytes(enc, 0, enc.Length, tmp, 0);

            len += ccm.DoFinal(tmp, len);

            byte[] dec = new byte[len];

            Array.Copy(tmp, 0, dec, 0, len);

            if (!AreEqual(p, dec))
            {
                Fail("decrypted stream fails to match in test " + count + " with " + additionalDataType,
                     Hex.ToHexString(p), Hex.ToHexString(dec));
            }

            if (!AreEqual(t, ccm.GetMac()))
            {
                Fail("MAC fails to match in test " + count + " with " + additionalDataType);
            }
        }
        /**
         * decrypt the content and return an input stream.
         */
        public override CmsTypedStream GetContentStream(
//			Key key)
            ICipherParameters key)
        {
            if (!(key is AsymmetricKeyParameter))
            {
                throw new ArgumentException("KeyAgreement requires asymmetric key", "key");
            }

            AsymmetricKeyParameter privKey = (AsymmetricKeyParameter)key;

            if (!privKey.IsPrivate)
            {
                throw new ArgumentException("Expected private key", "key");
            }

            try
            {
                OriginatorPublicKey    origK    = _info.Originator.OriginatorKey;
                PrivateKeyInfo         privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey);
                SubjectPublicKeyInfo   pubInfo  = new SubjectPublicKeyInfo(privInfo.AlgorithmID, origK.PublicKey.GetBytes());
                AsymmetricKeyParameter pubKey   = PublicKeyFactory.CreateKey(pubInfo);

                string wrapAlg = DerObjectIdentifier.GetInstance(
                    Asn1Sequence.GetInstance(_keyEncAlg.Parameters)[0]).Id;

                IBasicAgreement agreement = AgreementUtilities.GetBasicAgreementWithKdf(
                    _keyEncAlg.ObjectID, wrapAlg);

                agreement.Init(privKey);

                BigInteger wKeyNum = agreement.CalculateAgreement(pubKey);
                // TODO Fix the way bytes are derived from the secret
                byte[]       wKeyBytes = wKeyNum.ToByteArrayUnsigned();
                KeyParameter wKey      = ParameterUtilities.CreateKeyParameter(wrapAlg, wKeyBytes);

                IWrapper keyCipher = WrapperUtilities.GetWrapper(wrapAlg);

                keyCipher.Init(false, wKey);

                AlgorithmIdentifier aid = _encAlg;
                string alg = aid.ObjectID.Id;

                byte[] encryptedKey = _encryptedKey.GetOctets();
                byte[] sKeyBytes    = keyCipher.Unwrap(encryptedKey, 0, encryptedKey.Length);

                KeyParameter sKey = ParameterUtilities.CreateKeyParameter(alg, sKeyBytes);

                return(GetContentFromSessionKey(sKey));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
            catch (Exception e)
            {
                throw new CmsException("originator key invalid.", e);
            }
        }
 public ParametersWithIV(KeyParameter random, byte[] getEncoded, int i, int i1)
     : base(null, 0)
 {
     throw new System.NotImplementedException();
 }
Exemple #32
0
        public override KdfParameters GetBestParameters(uint uMilliseconds)
        {
            const ulong uStep = 3001;
            ulong       uRounds;

            KdfParameters p = GetDefaultParameters();

            // Try native method
            if (NativeLib.TransformKeyBenchmark256(uMilliseconds, out uRounds))
            {
                p.SetUInt64(ParamRounds, uRounds);
                return(p);
            }

            byte[] pbKey    = new byte[32];
            byte[] pbNewKey = new byte[32];
            for (int i = 0; i < pbKey.Length; ++i)
            {
                pbKey[i]    = (byte)i;
                pbNewKey[i] = (byte)i;
            }

#if KeePassUAP
            KeyParameter kp  = new KeyParameter(pbKey);
            AesEngine    aes = new AesEngine();
            aes.Init(true, kp);
#else
            byte[] pbIV = new byte[16];
            Array.Clear(pbIV, 0, pbIV.Length);

            RijndaelManaged r = new RijndaelManaged();
            if (r.BlockSize != 128)            // AES block size
            {
                Debug.Assert(false);
                r.BlockSize = 128;
            }

            r.IV      = pbIV;
            r.Mode    = CipherMode.ECB;
            r.KeySize = 256;
            r.Key     = pbKey;
            ICryptoTransform iCrypt = r.CreateEncryptor();

            // !iCrypt.CanReuseTransform -- doesn't work with Mono
            if ((iCrypt == null) || (iCrypt.InputBlockSize != 16) ||
                (iCrypt.OutputBlockSize != 16))
            {
                Debug.Assert(false, "Invalid ICryptoTransform.");
                Debug.Assert(iCrypt.InputBlockSize == 16, "Invalid input block size!");
                Debug.Assert(iCrypt.OutputBlockSize == 16, "Invalid output block size!");

                p.SetUInt64(ParamRounds, PwDefs.DefaultKeyEncryptionRounds);
                return(p);
            }
#endif

            uRounds = 0;
            int tStart = Environment.TickCount;
            while (true)
            {
                for (ulong j = 0; j < uStep; ++j)
                {
#if KeePassUAP
                    aes.ProcessBlock(pbNewKey, 0, pbNewKey, 0);
                    aes.ProcessBlock(pbNewKey, 16, pbNewKey, 16);
#else
                    iCrypt.TransformBlock(pbNewKey, 0, 16, pbNewKey, 0);
                    iCrypt.TransformBlock(pbNewKey, 16, 16, pbNewKey, 16);
#endif
                }

                uRounds += uStep;
                if (uRounds < uStep)                // Overflow check
                {
                    uRounds = ulong.MaxValue;
                    break;
                }

                uint tElapsed = (uint)(Environment.TickCount - tStart);
                if (tElapsed > uMilliseconds)
                {
                    break;
                }
            }

            p.SetUInt64(ParamRounds, uRounds);
            return(p);
        }
        public static void SendShiftKeyUp(IntPtr windowHandle)
        {
            var virtualKey = VK_SHIFT;
              var scanCode = GetScanCode(virtualKey);
              var keyParameter = new KeyParameter(1, scanCode, false, false, true, true);

              NativeMethods.PostMessage(windowHandle, (uint)KeyboardCommand.KeyUp, new UIntPtr(virtualKey), keyParameter.ToLParam());
        }