GenerateIV() public method

public GenerateIV ( ) : void
return void
        /// <summary>
        /// 测试 生成对称密钥.
        /// </summary>
        public static void DoTest()
        {
            Console.WriteLine("##### 生成对称密钥的例子 !");

            TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();

            Console.WriteLine("对称算法的密钥:");
            ByteArrayOutput.Print(TDES.Key);

            Console.WriteLine("对称算法的对称算法的初始化向量 (IV):");
            ByteArrayOutput.Print(TDES.IV);

            Console.WriteLine("再多生成一组密钥 !");

            TDES.GenerateIV();
            TDES.GenerateKey();

            Console.WriteLine("对称算法的密钥:");
            ByteArrayOutput.Print(TDES.Key);

            Console.WriteLine("对称算法的对称算法的初始化向量 (IV):");
            ByteArrayOutput.Print(TDES.IV);

            Console.WriteLine("再多生成一组密钥 !");

            TDES.GenerateIV();
            TDES.GenerateKey();

            Console.WriteLine("对称算法的密钥:");
            ByteArrayOutput.Print(TDES.Key);

            Console.WriteLine("对称算法的对称算法的初始化向量 (IV):");
            ByteArrayOutput.Print(TDES.IV);
        }
        public static String DecryptString(String in_string)
        {
            String return_value;
            using (TripleDESCryptoServiceProvider tdsAlg = new TripleDESCryptoServiceProvider())
            {
                tdsAlg.GenerateKey();
                tdsAlg.GenerateIV();

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = tdsAlg.CreateDecryptor(tdsAlg.Key, tdsAlg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(in_string)))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            return_value = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            return return_value;

        }
        public static String EncryptString(String in_string)
        {
            String return_value;

            using (TripleDESCryptoServiceProvider tdsAlg = new TripleDESCryptoServiceProvider())
            {
                tdsAlg.GenerateKey();
                tdsAlg.GenerateIV();

                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = tdsAlg.CreateEncryptor(tdsAlg.Key, tdsAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {

                            //Write all data to the stream.
                            swEncrypt.Write(in_string);
                        }
                        return_value = msEncrypt.ToString();
                    }
                }
            }
            return return_value;
        }
 public static string CreateNewVector()
 {
     using (var des = new System.Security.Cryptography.TripleDESCryptoServiceProvider())
     {
         des.GenerateIV();
         return(Convert.ToBase64String(des.IV));
     }
 }
        public void DoEncryption()
        {
            // create a symmetric encryptor
            TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider ();
            // create IV and Key need for symmetric encryption
            TDES.GenerateIV();
            TDES.GenerateKey();

            // create an asymmetric encryptor
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider ();
            string AsymKeys = RSA.ToXmlString (true);

            // export the public and private keys to a file
            WriteKeyToFile(AsymKeys);

            // asymmetric encryption is good for
            // small data, hence, we use it to encrypted
            // IV and Key for symmetric encryption
            byte[] encryptedIV = RSA.Encrypt(TDES.IV, false);
            byte[] encryptedKey = RSA.Encrypt(TDES.Key, false);

            // convert the length of IV and Key (e.g. number of bytes used)
            // into a byte, e.g. 4 to 0000 0100
            // as default length of a Integer in .NET is 32,
            // the result byte length should be 4 bytes, i.e. 32/8
            byte[] IVSize = BitConverter.GetBytes(encryptedIV.Length);
            byte[] keySize = BitConverter.GetBytes(encryptedKey.Length);

            // write out the IV length, the key length,
            // the encrypted iv, the encrypted key and the actual
            // date to a file using the symmetric encryptor.
            using(FileStream ostream = new FileStream("encrypted.enc", FileMode.Create)){
                ostream.Write(IVSize, 0, IVSize.Length);
                ostream.Write(keySize, 0, keySize.Length);
                ostream.Write(encryptedIV, 0, encryptedIV.Length);
                ostream.Write(encryptedKey, 0, encryptedKey.Length);

                CryptoStream cstream = new CryptoStream(ostream,
                                                       TDES.CreateEncryptor(),
                                                        CryptoStreamMode.Write);

                // encrypt the data using the crypto stream
                EncryptFile(cstream);

                // close streams
                cstream.Close();
                ostream.Close();
            }
        }
示例#6
0
        public static void GenerateNewIVAndKey(string path)
        {
            try
            {
                var encrypt = new TripleDESCryptoServiceProvider();

                encrypt.GenerateIV();
                encrypt.GenerateKey();

                var sb = new StringBuilder();
                sb.Append("private static byte[] _iv = new byte[] {");
                foreach (var b in encrypt.IV)
                {
                    sb.Append(b);
                    sb.Append(',');
                }

                var ivFront = sb.ToString().TrimEnd(',');
                sb = new StringBuilder();

                sb.Append(ivFront);
                sb.Append("};");

                var ivStr = sb.ToString();

                sb = new StringBuilder();
                sb.Append("private static byte[] _key = new byte[] {");
                foreach (var b in encrypt.Key)
                {
                    sb.Append(b);
                    sb.Append(',');
                }

                var keyFront = sb.ToString().TrimEnd(',');
                sb = new StringBuilder();

                sb.Append(keyFront);
                sb.Append("};");

                var keyStr = sb.ToString();

                var lines = new string[] { ivStr, "\n", keyStr };
                File.WriteAllLines(path, lines);
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message, ex);
            }
        }
        public string EncryptString(string data)
        {
            byte[] toEncrypt = Encoding.UTF8.GetBytes(data);
            var tDes = new TripleDESCryptoServiceProvider();

            tDes.GenerateIV();

            var key = _hashmd5.ComputeHash(_hashEnc);
            var bytes = TripleDes.Encrypt(toEncrypt, key, tDes.IV);

            var str = Convert.ToBase64String(bytes, 0, bytes.Length);
            var iv = Convert.ToBase64String(tDes.IV, 0, tDes.IV.Length);
            var res = string.Format("{0}|{1}", str, iv);
            return res;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider();

            //Set key size
            TDES.KeySize = 10;

            //Generate keys
            TDES.GenerateIV();
            TDES.GenerateKey();

            string data = "p@ssword";

            try
            {
                // Create or open the specified file.
                FileStream fStream = File.Open(@"C:\passwords.txt", FileMode.OpenOrCreate);

                // Create a CryptoStream using the FileStream  
                // and the passed key and initialization vector (IV).
                CryptoStream cStream = new CryptoStream(fStream,
                    new TripleDESCryptoServiceProvider().CreateEncryptor(TDES.Key, TDES.IV),
                    CryptoStreamMode.Write);

                // Create a StreamWriter using the CryptoStream.
                StreamWriter sWriter = new StreamWriter(cStream);

                // Write the data to the stream  
                // to encrypt it.
                sWriter.WriteLine(data);

                // Close the streams and 
                // close the file.
                sWriter.Close();
                cStream.Close();
                fStream.Close();
            }
            catch
            {
                Console.WriteLine("A Cryptographic error occurred");
            }

        }
示例#9
0
        static void Main(string[] args)
        {
            //criptografia
            //algoritmo de criptografia
            //mensagem
            //mensagem cifrada
            //chave de criptografia

            //ponta solta

            //abcdefghijklmnopqrstuvwxyz
            //paranoia e bom para senhas, entendeu?
            //parnoiebmshtd ucfgjklqvwxyz
            //puacrfngojikelbqmvswhxtydz -> chave

            //mensagem = opabeleza
            //cifrada =  bqpurkrzp
            //           opabeleza

            //abcdefghijklmnopqrstuvwxyz
            //opabeleza - original
            //bberqssgk - cifrada com rotação da chave
            //puacrfngojikelbqmvswhxtydz 1
            //zpuacrfngojikelbqmvswhxtyd 2
            //dzpuacrfngojikelbqmvswhxty 3
            //ydzpuacrfngojikelbqmvswhxt 4
            //tydzpuacrfngojikelbqmvswhx 5
            //xtydzpuacrfngojikelbqmvswh 6
            //hxtydzpuacrfngojikelbqmvsw 7
            //whxtydzpuacrfngojikelbqmvs 8
            //swhxtydzpuacrfngojikelbqmv 9

            /*
                XOR - eXclusive OR (algoritmo)

                6   - 0000 0110 (msg)
                2   - 0000 0010 (chave)
                6^2 - 0000 0100 -> 4 (msg cifrada)
                4^2 - 0000 0110 -> 6 (msg)
            */

            /*
               Algoritmos
               ----------
               DES: DESCryptoServiceProvider
               RC2: RC2CryptoServiceProvider
               Rijndael: RijndaelManaged
               TripleDES: TripleDESCryptoServiceProvider
            */

            //criação de chaves simétricas
            var tdes = new TripleDESCryptoServiceProvider();

            Console.WriteLine(tdes.IV); //64 bits
            Console.WriteLine(tdes.Key); //192 bits

            Console.WriteLine();

            Console.WriteLine(tdes.IV.GetString());

            Console.WriteLine();

            Console.WriteLine(tdes.Key.GetString());

            tdes.GenerateIV();
            tdes.GenerateKey();

            Console.WriteLine();
            Console.WriteLine();

            byte[] meuIV = { 12, 23, 54, 65, 23, 76, 87, 89 };
            byte[] minhaChave = { 12, 23, 54, 65, 23, 76, 87, 189, 112, 123, 154, 165, 123, 176, 187, 189, 102, 230, 254, 5, 213, 167, 178, 9 };

            tdes.IV = meuIV;
            tdes.Key = minhaChave;

            Console.WriteLine(tdes.IV.GetString());

            Console.WriteLine();

            Console.WriteLine(tdes.Key.GetString());

            Console.ReadKey();
        }
示例#10
0
        public static void main(string[] args)
        {
            AesManaged aes = new AesManaged();
            Console.WriteLine("AesManaged ");
            KeySizes[] ks = aes.LegalKeySizes;
            foreach (KeySizes k in ks)
            {
                Console.WriteLine("\tLegal min key size = " + k.MinSize);
                Console.WriteLine("\tLegal max key size = " + k.MaxSize);
            }
            ks = aes.LegalBlockSizes;
            foreach (KeySizes k in ks)
            {
                Console.WriteLine("\tLegal min block size = " + k.MinSize);
                Console.WriteLine("\tLegal max block size = " + k.MaxSize);
            }

            RijndaelManaged rij = new RijndaelManaged();
            Console.WriteLine("RijndaelManaged ");
            ks = rij.LegalKeySizes;
            foreach (KeySizes k in ks)
            {
                Console.WriteLine("\tLegal min key size = " + k.MinSize);
                Console.WriteLine("\tLegal max key size = " + k.MaxSize);
            }
            ks = rij.LegalBlockSizes;
            foreach (KeySizes k in ks)
            {
                Console.WriteLine("\tLegal min block size = " + k.MinSize);
                Console.WriteLine("\tLegal max block size = " + k.MaxSize);
            }
            TripleDESCryptoServiceProvider tsp = new TripleDESCryptoServiceProvider();
            Console.WriteLine("TripleDESCryptoServiceProvider ");
            ks = tsp.LegalKeySizes;
            foreach (KeySizes k in ks)
            {
                Console.WriteLine("\tLegal min key size = " + k.MinSize);
                Console.WriteLine("\tLegal max key size = " + k.MaxSize);
            }
            ks = tsp.LegalBlockSizes;
            foreach (KeySizes k in ks)
            {
                Console.WriteLine("\tLegal min block size = " + k.MinSize);
                Console.WriteLine("\tLegal max block size = " + k.MaxSize);
            }

            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.KeySize = 256;
                rijAlg.BlockSize = 256;
                rijAlg.GenerateKey();
                rijAlg.GenerateIV();
                Console.Out.WriteLine(rijAlg.KeySize + " " + rijAlg.BlockSize + " " + Convert.ToBase64String(rijAlg.IV, Base64FormattingOptions.None) + " " +
                    Convert.ToBase64String(rijAlg.Key, Base64FormattingOptions.None));
            }

            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
            des.KeySize = 192;
            des.BlockSize = 64;
            des.GenerateKey();
            des.GenerateIV();
            Console.Out.WriteLine(des.KeySize + " " + des.BlockSize + " " + Convert.ToBase64String(des.IV, Base64FormattingOptions.None) + " " +
                Convert.ToBase64String(des.Key, Base64FormattingOptions.None));
        }
示例#11
0
 /// <summary>
 /// Gets the initialization vector.
 /// </summary>
 /// <returns>
 /// The initialization vector.
 /// </returns>
 public byte[] GetInitializationVector()
 {
     var tripleDes = new TripleDESCryptoServiceProvider();
     tripleDes.GenerateIV();
     return tripleDes.IV;
 }
示例#12
0
 public static string GenerateIV()
 {
     var crypto = new TripleDESCryptoServiceProvider();
     crypto.GenerateIV();
     return Convert.ToBase64String(crypto.IV);
 }
示例#13
0
        internal static bool EncryptFile(string fileNameToEncrypt)
        {
            string encryptedFileName = fileNameToEncrypt + ".enc";

            //instantiate our RSA crypto service provider with parameters
            const int PROVIDER_RSA_FULL = 1;
            const string CONTAINER_NAME = "CodewordCryptoContainer";
            CspParameters cspParams;
            cspParams = new CspParameters(PROVIDER_RSA_FULL);
            cspParams.KeyContainerName = CONTAINER_NAME;
            cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
            cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";
            RSACryptoServiceProvider aSymmetricEncProvider = new RSACryptoServiceProvider(cspParams);
            TripleDESCryptoServiceProvider SymmetricEncProvider = new TripleDESCryptoServiceProvider();

            //open read-only file stream for our unencrypted file
            FileStream PlaintextFileDataStream = new FileStream(fileNameToEncrypt, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            //create a writable filestream to write encrypted file out
            FileStream EncryptedFileDataStream = new FileStream(encryptedFileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            //init a binaryWriter class to dump data to file
            BinaryWriter bw = new BinaryWriter(EncryptedFileDataStream);

            int fileLength = (int)PlaintextFileDataStream.Length;

            //if no data to encrypt, fail now
            if (fileLength == 0)
            {
                PlaintextFileDataStream.Close();
                EncryptedFileDataStream.Close();
                return false;
            }

            //read all data from file as binary data
            byte[] UnencryptedBinaryData = ReadByteArray(PlaintextFileDataStream);
            PlaintextFileDataStream.Close();

            //generate a new IV and sym key for encryption
            SymmetricEncProvider.GenerateIV();
            SymmetricEncProvider.GenerateKey();

            //use asymmetric encryption to encrpyt initialization vector (IV)
            byte[] EncryptedBinaryData = aSymmetricEncProvider.Encrypt(SymmetricEncProvider.IV, false);
            //then write it to the output stream (encrypted file)
            bw.Write(EncryptedBinaryData);
            //do the same for symmetric key
            EncryptedBinaryData = aSymmetricEncProvider.Encrypt(SymmetricEncProvider.Key, false);
            bw.Write(EncryptedBinaryData);

            //create our symmetric encryptor
            ICryptoTransform DES3Encrypt = SymmetricEncProvider.CreateEncryptor();

            //create a crypto stream to write our encrypted data by using:
            //      -target data stream (EncryptedFileDataStream), ie output file encrypted
            //      -transformation to user (3-DES)
            //      -mode (Write)
            //this will essentially pipe all our unencrypted data we read in from the file-to-encrypt
            //through our encrypted data stream using the 3-DES transformation
            CryptoStream cryptoStream = new CryptoStream(EncryptedFileDataStream, DES3Encrypt, CryptoStreamMode.Write);
            cryptoStream.Write(UnencryptedBinaryData, 0, UnencryptedBinaryData.Length);
            cryptoStream.Close();
            EncryptedFileDataStream.Close();
            PlaintextFileDataStream.Close();
            bw.Close();

            return true;
        }
示例#14
0
        /// <summary>
        /// Desifrovani dat (3DES alg.)
        /// - v pripade, ze vstupni data nemaji validni format vyhazuje GopayException
        /// </summary>
        /// 
        /// <param name="data">data</param>
        /// <param name="secureKey">secureKey</param>
        /// 
        /// <returns>desifrovany retezec</returns>
        public static string Decrypt(string data, string secureKey) {
            byte[] cData = Hex2Byte(data);

            // Vytvorime instanci 3DES algoritmu, nastavime parametry
            TripleDESCryptoServiceProvider alg = new TripleDESCryptoServiceProvider();
            alg.Mode = CipherMode.ECB;
            alg.GenerateIV();
            alg.Key = Encoding.Default.GetBytes(secureKey);
            alg.Padding = PaddingMode.None;

            // Vytvorime decryptor
            ICryptoTransform decryptor = alg.CreateDecryptor(alg.Key, alg.IV);

            MemoryStream ms;
            CryptoStream cs;
            String decryptedData = "";

            try {
                ms = new MemoryStream(cData.Length);
                cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write);
                cs.Write(cData, 0, cData.Length);
                decryptedData = Encoding.UTF8.GetString(ms.ToArray());

            } catch (Exception ex) {
                throw new GopayException(ex.ToString());
            }

            return decryptedData.TrimEnd('\0');
        }
示例#15
0
        /// <summary>
        /// Sifrovani dat 3DES
        /// - v pripade, ze vstupni data nemaji validni format vyhazuje GopayException
        /// </summary>
        /// 
        /// <param name="data">data</param>
        /// <param name="secureKey">secureKey</param>
        /// 
        /// <returns>zasifrovana data</returns>
        public static string Encrypt(string data, string secureKey) {
            // Vytvorime instanci 3DES algoritmu, nastavime parametry
            TripleDESCryptoServiceProvider alg = new TripleDESCryptoServiceProvider();
            alg.Padding = PaddingMode.Zeros;
            alg.Mode = CipherMode.ECB;
            alg.GenerateIV();
            try {
                alg.Key = new ASCIIEncoding().GetBytes(secureKey);

            } catch (Exception ex) {
                throw new GopayException(ex.ToString());
            }

            // Vytvorime encryptor
            ICryptoTransform encryptor = alg.CreateEncryptor(alg.Key, alg.IV);

            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
            StreamWriter sw = new StreamWriter(cs);
            byte[] encryptedByte;

            try {
                sw.Write(data);
                sw.Flush();
                cs.FlushFinalBlock();

                encryptedByte = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(encryptedByte, 0, (int)ms.Length);

            } catch (Exception ex) {
                throw new GopayException(ex.ToString());

            } finally {
                ms.Close();
                ms.Dispose();

                cs.Close();
                cs.Dispose();

                sw.Close();
                sw.Dispose();
            }

            StringBuilder encryptedData = new StringBuilder();
            foreach (byte b in encryptedByte) {
                try {
                    encryptedData.Append(String.Format("{0:x2}", b));

                } catch (Exception ex) {
                    throw new GopayException(ex.ToString());
                }
            }

            return encryptedData.ToString();
        }
示例#16
0
        private static void CreateKey(out byte[] key, out byte[] iv)
        {
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();

            KeySizes[] ks = des.LegalKeySizes;
            foreach (var k in ks)
            {
                des.KeySize = k.MaxSize;
            }
            ks = des.LegalBlockSizes;
            foreach (var k in ks)
            {
                des.BlockSize = k.MaxSize;
            }
            des.GenerateKey();
            des.GenerateIV();

            key = des.Key;
            iv = des.IV;
        }
 public static Secret HybridEncrypt
                             (
                                 RSACryptoServiceProvider encryptorPrivateKeyPfxProvider
                                 , X509Certificate2 encryptorPublicKeyCer
                                 , RSACryptoServiceProvider decryptorPublicKeyCerProvider
                                 , HashSignatureMode signHashMode
                                 , bool DoOAEPadding
                                 , byte[] data
                             )
 {
     Secret secret = new Secret();
     using (TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider())
     {
         provider.GenerateIV();
         secret.EncryptorSharedEncryptedOnceIV = provider.IV;
         provider.GenerateKey();
         secret.EncryptorSharedEncryptedOnceKey = provider.Key;
         secret.EncryptedData = provider.CreateEncryptor().TransformFinalBlock(data, 0, data.Length);
     }
     secret.EncryptorSharedEncryptedOnceIV = decryptorPublicKeyCerProvider.Encrypt(secret.EncryptorSharedEncryptedOnceIV, DoOAEPadding);
     secret.EncryptorSharedEncryptedOnceKey = decryptorPublicKeyCerProvider.Encrypt(secret.EncryptorSharedEncryptedOnceKey, DoOAEPadding);
     HashAlgorithm hashAlgorithm;
     if (signHashMode == HashSignatureMode.SHA1)
     {
         hashAlgorithm = new SHA1CryptoServiceProvider();
     }
     else //(hashSignatureMode == HashSignatureMode.MD5)
     {
         hashAlgorithm = new MD5CryptoServiceProvider();
     }
     MemoryStream stream = new MemoryStream();
     byte[] buffer = secret.EncryptorSharedEncryptedOnceIV;
     stream.Write(buffer, 0, buffer.Length);
     buffer = secret.EncryptorSharedEncryptedOnceKey;
     stream.Write(buffer, 0, buffer.Length);
     buffer = secret.EncryptedData;
     stream.Position = 0;
     buffer = hashAlgorithm.ComputeHash(stream);
     stream.Close();
     stream.Dispose();
     secret.EncryptorHashSignature = encryptorPrivateKeyPfxProvider.SignHash
                                                                         (
                                                                             buffer
                                                                             , Enum.GetName
                                                                                         (
                                                                                             signHashMode.GetType()
                                                                                             , signHashMode
                                                                                         )
                                                                         );
     secret.EncryptorPublicKeyCerRawData = encryptorPublicKeyCer.RawData;
     secret.SignHashMode = signHashMode;
     secret.DoOAEPadding = DoOAEPadding;
     return secret;
 }
 public static string GenerateTripleDESHexStringIV()
 {
     TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
     des.GenerateIV();
     return BytesArrayToHexString(des.IV);
 }
示例#19
0
 //$input - stuff to decrypt
 //$key - the secret key to use
 public static string decrypt_cc(string cipherString, int customer_id)
 {
     try
     {
         string key = string.Empty;
         cipherString = cipherString.Replace("\n", "");
         cipherString = cipherString.Replace("\t", "");
         cipherString = cipherString.Replace("\r", "");
         cipherString = cipherString.Trim();
         byte[] keyArray;
         byte[] toEncryptArray = Convert.FromBase64String(cipherString);
         key = get_key(Key);
         TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
         key = key.Substring(0, tdes.Key.Length);
         keyArray = System.Text.Encoding.UTF8.GetBytes(key);
         tdes.Key = keyArray;
         tdes.GenerateIV();
         tdes.Mode = CipherMode.ECB;
         tdes.Padding = PaddingMode.None;
         ICryptoTransform cTransform = tdes.CreateDecryptor();
         byte[] resultArray = cTransform.TransformFinalBlock(
                              toEncryptArray, 0, toEncryptArray.Length);
         tdes.Clear();
         return System.Text.Encoding.UTF8.GetString(resultArray);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         EventLog.WriteEntry(sSource, ex.Message);
         return ex.Message;
     }
 }
示例#20
0
        public string DoEncrypt3DES(string _PlaneText, string _userPass)
        {
            // 暗号化する対象となる平文をバイト型の配列に格納。
            byte[] _aftData = Encoding.UTF8.GetBytes(_PlaneText);

            // 暗号化で使用するTripleDESCryptoServiceProviderオブジェクトの作成。
            // TripleDESの場合 BlockSize = 64bit、KeySize = 128bit, 192bit のどちらか。
            TripleDESCryptoServiceProvider enc = new TripleDESCryptoServiceProvider();
            enc.BlockSize = 64;
            enc.KeySize = 128;
            enc.Mode = CipherMode.CBC;
            enc.Padding = PaddingMode.PKCS7;

            // 初期化ベクトルの設定。鍵のサイズ16byteの場合、初期化ベクトルは8byteとなる。
            enc.GenerateIV();
            byte[] _byteIV = enc.IV;

            // 秘密鍵の設定。3DESの秘密鍵のサイズは16byte(128bit)。パスワードを有効なキーサイズに調整。
            byte[] _bytePassWordKey = Encoding.UTF8.GetBytes(_userPass);
            byte[] _byteKey = new Byte[16];

            for (int i = 0; i < 16; i++)
            {
                if (i < _bytePassWordKey.Length)
                {
                    _byteKey[i] = _bytePassWordKey[i];
                }
                else
                {
                    _byteKey[i] = 0;
                }
            }
            enc.Key = _byteKey;

            // 暗号化で使用する3DES暗号化オブジェクトの作成。
            ICryptoTransform encrypt = enc.CreateEncryptor();

            // 暗号化したデータを格納するMemoryStreamの先頭に初期化ベクトルを書き込む。
            MemoryStream ms = new MemoryStream();
            ms.Write(_byteIV, 0, 8);

            // 暗号化で使用するCrepotStreamの作成。
            CryptoStream cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write);

            // 暗号化データを書き込んでいく。
            cs.Write(_aftData, 0, _aftData.Length);
            cs.Close();

            string _tmpReturnString = Byte2HexString(ms.ToArray());
            ms.Close();
            encrypt.Dispose();

            return _tmpReturnString;
        }