예제 #1
0
        private static byte[] DoCryptStuff(byte[] data, IKey key, CipherDirection direction, CipherMode cipherMode, byte[] iv)
        {
            byte[] result;
            String transformation = key.GetAlgorithm();

            if (key.GetAlgorithm().StartsWith(ALG_DES))
            {
                transformation += "/" + ModetoString(cipherMode) + "/" + DES_NO_PADDING;
            }

            ICipherParameters keyparam = new KeyParameter(key.GetEncoded());
            IBufferedCipher   cipher   = CipherUtilities.GetCipher(transformation);

            if (cipherMode != CipherMode.ECB)
            {
                keyparam = new ParametersWithIV(keyparam, iv);
            }

            byte[] output = new byte[cipher.GetOutputSize(data.Length)];
            cipher.Init(direction == CipherDirection.ENCRYPT_MODE ? true : false, keyparam);
            result = cipher.DoFinal(data);

            if (cipherMode != CipherMode.ECB)
            {
                Array.Copy(result, result.Length - 8, iv, 0, iv.Length);
            }

            //AlgorithmParameterSpec aps = null;
            //try
            //{
            //    Cipher c1 = Cipher.getInstance(transformation, provider.getName());
            //    if (cipherMode != CipherMode.ECB)
            //        aps = new IvParameterSpec(iv);
            //    c1.init(direction, key, aps);
            //    result = c1.doFinal(data);
            //    if (cipherMode != CipherMode.ECB)
            //        System.arraycopy(result, result.length - 8, iv, 0, iv.length);
            //}
            //catch (Exception e)
            //{
            //    throw e;
            //}
            return(result);
        }
예제 #2
0
        public static byte[] ExtractDESKeyMaterial(short keyLength, IKey clearDESKey)
        {
            String keyAlg    = clearDESKey.GetAlgorithm();
            String keyFormat = clearDESKey.GetFormat();

            if (keyFormat.CompareTo("RAW") != 0)
            {
                throw new Exception("Unsupported DES key encoding format: " + keyFormat);
            }
            if (!keyAlg.StartsWith(ALG_DES))
            {
                throw new Exception("Unsupported key algorithm: " + keyAlg);
            }
            byte[] clearKeyBytes = clearDESKey.GetEncoded();
            clearKeyBytes = Util.Trim(clearKeyBytes, GetBytesLength(keyLength));
            return(clearKeyBytes);
        }