protected override byte[] engineGenerateKey()
 {
     byte[] array = new byte[8];
     do
     {
         random.NextBytes(array);
         DesParameters.SetOddParity(array);
     }while (DesParameters.IsWeakKey(array, 0));
     return(array);
 }
Exemplo n.º 2
0
 protected override byte[] engineGenerateKey()
 {
     byte[] array;
     do
     {
         array = this.random.GenerateSeed(this.strength);
         DesParameters.SetOddParity(array);
     }while (DesEdeParameters.IsWeakKey(array, 0, array.Length));
     return(array);
 }
 protected override byte[] engineGenerateKey()
 {
     byte[] array = new byte[strength];
     do
     {
         random.NextBytes(array);
         DesParameters.SetOddParity(array);
     }while (DesEdeParameters.IsWeakKey(array, 0, array.Length) || !DesEdeParameters.IsRealEdeKey(array, 0));
     return(array);
 }
Exemplo n.º 4
0
 public static bool IsWeakKey(byte[] key, int offset, int length)
 {
     for (int i = offset; i < length; i += 8)
     {
         if (DesParameters.IsWeakKey(key, i))
         {
             return(true);
         }
     }
     return(false);
 }
Exemplo n.º 5
0
        protected override byte[] engineGenerateKey()
        {
            byte[] newKey;

            do
            {
                newKey = random.GenerateSeed(DesParameters.DesKeyLength);
                DesParameters.SetOddParity(newKey);
            }while (DesParameters.IsWeakKey(newKey, 0));

            return(newKey);
        }
        protected override byte[] engineGenerateKey()
        {
            byte[] newKey = new byte[DesParameters.DesKeyLength];

            do
            {
                random.NextBytes(newKey);
                DesParameters.SetOddParity(newKey);
            }while (DesParameters.IsWeakKey(newKey, 0));

            return(newKey);
        }
Exemplo n.º 7
0
 private void PadKey(byte[] keyMaster, int keyOff, byte[] tmp, int tmpOff)
 {
     tmp[tmpOff]     = (byte)(keyMaster[keyOff] & 0xFE);
     tmp[tmpOff + 1] = (byte)((keyMaster[keyOff] << 7) | ((keyMaster[keyOff + 1] & 0xFC) >> 1));
     tmp[tmpOff + 2] = (byte)((keyMaster[keyOff + 1] << 6) | ((keyMaster[keyOff + 2] & 0xF8) >> 2));
     tmp[tmpOff + 3] = (byte)((keyMaster[keyOff + 2] << 5) | ((keyMaster[keyOff + 3] & 0xF0) >> 3));
     tmp[tmpOff + 4] = (byte)((keyMaster[keyOff + 3] << 4) | ((keyMaster[keyOff + 4] & 0xE0) >> 4));
     tmp[tmpOff + 5] = (byte)((keyMaster[keyOff + 4] << 3) | ((keyMaster[keyOff + 5] & 0xC0) >> 5));
     tmp[tmpOff + 6] = (byte)((keyMaster[keyOff + 5] << 2) | ((keyMaster[keyOff + 6] & 0x80) >> 6));
     tmp[tmpOff + 7] = (byte)(keyMaster[keyOff + 6] << 1);
     DesParameters.SetOddParity(tmp, tmpOff, 8);
 }
Exemplo n.º 8
0
        public ITestResult Perform()
        {
            try
            {
//				IBufferedCipher cipher = CipherUtilities.GetCipher("DES/ECB/PKCS5Padding");
                IWrapper cipher = WrapperUtilities.GetWrapper("DES/ECB/PKCS5Padding");

                IAsymmetricCipherKeyPairGenerator fact = GeneratorUtilities.GetKeyPairGenerator("RSA");
                fact.Init(
                    new RsaKeyGenerationParameters(
                        BigInteger.ValueOf(0x10001),
                        new SecureRandom(),
                        512,
                        25));

                AsymmetricCipherKeyPair keyPair = fact.GenerateKeyPair();

                AsymmetricKeyParameter priKey = keyPair.Private;
                AsymmetricKeyParameter pubKey = keyPair.Public;

                byte[] priKeyBytes = PrivateKeyInfoFactory.CreatePrivateKeyInfo(priKey).GetDerEncoded();

                CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator("DES");

//				Key wrapKey = keyGen.generateKey();
                byte[]       wrapKeyBytes = keyGen.GenerateKey();
                KeyParameter wrapKey      = new DesParameters(wrapKeyBytes);

//				cipher.Init(IBufferedCipher.WRAP_MODE, wrapKey);
                cipher.Init(true, wrapKey);
//				byte[] wrappedKey = cipher.Wrap(priKey);
                byte[] wrappedKey = cipher.Wrap(priKeyBytes, 0, priKeyBytes.Length);

//				cipher.Init(IBufferedCipher.UNWRAP_MODE, wrapKey);
                cipher.Init(false, wrapKey);

//				Key key = cipher.unwrap(wrappedKey, "RSA", IBufferedCipher.PRIVATE_KEY);
                byte[] unwrapped = cipher.Unwrap(wrappedKey, 0, wrappedKey.Length);

                //if (!Arrays.AreEqual(priKey.getEncoded(), key.getEncoded()))
                if (!Arrays.AreEqual(priKeyBytes, unwrapped))
                {
                    return(new SimpleTestResult(false, "Unwrapped key does not match"));
                }

                return(new SimpleTestResult(true, Name + ": Okay"));
            }
            catch (Exception e)
            {
                return(new SimpleTestResult(false, Name + ": exception - " + e.ToString()));
            }
        }
Exemplo n.º 9
0
        private static ICipherParameters FixDesParity(string mechanism, ICipherParameters parameters)
        {
            if (!Platform.EndsWith(mechanism, "DES-CBC") && !Platform.EndsWith(mechanism, "DESEDE-CBC"))
            {
                return(parameters);
            }
            if (parameters is ParametersWithIV)
            {
                ParametersWithIV parametersWithIV = (ParametersWithIV)parameters;
                return(new ParametersWithIV(FixDesParity(mechanism, parametersWithIV.Parameters), parametersWithIV.GetIV()));
            }
            KeyParameter keyParameter = (KeyParameter)parameters;

            byte[] key = keyParameter.GetKey();
            DesParameters.SetOddParity(key);
            return(new KeyParameter(key));
        }
Exemplo n.º 10
0
        private static ICipherParameters FixDesParity(string mechanism, ICipherParameters parameters)
        {
            if (!mechanism.EndsWith("DES-CBC") & !mechanism.EndsWith("DESEDE-CBC"))
            {
                return(parameters);
            }

            if (parameters is ParametersWithIV)
            {
                ParametersWithIV ivParams = (ParametersWithIV)parameters;
                return(new ParametersWithIV(FixDesParity(mechanism, ivParams.Parameters), ivParams.GetIV()));
            }

            KeyParameter kParam = (KeyParameter)parameters;

            byte[] keyBytes = kParam.GetKey();
            DesParameters.SetOddParity(keyBytes);
            return(new KeyParameter(keyBytes));
        }
Exemplo n.º 11
0
        private static ICipherParameters FixDesParity(string mechanism, ICipherParameters parameters)
        {
            if (!BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "DES-CBC") && !BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "DESEDE-CBC"))
            {
                return(parameters);
            }

            if (parameters is ParametersWithIV)
            {
                ParametersWithIV ivParams = (ParametersWithIV)parameters;
                return(new ParametersWithIV(FixDesParity(mechanism, ivParams.Parameters), ivParams.GetIV()));
            }

            KeyParameter kParam = (KeyParameter)parameters;

            byte[] keyBytes = kParam.GetKey();
            DesParameters.SetOddParity(keyBytes);
            return(new KeyParameter(keyBytes));
        }
Exemplo n.º 12
0
        public byte[] generateKey()
        {
            byte[] newKey = new byte[strength];
            int    count  = 0;

            do
            {
                random.NextBytes(newKey);

                DesParameters.SetOddParity(newKey);
            }while (DesEdeParameters.IsWeakKey(newKey, 0, newKey.Length) && !DesEdeParameters.IsRealEdeKey(newKey) && count++ < 10);

            if (DesEdeParameters.IsWeakKey(newKey, 0, newKey.Length) || !DesEdeParameters.IsRealEdeKey(newKey))
            {
                // if this happens there's got to be something terribly wrong.
                throw new CryptoOperationError("Failed to generate a valid TripleDES key: " + algorithm.Name);
            }

            return(newKey);
        }
Exemplo n.º 13
0
        public override void PerformTest()
        {
            byte[] k1In = { (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff,
                            (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff };
            byte[] k1Out = { (byte)0xfe, (byte)0xfe, (byte)0xfe, (byte)0xfe,
                             (byte)0xfe, (byte)0xfe, (byte)0xfe, (byte)0xfe };

            byte[] k2In = { (byte)0xef, (byte)0xcb, (byte)0xda, (byte)0x4f,
                            (byte)0xaa, (byte)0x99, (byte)0x7f, (byte)0x63 };
            byte[] k2Out = { (byte)0xef, (byte)0xcb, (byte)0xda, (byte)0x4f,
                             (byte)0xab, (byte)0x98, (byte)0x7f, (byte)0x62 };

            DesParameters.SetOddParity(k1In);

            for (int i = 0; i != k1In.Length; i++)
            {
                if (k1In[i] != k1Out[i])
                {
                    Fail("Failed "
                         + "got " + Hex.ToHexString(k1In)
                         + " expected " + Hex.ToHexString(k1Out));
                }
            }

            DesParameters.SetOddParity(k2In);

            for (int i = 0; i != k2In.Length; i++)
            {
                if (k2In[i] != k2Out[i])
                {
                    Fail("Failed "
                         + "got " + Hex.ToHexString(k2In)
                         + " expected " + Hex.ToHexString(k2Out));
                }
            }
        }
Exemplo n.º 14
0
        public override void PerformTest()
        {
            try
            {
                DesParameters.IsWeakKey(new byte[4], 0);
                Fail("no exception on small key");
            }
            catch (ArgumentException e)
            {
                if (!e.Message.Equals("key material too short."))
                {
                    Fail("wrong exception");
                }
            }

            try
            {
                new DesParameters(weakKeys);
                Fail("no exception on weak key");
            }
            catch (ArgumentException e)
            {
                if (!e.Message.Equals("attempt to create weak DES key"))
                {
                    Fail("wrong exception");
                }
            }

            for (int i = 0; i != weakKeys.Length; i += 8)
            {
                if (!DesParameters.IsWeakKey(weakKeys, i))
                {
                    Fail("weakKey test failed");
                }
            }
        }
Exemplo n.º 15
0
        // TODO Make private again and call from PerformTest
        public void doTestExceptions()
        {
            // TODO Put back in
//			SecretKeyFactory skF = null;
//
//			try
//			{
//				skF = SecretKeyFactory.getInstance("DESede");
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}
//
//			KeySpec ks = null;
//			SecretKey secKey = null;
//			byte[] bb = new byte[24];
//
//			try
//			{
//				skF.getKeySpec(null, null);
//
//				Fail("failed exception test - no exception thrown");
//			}
//			catch (InvalidKeySpecException e)
//			{
//				// ignore okay
//			}
//			catch (Exception e)
//			{
//				Fail("failed exception test.", e);
//			}
//			try
//			{
//				ks = (KeySpec)new DESedeKeySpec(bb);
//				skF.getKeySpec(null, ks.getClass());
//
//				Fail("failed exception test - no exception thrown");
//			}
//			catch (InvalidKeySpecException e)
//			{
//				// ignore okay;
//			}
//			catch (Exception e)
//			{
//				Fail("failed exception test.", e);
//			}
//			try
//			{
//				skF.getKeySpec(secKey, null);
//			}
//			catch (InvalidKeySpecException e)
//			{
//				// ignore okay
//			}
//			catch (Exception e)
//			{
//				Fail("failed exception test.", e);
//			}

            try
            {
                CipherKeyGenerator kg = GeneratorUtilities.GetKeyGenerator("DESede");

                try
                {
                    kg.Init(new KeyGenerationParameters(new SecureRandom(), int.MinValue));

                    Fail("failed exception test - no exception thrown");
                }
//				catch (InvalidParameterException)
                catch (ArgumentException)
                {
                    // ignore okay
                }
                catch (Exception e)
                {
                    Fail("failed exception test.", e);
                }
            }
            catch (Exception e)
            {
                Fail("unexpected exception.", e);
            }

            // TODO Put back in
//			try
//			{
//				skF = SecretKeyFactory.getInstance("DESede");
//
//				try
//				{
//					skF.translateKey(null);
//
//					Fail("failed exception test - no exception thrown");
//				}
//				catch (InvalidKeyException)
//				{
//					// ignore okay
//				}
//				catch (Exception e)
//				{
//					Fail("failed exception test.", e);
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}

//			try
//			{
//				byte[] rawDESKey = { (byte)128, (byte)131, (byte)133, (byte)134,
//						(byte)137, (byte)138, (byte)140, (byte)143 };
//
////				SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES");
//				KeyParameter cipherKey = new DesParameters(rawDESKey);
//
//				IBufferedCipher cipher = CipherUtilities.GetCipher("DES/CBC/NoPadding");
//
//				try
//				{
//					// According specification engineInit(int opmode, Key key,
//					// SecureRandom random) throws InvalidKeyException if this
//					// cipher is being
//					// initialized for decryption and requires algorithm parameters
//					// that cannot be determined from the given key
////					cipher.Init(false, cipherKey, (SecureRandom)null);
//					cipher.Init(false, new ParametersWithRandom(cipherKey, new SecureRandom()));
//
//					Fail("failed exception test - no InvalidKeyException thrown");
//				}
//				catch (InvalidKeyException)
//				{
//					// ignore
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}

            try
            {
//				byte[] rawDESKey = { -128, -125, -123, -122, -119, -118 };
                byte[] rawDESKey = { 128, 131, 133, 134, 137, 138 };

//				SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES");

//				IBufferedCipher cipher = CipherUtilities.GetCipher("DES/ECB/NoPadding");
                try
                {
                    KeyParameter cipherKey = new DesParameters(rawDESKey);

                    // According specification engineInit(int opmode, Key key,
                    // SecureRandom random) throws InvalidKeyException if the given
                    // key is inappropriate for initializing this cipher
//					cipher.Init(true, cipherKey);

//					Fail("failed exception test - no InvalidKeyException thrown");
                    Fail("failed exception test - no ArgumentException thrown");
                }
//				catch (InvalidKeyException)
                catch (ArgumentException)
                {
                    // ignore
                }
            }
            catch (Exception e)
            {
                Fail("unexpected exception.", e);
            }

//			try
//			{
////				byte[] rawDESKey = { -128, -125, -123, -122, -119, -118, -117, -115, -114 };
//				byte[] rawDESKey = { 128, 131, 133, 134, 137, 138, 139, 141, 142 };
//
////				SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES");
//				KeyParameter cipherKey = new DesParameters(rawDESKey);
//
//				IBufferedCipher cipher = CipherUtilities.GetCipher("DES/ECB/NoPadding");
//				try
//				{
//					// According specification engineInit(int opmode, Key key,
//					// SecureRandom random) throws InvalidKeyException if the given
//					// key is inappropriate for initializing this cipher
//					cipher.Init(true, cipherKey);
//
//					Fail("failed exception test - no InvalidKeyException thrown");
//				}
//				catch (InvalidKeyException)
//				{
//					// ignore
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}


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

//				SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES");
                KeyParameter cipherKey = new DesParameters(rawDESKey);

                IBufferedCipher ecipher = CipherUtilities.GetCipher("DES/ECB/PKCS5Padding");
                ecipher.Init(true, cipherKey);

                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.update(new byte[20], 0, 20, cipherText);
                    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)
                catch (DataLengthException)
                {
                    // ignore
                }
            }
            catch (Exception e)
            {
                Fail("unexpected exception.", e);
            }

            // TODO Put back in
//			try
//			{
//				KeyGenerator keyGen = KeyGenerator.getInstance("DES");
//
//				keyGen.init((SecureRandom)null);
//
//				// According specification engineGenerateKey() doesn't throw any exceptions.
//
//				SecretKey key = keyGen.generateKey();
//				if (key == null)
//				{
//					Fail("key is null!");
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}
//
//			try
//			{
//				AlgorithmParameters algParams = AlgorithmParameters.getInstance("DES");
//
//				algParams.init(new IvParameterSpec(new byte[8]));
//
//				// According specification engineGetEncoded() returns
//				// the parameters in their primary encoding format. The primary
//				// encoding
//				// format for parameters is ASN.1, if an ASN.1 specification for
//				// this type
//				// of parameters exists.
//				byte[] iv = algParams.getEncoded();
//
//				if (iv.Length!= 10)
//				{
//					Fail("parameters encoding wrong length - "  + iv.Length);
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}

            try
            {
                try
                {
//					AlgorithmParameters algParams = AlgorithmParameters.getInstance("DES");

                    byte[] encoding = new byte[10];
                    encoding[0] = 3;
                    encoding[1] = 8;

//					algParams.init(encoding, "ASN.1");
                    ParameterUtilities.GetCipherParameters(
                        "AES",
                        ParameterUtilities.CreateKeyParameter("AES", new byte[16]),
                        Asn1Object.FromByteArray(encoding));

//					Fail("failed exception test - no IOException thrown");
                    Fail("failed exception test - no Exception thrown");
                }
//				catch (IOException)
                catch (ArgumentException)
                {
                    // okay
                }

//				try
//				{
//					IBufferedCipher c = CipherUtilities.GetCipher("DES");
//
//					Key k = new PublicKey()
//					{
//
//						public string getAlgorithm()
//						{
//							return "STUB";
//						}
//
//						public string getFormat()
//						{
//							return null;
//						}
//
//						public byte[] getEncoded()
//						{
//							return null;
//						}
//
//					};
//
//					c.Init(true, k);
//
//					Fail("failed exception test - no InvalidKeyException thrown for public key");
//				}
//				catch (InvalidKeyException e)
//				{
//					// okay
//				}
//
//				try
//				{
//					IBufferedCipher c = CipherUtilities.GetCipher("DES");
//
//					Key k = new PrivateKey()
//					{
//
//						public string getAlgorithm()
//						{
//							return "STUB";
//						}
//
//						public string getFormat()
//						{
//							return null;
//						}
//
//						public byte[] getEncoded()
//						{
//							return null;
//						}
//
//					};
//
//					c.Init(false, k);
//
//					Fail("failed exception test - no InvalidKeyException thrown for private key");
//				}
//				catch (InvalidKeyException e)
//				{
//					// okay
//				}
            }
            catch (Exception e)
            {
                Fail("unexpected exception.", e);
            }
        }
Exemplo n.º 16
0
        public ITestResult doTest(
            string algorithm,
            byte[]  input,
            byte[]  output)
        {
            KeyParameter    key;
            IBufferedCipher inCipher, outCipher;
            CipherStream    cIn, cOut;
            MemoryStream    bIn, bOut;

//			IvParameterSpec spec = new IvParameterSpec();
            byte[] spec = Hex.Decode("1234567890abcdef");

            try
            {
                key = new DesParameters(Hex.Decode("0123456789abcdef"));

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

                if (algorithm.StartsWith("DES/ECB"))
                {
                    outCipher.Init(true, key);
                }
                else
                {
                    outCipher.Init(true, new ParametersWithIV(key, spec));
                }
            }
            catch (Exception e)
            {
                return(new SimpleTestResult(false, Name + ": " + algorithm + " failed initialisation - " + e.ToString(), e));
            }

            try
            {
                if (algorithm.StartsWith("DES/ECB"))
                {
                    inCipher.Init(false, key);
                }
                else
                {
                    inCipher.Init(false, new ParametersWithIV(key, spec));
                }
            }
            catch (Exception e)
            {
                return(new SimpleTestResult(false, Name + ": " + algorithm + " failed initialisation - " + e.ToString(), e));
            }

            //
            // 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)
            {
                return(new SimpleTestResult(false, Name + ": " + algorithm + " failed encryption - " + e.ToString()));
            }

            byte[] bytes = bOut.ToArray();

            if (!Arrays.AreEqual(bytes, output))
            {
                return(new SimpleTestResult(false, Name + ": " + 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)
            {
                return(new SimpleTestResult(false, Name + ": " + algorithm + " failed encryption - " + e.ToString()));
            }

            if (!Arrays.AreEqual(bytes, input))
            {
                return(new SimpleTestResult(false, Name + ": " + algorithm + " failed decryption - expected "
                                            + Hex.ToHexString(input) + " got " + Hex.ToHexString(bytes)));
            }

            return(new SimpleTestResult(true, Name + ": " + algorithm + " Okay"));
        }
Exemplo n.º 17
0
        // default behaviour is to look for keys defined by an EncryptedKey clause
        // either directly or through a KeyInfoRetrievalMethod, and key names in the key mapping
        public virtual ICipherParameters GetDecryptionKey(EncryptedData encryptedData, string symmetricAlgorithmUri)
        {
            if (encryptedData == null)
            {
                throw new ArgumentNullException(nameof(encryptedData));
            }

            if (encryptedData.KeyInfo == null)
            {
                return(null);
            }
            IEnumerator            keyInfoEnum = encryptedData.KeyInfo.GetEnumerator();
            KeyInfoRetrievalMethod kiRetrievalMethod;
            KeyInfoName            kiName;
            KeyInfoEncryptedKey    kiEncKey;
            EncryptedKey           ek = null;

            while (keyInfoEnum.MoveNext())
            {
                kiName = keyInfoEnum.Current as KeyInfoName;
                if (kiName != null)
                {
                    // Get the decryption key from the key mapping
                    string keyName = kiName.Value;
                    if (_keyNameMapping[keyName] as ICipherParameters != null)
                    {
                        return((ICipherParameters)_keyNameMapping[keyName]);
                    }
                    // try to get it from a CarriedKeyName
                    XmlNamespaceManager nsm = new XmlNamespaceManager(_document.NameTable);
                    nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl);
                    XmlNodeList encryptedKeyList = _document.SelectNodes("//enc:EncryptedKey", nsm);
                    if (encryptedKeyList != null)
                    {
                        foreach (XmlNode encryptedKeyNode in encryptedKeyList)
                        {
                            XmlElement   encryptedKeyElement = encryptedKeyNode as XmlElement;
                            EncryptedKey ek1 = new EncryptedKey();
                            ek1.LoadXml(encryptedKeyElement);
                            if (ek1.CarriedKeyName == keyName && ek1.Recipient == Recipient)
                            {
                                ek = ek1;
                                break;
                            }
                        }
                    }
                    break;
                }
                kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod;
                if (kiRetrievalMethod != null)
                {
                    string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri);
                    ek = new EncryptedKey();
                    ek.LoadXml(GetIdElement(_document, idref));
                    break;
                }
                kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey;
                if (kiEncKey != null)
                {
                    ek = kiEncKey.EncryptedKey;
                    break;
                }
            }

            // if we have an EncryptedKey, decrypt to get the symmetric key
            if (ek != null)
            {
                // now process the EncryptedKey, loop recursively
                // If the Uri is not provided by the application, try to get it from the EncryptionMethod
                if (symmetricAlgorithmUri == null)
                {
                    if (encryptedData.EncryptionMethod == null)
                    {
                        throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_MissingAlgorithm);
                    }
                    symmetricAlgorithmUri = encryptedData.EncryptionMethod.KeyAlgorithm;
                }
                byte[] key = DecryptEncryptedKey(ek);
                if (key == null)
                {
                    throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_MissingDecryptionKey);
                }

                IBufferedCipher symAlg = CryptoHelpers.CreateFromName <IBufferedCipher>(symmetricAlgorithmUri);
                if (symAlg == null)
                {
                    throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_MissingAlgorithm);
                }

                KeyParameter keyParam;
                if (symAlg.AlgorithmName.IndexOf("DESede", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    keyParam = new DesEdeParameters(key);
                }
                else if (symAlg.AlgorithmName.IndexOf("DES", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    keyParam = new DesParameters(key);
                }
                else
                {
                    keyParam = new KeyParameter(key);
                }

                return(keyParam);
            }
            return(null);
        }
Exemplo n.º 18
0
        public override void PerformTest()
        {
            KeyParameter key = new DesParameters(keyBytes);
            IMac         mac = MacUtilities.GetMac("DESMac");

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

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

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

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

            //
            // mac with IV.
            //
            mac.Init(new ParametersWithIV(key, ivBytes));

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

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

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

            //
            // CFB mac with IV - 8 bit CFB mode
            //
            mac = MacUtilities.GetMac("DESMac/CFB8");

            mac.Init(new ParametersWithIV(key, ivBytes));

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

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

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

            //
            // ISO9797 algorithm 3 using DESEDE
            //
            key = new DesEdeParameters(keyBytesISO9797);

            mac = MacUtilities.GetMac("ISO9797ALG3");

            mac.Init(key);

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

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

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

            //
            // 64bit DESede Mac
            //
            key = new DesEdeParameters(keyBytesISO9797);

            mac = MacUtilities.GetMac("DESEDE64");

            mac.Init(key);

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

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

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

            aliasTest(
                ParameterUtilities.CreateKeyParameter("DESede", keyBytesISO9797),
                "DESedeMac64withISO7816-4Padding",
                "DESEDE64WITHISO7816-4PADDING",
                "DESEDEISO9797ALG1MACWITHISO7816-4PADDING",
                "DESEDEISO9797ALG1WITHISO7816-4PADDING");

            aliasTest(
                ParameterUtilities.CreateKeyParameter("DESede", keyBytesISO9797),
                "ISO9797ALG3WITHISO7816-4PADDING",
                "ISO9797ALG3MACWITHISO7816-4PADDING");
        }