Пример #1
0
        /**
         * initialise a RC5-32 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)
        {
            if (parameters is RC5Parameters)
            {
                RC5Parameters p = (RC5Parameters)parameters;

                _noRounds = p.Rounds;

                SetKey(p.GetKey());
            }
            else if (parameters is KeyParameter)
            {
                KeyParameter p = (KeyParameter)parameters;

                SetKey(p.GetKey());
            }
            else
            {
                throw new ArgumentException("invalid parameter passed to RC532 init - " + parameters.GetType().ToString());
            }

            this.forEncryption = forEncryption;
        }
Пример #2
0
        public virtual void Init(bool forEncryption, ICipherParameters parameters)
        {
            //IL_000d: Unknown result type (might be due to invalid IL or missing references)
            //IL_002c: Unknown result type (might be due to invalid IL or missing references)
            //IL_0071: Unknown result type (might be due to invalid IL or missing references)
            if (!(parameters is ParametersWithIV))
            {
                throw new ArgumentException("VMPC Init parameters must include an IV");
            }
            ParametersWithIV parametersWithIV = (ParametersWithIV)parameters;

            if (!(parametersWithIV.Parameters is KeyParameter))
            {
                throw new ArgumentException("VMPC Init parameters must include a key");
            }
            KeyParameter keyParameter = (KeyParameter)parametersWithIV.Parameters;

            workingIV = parametersWithIV.GetIV();
            if (workingIV == null || workingIV.Length < 1 || workingIV.Length > 768)
            {
                throw new ArgumentException("VMPC requires 1 to 768 bytes of IV");
            }
            workingKey = keyParameter.GetKey();
            InitKey(workingKey, workingIV);
        }
Пример #3
0
        /**
         * initialise a RC5-32 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 virtual void Init(
            bool forEncryption,
            ICipherParameters parameters)
        {
            if (typeof(RC5Parameters).IsInstanceOfType(parameters))
            {
                RC5Parameters p = (RC5Parameters)parameters;

                _noRounds = p.Rounds;

                SetKey(p.GetKey());
            }
            else if (typeof(KeyParameter).IsInstanceOfType(parameters))
            {
                KeyParameter p = (KeyParameter)parameters;

                SetKey(p.GetKey());
            }
            else
            {
                throw new ArgumentException("invalid parameter passed to RC532 init - " + Platform.GetTypeName(parameters));
            }

            this.forEncryption = forEncryption;
        }
Пример #4
0
        public TlsMac(TlsContext context, IDigest digest, byte[] key, int keyOff, int keyLen)
        {
            this.context = context;
            KeyParameter parameters = new KeyParameter(key, keyOff, keyLen);

            this.secret = Arrays.Clone(parameters.GetKey());
            if (digest is LongDigest)
            {
                this.digestBlockSize = 0x80;
                this.digestOverhead  = 0x10;
            }
            else
            {
                this.digestBlockSize = 0x40;
                this.digestOverhead  = 8;
            }
            if (TlsUtilities.IsSsl(context))
            {
                this.mac = new Ssl3Mac(digest);
                if (digest.GetDigestSize() == 20)
                {
                    this.digestOverhead = 4;
                }
            }
            else
            {
                this.mac = new HMac(digest);
            }
            this.mac.Init(parameters);
            this.macLength = this.mac.GetMacSize();
            if (context.SecurityParameters.truncatedHMac)
            {
                this.macLength = Math.Min(this.macLength, 10);
            }
        }
Пример #5
0
        /**
         * initialise a RC5-32 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)
        {
            if (parameters != null && typeof(RC5Parameters).GetTypeInfo().IsAssignableFrom(parameters.GetType().GetTypeInfo()))
            {
                RC5Parameters p = (RC5Parameters)parameters;

                _noRounds = p.Rounds;

                SetKey(p.GetKey());
            }
            else if (parameters != null && typeof(KeyParameter).GetTypeInfo().IsAssignableFrom(parameters.GetType().GetTypeInfo()))
            {
                KeyParameter p = (KeyParameter)parameters;

                SetKey(p.GetKey());
            }
            else
            {
                throw new ArgumentException("invalid parameter passed to RC532 init - " + parameters.GetType().ToString());
            }

            this.forEncryption = forEncryption;
        }
Пример #6
0
        public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
        {
            byte[] keyBytes = contentEncryptionKey.GetKey();

            string   rfc3211WrapperName = Helper.GetRfc3211WrapperName(keyEncryptionKeyOID);
            IWrapper keyWrapper         = Helper.CreateWrapper(rfc3211WrapperName);

            // Note: In Java build, the IV is automatically generated in JCE layer
            int ivLength = rfc3211WrapperName.StartsWith("DESEDE") ? 8 : 16;

            byte[] iv = new byte[ivLength];
            random.NextBytes(iv);

            ICipherParameters parameters = new ParametersWithIV(keyEncryptionKey, iv);

            keyWrapper.Init(true, new ParametersWithRandom(parameters, random));
            Asn1OctetString encryptedKey = new DerOctetString(
                keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

            DerSequence seq = new DerSequence(
                new DerObjectIdentifier(keyEncryptionKeyOID),
                new DerOctetString(iv));

            AlgorithmIdentifier keyEncryptionAlgorithm = new AlgorithmIdentifier(
                PkcsObjectIdentifiers.IdAlgPwriKek, seq);

            return(new RecipientInfo(new PasswordRecipientInfo(
                                         keyDerivationAlgorithm, keyEncryptionAlgorithm, encryptedKey)));
        }
Пример #7
0
        public virtual void Init(bool forEncryption, ICipherParameters parameters)
        {
            ParametersWithIV parametersWithIV = parameters as ParametersWithIV;

            if (parametersWithIV == null)
            {
                throw new ArgumentException(this.AlgorithmName + " Init requires an IV", "parameters");
            }
            byte[] iV = parametersWithIV.GetIV();
            if (iV == null || iV.Length != this.NonceSize)
            {
                throw new ArgumentException(string.Concat(new object[]
                {
                    this.AlgorithmName,
                    " requires exactly ",
                    this.NonceSize,
                    " bytes of IV"
                }));
            }
            KeyParameter keyParameter = parametersWithIV.Parameters as KeyParameter;

            if (keyParameter == null)
            {
                throw new ArgumentException(this.AlgorithmName + " Init requires a key", "parameters");
            }
            this.SetKey(keyParameter.GetKey(), iV);
            this.Reset();
            this.initialised = true;
        }
Пример #8
0
        public TlsMac(TlsContext context, IDigest digest, byte[] key, int keyOff, int keyLen)
        {
            this.context = context;
            KeyParameter keyParameter = new KeyParameter(key, keyOff, keyLen);

            secret = Arrays.Clone(keyParameter.GetKey());
            if (digest is LongDigest)
            {
                digestBlockSize = 128;
                digestOverhead  = 16;
            }
            else
            {
                digestBlockSize = 64;
                digestOverhead  = 8;
            }
            if (TlsUtilities.IsSsl(context))
            {
                mac = new Ssl3Mac(digest);
                if (digest.GetDigestSize() == 20)
                {
                    digestOverhead = 4;
                }
            }
            else
            {
                mac = new HMac(digest);
            }
            mac.Init(keyParameter);
            macLength = mac.GetMacSize();
            if (context.SecurityParameters.truncatedHMac)
            {
                macLength = Math.Min(macLength, 10);
            }
        }
Пример #9
0
        public static string RSAEncrypt(string pemStreamText, KeyParameter secretKeyParameter)
        {
            string result = string.Empty;

            try
            {
                RsaKeyParameters rsaKeyParameters            = null;
                StreamReader     reader                      = new StreamReader(new MemoryStream(Convert.FromBase64String(pemStreamText)));
                Org.BouncyCastle.OpenSsl.PemReader pemReader = new Org.BouncyCastle.OpenSsl.PemReader(reader);
                PemObject pemObject = pemReader.ReadPemObject();
                if (pemObject != null)
                {
                    AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(pemObject.Content);
                    rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;
                }
                else
                {
                    rsaKeyParameters = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(pemStreamText));
                }
                byte[]          key    = secretKeyParameter.GetKey();
                IBufferedCipher cipher = CipherUtilities.GetCipher("RSA/ECB/OAEPWithSHA_1AndMGF1Padding");
                cipher.Init(forEncryption: true, rsaKeyParameters);
                byte[] inArray = BlockCipher(key, cipher, isEncrypt: true);
                result = Convert.ToBase64String(inArray, Base64FormattingOptions.None);
            }
            catch (Exception ex)
            {
                Debug.LogError("### SwrveManagerUtils::RSAEncrypt: " + ex.Message);
            }
            return(result);
        }
Пример #10
0
        /**
         * initialise
         *
         * @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 virtual void Init(bool forEncryption, ICipherParameters parameters)
        {
            if (!(parameters is KeyParameter))
            {
                throw new ArgumentException("Invalid parameters passed to Noekeon init - "
                                            + Platform.GetTypeName(parameters), "parameters");
            }

            this._forEncryption = forEncryption;
            this._initialised   = true;

            KeyParameter p = (KeyParameter)parameters;

            Pack.BE_To_UInt32(p.GetKey(), 0, k, 0, 4);

            if (!forEncryption)
            {
                // theta(k, new uint[]{ 0x00, 0x00, 0x00, 0x00 });
                {
                    uint a0 = k[0], a1 = k[1], a2 = k[2], a3 = k[3];

                    uint t = a0 ^ a2;
                    t  ^= Integers.RotateLeft(t, 8) ^ Integers.RotateLeft(t, 24);
                    a1 ^= t;
                    a3 ^= t;

                    t   = a1 ^ a3;
                    t  ^= Integers.RotateLeft(t, 8) ^ Integers.RotateLeft(t, 24);
                    a0 ^= t;
                    a2 ^= t;

                    k[0] = a0; k[1] = a1; k[2] = a2; k[3] = a3;
                }
            }
        }
Пример #11
0
        public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
        {
            byte[] keyBytes = contentEncryptionKey.GetKey();
            AlgorithmIdentifier keyEncryptionAlgorithm = info.AlgorithmID;

            IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionAlgorithm.Algorithm.Id);

            keyWrapper.Init(true, new ParametersWithRandom(recipientPublicKey, random));
            byte[] encryptedKeyBytes = keyWrapper.Wrap(keyBytes, 0, keyBytes.Length);

            RecipientIdentifier recipId;

            if (recipientTbsCert != null)
            {
                IssuerAndSerialNumber issuerAndSerial = new IssuerAndSerialNumber(
                    recipientTbsCert.Issuer, recipientTbsCert.SerialNumber.Value);
                recipId = new RecipientIdentifier(issuerAndSerial);
            }
            else
            {
                recipId = new RecipientIdentifier(subjectKeyIdentifier);
            }

            return(new RecipientInfo(new KeyTransRecipientInfo(recipId, keyEncryptionAlgorithm,
                                                               new DerOctetString(encryptedKeyBytes))));
        }
Пример #12
0
        public byte[] computeSharedSecret(byte[] pri, byte[] pub)
        {
            const string Algorithm = "ECDH";
            //const int KeyBitSize = 128;

            X9ECParameters     ecPars    = NistNamedCurves.GetByName("P-256");
            ECDomainParameters ecDomPars = new ECDomainParameters(ecPars.Curve, ecPars.G, ecPars.N, ecPars.H, ecPars.GetSeed());
            var curve = ecDomPars.Curve;

            var pubQ = curve.DecodePoint(pub);
            //ECPoint pubQ = ecPars.Curve.DecodePoint(pub);
            //ECPoint priQ = curve.DecodePoint(pri);
            IBasicAgreement _aliceKeyAgree = AgreementUtilities.GetBasicAgreement(Algorithm);

            //csPri = ((ECPrivateKeyParameters)aliceKeyPair.Private).D.ToByteArray();
            var priKeyPara = new ECPrivateKeyParameters(new BigInteger(pri), ecDomPars);            //priQ.Curve.

            _aliceKeyAgree.Init(priKeyPara);

            AsymmetricKeyParameter pubKeyPara = new ECPublicKeyParameters(pubQ, ecDomPars);
            //SubjectPublicKeyInfo _key = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKeyPara);
            //var pubPara = new ECPublicKeyParameters(priQ, ecDomPars);
            BigInteger aliceAgree = _aliceKeyAgree.CalculateAgreement(pubKeyPara);

            KeyParameter sharedKey = new KeyParameter(aliceAgree.ToByteArrayUnsigned());

            //return sharedKey.;
            return(sharedKey.GetKey());
        }
Пример #13
0
        private void DoTestHMac(string hmacName, int defKeySize, byte[] output)
        {
            KeyParameter key = new KeyParameter(keyBytes); //, hmacName);

            IMac mac = MacUtilities.GetMac(hmacName);

            mac.Init(key);
            mac.Reset();
            mac.BlockUpdate(message, 0, message.Length);
            byte[] outBytes = MacUtilities.DoFinal(mac);

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

            CipherKeyGenerator kGen = GeneratorUtilities.GetKeyGenerator(hmacName);

            key = new KeyParameter(kGen.GenerateKey());
            mac.Init(key); // hmacName
            mac.BlockUpdate(message, 0, message.Length);
            outBytes = MacUtilities.DoFinal(mac);

            IsTrue("default key wrong length", key.GetKey().Length == (defKeySize / 8));
        }
Пример #14
0
        public virtual void Init(ICipherParameters parameters)
        {
            if (!(parameters is ParametersWithIV))
            {
                throw new ArgumentException("VMPC-MAC Init parameters must include an IV", "parameters");
            }

            ParametersWithIV ivParams = (ParametersWithIV)parameters;
            KeyParameter     key      = (KeyParameter)ivParams.Parameters;

            if (!(ivParams.Parameters is KeyParameter))
            {
                throw new ArgumentException("VMPC-MAC Init parameters must include a key", "parameters");
            }

            this.workingIV = ivParams.GetIV();

            if (workingIV == null || workingIV.Length < 1 || workingIV.Length > 768)
            {
                throw new ArgumentException("VMPC-MAC requires 1 to 768 bytes of IV", "parameters");
            }

            this.workingKey = key.GetKey();

            Reset();
        }
Пример #15
0
        /// <summary>
        /// Initialises the Poly1305 MAC.
        /// </summary>
        /// <param name="parameters">a {@link ParametersWithIV} containing a 128 bit nonce and a {@link KeyParameter} with
        ///          a 256 bit key complying to the {@link Poly1305KeyGenerator Poly1305 key format}.</param>
        public void Init(ICipherParameters parameters)
        {
            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 ivParams = (ParametersWithIV)parameters;
                nonce      = ivParams.GetIV();
                parameters = ivParams.Parameters;
            }

            if (!(parameters is KeyParameter))
            {
                throw new ArgumentException("Poly1305 requires a key.");
            }

            KeyParameter keyParams = (KeyParameter)parameters;

            SetKey(keyParams.GetKey(), nonce);

            Reset();
        }
Пример #16
0
        /// <summary>
        /// Simple Decryption and Authentication of a UTF8 message
        /// using a key derived from a password
        /// </summary>
        /// <param name="encryptedMessage">The encrypted message.</param>
        /// <param name="password">The password.</param>
        /// <param name="nonSecretPayloadLength">Length of the non secret payload.</param>
        /// <returns>
        /// Decrypted Message
        /// </returns>
        /// <exception cref="System.ArgumentException">Must have a password of minimum length;password</exception>
        /// <remarks>
        /// Significantly less secure than using random binary keys.
        /// </remarks>
        public static byte[] SimpleDecryptWithPassword(byte[] encryptedMessage, string password, int nonSecretPayloadLength = 0)
        {
            //User Error Checks
            if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)
            {
                throw new ArgumentException($"Must have a password of at least {MinPasswordLength} characters!", nameof(password));
            }

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

            Pkcs5S2ParametersGenerator generator = new Pkcs5S2ParametersGenerator();

            //Grab Salt from Payload
            byte[] salt = new byte[SaltBitSize / 8];
            Array.Copy(encryptedMessage, nonSecretPayloadLength, salt, 0, salt.Length);

            generator.Init(
                PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()),
                salt,
                Iterations);

            //Generate Key
            KeyParameter key = (KeyParameter)generator.GenerateDerivedMacParameters(KeyBitSize);

            return(SimpleDecrypt(encryptedMessage, key.GetKey(), salt.Length + nonSecretPayloadLength));
        }
Пример #17
0
        public virtual 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(AlgorithmName + " Init requires an IV", "parameters");
            }

            byte[] iv = ivParams.GetIV();

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

            KeyParameter key = ivParams.Parameters as KeyParameter;

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

            SetKey(key.GetKey(), iv);
            Reset();
            initialised = true;
        }
Пример #18
0
        public void Init(ICipherParameters parameters)
        {
            KeyParameter param = null;

            param = parameters as KeyParameter;

            if (param == null)
            {
                throw new ArgumentException("Bad parameters passed");
            }

            byte[] key = param.GetKey();

            paddedKey = Pad(key, 0, key.Length);

            inversedKey = new byte[key.Length];
            Array.Copy(key, inversedKey, key.Length);


            //Inverse each byte in key
            for (int i = 0; i < inversedKey.Length; i++)
            {
                inversedKey[i] ^= 0xFF;
            }
        }
		public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
		{
			byte[] key = contentEncryptionKey.GetKey();
			IWrapper wrapper = KekRecipientInfoGenerator.Helper.CreateWrapper(this.keyEncryptionAlgorithm.ObjectID.Id);
			wrapper.Init(true, new ParametersWithRandom(this.keyEncryptionKey, random));
			Asn1OctetString encryptedKey = new DerOctetString(wrapper.Wrap(key, 0, key.Length));
			return new RecipientInfo(new KekRecipientInfo(this.kekIdentifier, this.keyEncryptionAlgorithm, encryptedKey));
		}
Пример #20
0
 private void checkKeyParameter(
     KeyParameter key,
     Type expectedType,
     byte[]                  expectedBytes)
 {
     Assert.IsTrue(expectedType.IsInstanceOfType(key));
     Assert.IsTrue(Arrays.AreEqual(expectedBytes, key.GetKey()));
 }
Пример #21
0
        public void Init(ICipherParameters parameters)
        {
            KeyParameter kParam = (KeyParameter)parameters;

            this.key         = Arrays.Clone(kParam.GetKey());
            this.initialised = true;
            Reset();
        }
Пример #22
0
 private byte[] CreateSessionInfo(SymmetricKeyAlgorithmTag algorithm, KeyParameter key)
 {
     byte[] key2  = key.GetKey();
     byte[] array = new byte[key2.Length + 3];
     array[0] = (byte)algorithm;
     ((global::System.Array)key2).CopyTo((global::System.Array)array, 1);
     AddCheckSum(array);
     return(array);
 }
Пример #23
0
        private static byte[] SingleIterationPBKDF2(byte[] P, byte[] S, int dkLen)
        {
            PbeParametersGenerator pGen = new Pkcs5S2ParametersGenerator(new Sha256Digest());

            pGen.Init(P, S, 1);
            KeyParameter key = (KeyParameter)pGen.GenerateDerivedMacParameters(dkLen * 8);

            return(key.GetKey());
        }
Пример #24
0
        public void Init(bool pEncrypt,
                         ICipherParameters cipherParameters)
        {
            /* Set defaults */
            byte[]       myInitialAEAD = null;
            byte[]       myNonce       = null;
            KeyParameter myKey         = null;

            /* Access parameters */
            if (cipherParameters is AeadParameters)
            {
                AeadParameters myAEAD = (AeadParameters)cipherParameters;
                myInitialAEAD = myAEAD.GetAssociatedText();
                myNonce       = myAEAD.GetNonce();
                myKey         = myAEAD.Key;
            }
            else if (cipherParameters is ParametersWithIV)
            {
                ParametersWithIV myParms = (ParametersWithIV)cipherParameters;
                myNonce = myParms.GetIV();
                myKey   = (KeyParameter)myParms.Parameters;
            }
            else
            {
                throw new ArgumentException("invalid parameters passed to GCM_SIV");
            }

            /* Check nonceSize */
            if (myNonce == null || myNonce.Length != NONCELEN)
            {
                throw new ArgumentException("Invalid nonce");
            }

            /* Check keysize */
            if (myKey == null)
            {
                throw new ArgumentException("Invalid key");
            }

            byte[] k = myKey.GetKey();

            if (k.Length != BUFLEN &&
                k.Length != (BUFLEN << 1))
            {
                throw new ArgumentException("Invalid key");
            }

            /* Reset details */
            forEncryption  = pEncrypt;
            theInitialAEAD = myInitialAEAD;
            theNonce       = myNonce;

            /* Initialise the keys */
            deriveKeys(myKey);
            resetStreams();
        }
        private static byte[] CreateSessionInfo(SymmetricKeyAlgorithmTag algorithm, KeyParameter key)
        {
            var keyBytes    = key.GetKey();
            var sessionInfo = new byte[keyBytes.Length + 3];

            sessionInfo[0] = (byte)algorithm;
            keyBytes.CopyTo(sessionInfo, 1);
            AddCheckSum(sessionInfo);
            return(sessionInfo);
        }
Пример #26
0
        public virtual void Init(bool forEncryption, ICipherParameters parameters)
        {
            if (!(parameters is KeyParameter))
            {
                throw new ArgumentException("invalid parameter passed to ISAAC Init - " + parameters.GetType().Name, "parameters");
            }
            KeyParameter keyParameter = (KeyParameter)parameters;

            this.setKey(keyParameter.GetKey());
        }
        protected virtual byte[] GenerateWrappedKey(KeyParameter contentEncryptionKey)
        {
            byte[] keyBytes = contentEncryptionKey.GetKey();
            AlgorithmIdentifier keyEncryptionAlgorithm = info.AlgorithmID;

            IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionAlgorithm.Algorithm.Id);

            keyWrapper.Init(true, new ParametersWithRandom(recipientPublicKey, random));
            return(keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));
        }
Пример #28
0
        protected bool InitializeAESKey()
        {
            _AesParameters = new KeyParameter(Hex.Decode(_KeyValue));
            _AesEngine     = new AesEngine();
            _AesEngine.Init(true, _AesParameters);

            theKey = _AesParameters.GetKey();

            return(false);
        }
Пример #29
0
        /**
         * Derive Keys.
         * @param pKey the keyGeneration key
         */
        private void deriveKeys(KeyParameter pKey)
        {
            /* Create the buffers */
            byte[] myIn     = new byte[BUFLEN];
            byte[] myOut    = new byte[BUFLEN];
            byte[] myResult = new byte[BUFLEN];
            byte[] myEncKey = new byte[pKey.GetKey().Length];

            /* Prepare for encryption */
            Array.Copy(theNonce, 0, myIn, BUFLEN - NONCELEN, NONCELEN);
            theCipher.Init(true, pKey);

            /* Derive authentication key */
            int myOff = 0;

            theCipher.ProcessBlock(myIn, 0, myOut, 0);
            Array.Copy(myOut, 0, myResult, myOff, HALFBUFLEN);
            myIn[0]++;
            myOff += HALFBUFLEN;
            theCipher.ProcessBlock(myIn, 0, myOut, 0);
            Array.Copy(myOut, 0, myResult, myOff, HALFBUFLEN);

            /* Derive encryption key */
            myIn[0]++;
            myOff = 0;
            theCipher.ProcessBlock(myIn, 0, myOut, 0);
            Array.Copy(myOut, 0, myEncKey, myOff, HALFBUFLEN);
            myIn[0]++;
            myOff += HALFBUFLEN;
            theCipher.ProcessBlock(myIn, 0, myOut, 0);
            Array.Copy(myOut, 0, myEncKey, myOff, HALFBUFLEN);

            /* If we have a 32byte key */
            if (myEncKey.Length == BUFLEN << 1)
            {
                /* Derive remainder of encryption key */
                myIn[0]++;
                myOff += HALFBUFLEN;
                theCipher.ProcessBlock(myIn, 0, myOut, 0);
                Array.Copy(myOut, 0, myEncKey, myOff, HALFBUFLEN);
                myIn[0]++;
                myOff += HALFBUFLEN;
                theCipher.ProcessBlock(myIn, 0, myOut, 0);
                Array.Copy(myOut, 0, myEncKey, myOff, HALFBUFLEN);
            }

            /* Initialise the Cipher */
            theCipher.Init(true, new KeyParameter(myEncKey));

            /* Initialise the multiplier */
            fillReverse(myResult, 0, BUFLEN, myOut);
            mulX(myOut);
            theMultiplier.Init(myOut);
            theFlags |= INIT;
        }
Пример #30
0
        public virtual void Init(bool forEncryption, ICipherParameters parameters)
        {
            KeyParameter keyParameter = parameters as KeyParameter;

            if (keyParameter == null)
            {
                throw new ArgumentException("invalid parameter passed to AES init - " + parameters.GetType().Name);
            }
            WorkingKey         = GenerateWorkingKey(keyParameter.GetKey(), forEncryption);
            this.forEncryption = forEncryption;
        }