コード例 #1
1
    // Use this for initialization
    void Start () {
        Rfc2898DeriveBytes PBKDF2_hash = new Rfc2898DeriveBytes("qwerty", Encoding.ASCII.GetBytes("rm4fSDh0sofK"), 20000);
        HMACSHA256 HMACSHA256_hash = new HMACSHA256();
        //System.Text.Encoding.UTF8.GetString(bytes);
        string hPassword = Convert.ToBase64String(PBKDF2_hash.GetBytes(32));
        Debug.Log("Hash = " + hPassword);
        //Debug.Log("Password hash" + Encoding.ASCII.GetString(PBKDF2.GetBytes(256)));
        //PBKDF2.Salt = 


        /*string password = "******";
        string hPassword = ComputeHash(password, new SHA256CryptoServiceProvider());
        Debug.Log("Hash from: " + password + " = " + hPassword);*/
    }
コード例 #2
0
ファイル: TokenUtility.cs プロジェクト: kazeemkz/silverdale
    public static string GenerateUrlToken(string controllerName, string actionName, RouteValueDictionary argumentParams, string password)
    {
        //// The URL hash is dynamic by assign a dynamic key in each session. So
        //// eventhough your URL is stolen, it will not work in other session
        if (HttpContext.Current.Session["url_dynamickey"] == null)
        {
            HttpContext.Current.Session["url_dynamickey"] = RandomString();
        }

        // The salt include the dynamic session key and valid for an hour.
        var salt = HttpContext.Current.Session["url_dynamickey"] + DateTime.Now.ToShortDateString() + " " + DateTime.Now.Hour;

        // generating the partial url
        var stringToToken = controllerName + "/" + actionName + "/";
        stringToToken = argumentParams.Where(item => item.Key != "controller" && item.Key != "action" && item.Key != "urltoken").Aggregate(stringToToken, (current, item) => current + (item.Value));

        // Converting the salt in to a byte array
        var saltValueBytes = System.Text.Encoding.ASCII.GetBytes(salt);

        // Encrypt the salt bytes with the password
        var key = new Rfc2898DeriveBytes(password, saltValueBytes);

        // get the key bytes from the above process
        var secretKey = key.GetBytes(16);

        // generate the hash
        var tokenHash = new HMACSHA1(secretKey);
        tokenHash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(stringToToken));

        // convert the hash to a base64string
        var token = Convert.ToBase64String(tokenHash.Hash).Replace("/", "_");

        return token;
    }
コード例 #3
0
ファイル: Encryption.cs プロジェクト: Syriamanal/xprotect
    public static byte[] Encrypt(byte[] data, string password)
    {
        byte[] result = null;
            byte[] passwordBytes = Encoding.Default.GetBytes(password);

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize = keySize;
                    AES.BlockSize = 128;
                    var key = new Rfc2898DeriveBytes(passwordBytes, salt, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);
                    AES.Mode = CipherMode.CBC;
                    using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(data, 0, data.Length);
                        cs.Close();
                    }
                    result = ms.ToArray();
                }

            }
            return result;
    }
コード例 #4
0
ファイル: SimpleAES256.cs プロジェクト: JorgMU/AES256
    public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
    {
        byte[] encryptedBytes = null;

        // Set your salt here, change it to meet your flavor:
        // The salt bytes must be at least 8 bytes.
        byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

        using (MemoryStream ms = new MemoryStream())
        {
          using (RijndaelManaged AES = new RijndaelManaged())
          {
        AES.KeySize = 256;
        AES.BlockSize = 128;

        var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
        AES.Key = key.GetBytes(AES.KeySize / 8);
        AES.IV = key.GetBytes(AES.BlockSize / 8);

        AES.Mode = CipherMode.CBC;

        using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
        {
          cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
          cs.Close();
        }
        encryptedBytes = ms.ToArray();
          }
        }

        return encryptedBytes;
        //end public byte[] AES_Encrypt
    }
コード例 #5
0
ファイル: Encrypter.cs プロジェクト: RyanShaul/dig
 public static string Encrypt(string clearText)
 {
     byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
         Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(_Pwd, _Salt);
         byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
         return Convert.ToBase64String(encryptedData);
 }
    //This method is to decrypt the password given by user.
    public static string Decrypt(string data, string password)
    {
        if (String.IsNullOrEmpty(data))
            throw new ArgumentException("No data given");
        if (String.IsNullOrEmpty(password))
            throw new ArgumentException("No password given");

        byte[] rawData = Convert.FromBase64String(data.Replace(" ", "+"));
        if (rawData.Length < 8)
            throw new ArgumentException("Invalid input data");

        // setup the decryption algorithm
        byte[] salt = new byte[8];
        for (int i = 0; i < salt.Length; i++)
            salt[i] = rawData[i];

        Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(password, salt);

        TripleDES tdes = TripleDES.Create();
        //Rijndael aes = Rijndael.Create();

        tdes.IV = keyGenerator.GetBytes(tdes.BlockSize / 8);
        tdes.Key = keyGenerator.GetBytes(tdes.KeySize / 8);
        // decrypt the data
        using (MemoryStream memoryStream = new MemoryStream())
        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, tdes.CreateDecryptor(), CryptoStreamMode.Write))
        {
            cryptoStream.Write(rawData, 8, rawData.Length - 8);
            cryptoStream.Close();

            byte[] decrypted = memoryStream.ToArray();
            return Encoding.Unicode.GetString(decrypted);
        }
    }
コード例 #7
0
ファイル: Crypto.cs プロジェクト: mgerasika/portmone-app
    public static string Encrypt(this string text, string lKey)
    {
        try
        {
            using (Aes aes = new AesManaged())
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(lKey));
                aes.Key = deriveBytes.GetBytes(128 / 8);
                aes.IV = aes.Key;
                using (MemoryStream encryptionStream = new MemoryStream())
                {
                    using (CryptoStream encrypt = new CryptoStream(encryptionStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        byte[] cleanText = Encoding.UTF8.GetBytes(text);
                        encrypt.Write(cleanText, 0, cleanText.Length);
                        encrypt.FlushFinalBlock();
                    }

                    byte[] encryptedData = encryptionStream.ToArray();
                    string encryptedText = Convert.ToBase64String(encryptedData);


                    return encryptedText;
                }
            }
        }
        catch
        {
            return String.Empty;
        }
    }
コード例 #8
0
    internal static SecurePassword GetSaltHash(string password) {

        Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, 20);
        byte[] salt = deriveBytes.Salt;
        byte[] pass = deriveBytes.GetBytes(20);
        return new SecurePassword(Convert.ToBase64String(pass), Convert.ToBase64String(salt));
    }
コード例 #9
0
ファイル: Encrypter.cs プロジェクト: RyanShaul/dig
 public static string Decrypt(string cipherText)
 {
     byte[] cipherBytes = Convert.FromBase64String(cipherText);
         Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(_Pwd, _Salt);
         byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
         return System.Text.Encoding.Unicode.GetString(decryptedData);
 }
コード例 #10
0
    internal static bool DecryptFile(string inputPath, string outputPath, string password)
    {
        var input = new FileStream(inputPath, FileMode.Open, FileAccess.Read);
        var output = new FileStream(outputPath, FileMode.OpenOrCreate, FileAccess.Write);

        // Essentially, if you want to use RijndaelManaged as AES you need to make sure that:
        // 1.The block size is set to 128 bits
        // 2.You are not using CFB mode, or if you are the feedback size is also 128 bits
        RijndaelManaged algorithm = new RijndaelManaged {KeySize = 256, BlockSize = 128};

        algorithm.Mode = CipherMode.CBC;

        var key = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(Salt));

        algorithm.Key = key.GetBytes(algorithm.KeySize/8);
        algorithm.IV = key.GetBytes(algorithm.BlockSize/8);

        try
        {
        using (var decryptedStream = new CryptoStream(output, algorithm.CreateDecryptor(), CryptoStreamMode.Write))
        {
        CopyStream(input, decryptedStream);
        return true;
        }
        }
        catch (CryptographicException)
        {
        throw new InvalidDataException("Please supply a correct password");
        }
        catch (Exception ex)
        {
        throw new Exception(ex.Message);
        }
    }
コード例 #11
0
 private static byte[] PBKDF2(string password, byte[] salt, int interations,
     int outputBytes)
 {
     Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, salt);
     pbkdf2.IterationCount = interations;
     return pbkdf2.GetBytes(outputBytes);
 }
    //This method is to encrypt the password given by user.
    public static string Encrypt(string data, string password)
    {
        if (String.IsNullOrEmpty(data))
            throw new ArgumentException("No data given");
        if (String.IsNullOrEmpty(password))
            throw new ArgumentException("No password given");

        // setup the encryption algorithm
        Rfc2898DeriveBytes keyGenerator = new Rfc2898DeriveBytes(password, 8);
        TripleDES tdes = TripleDES.Create();
        //Rijndael aes = Rijndael.Create();

        tdes.IV = keyGenerator.GetBytes(tdes.BlockSize / 8);
        tdes.Key = keyGenerator.GetBytes(tdes.KeySize / 8);

        // encrypt the data
        byte[] rawData = Encoding.Unicode.GetBytes(data);
        using (MemoryStream memoryStream = new MemoryStream())
        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, tdes.CreateEncryptor(), CryptoStreamMode.Write))
        {
            memoryStream.Write(keyGenerator.Salt, 0, keyGenerator.Salt.Length);
            cryptoStream.Write(rawData, 0, rawData.Length);
            cryptoStream.Close();

            byte[] encrypted = memoryStream.ToArray();
            return Convert.ToBase64String(encrypted);
        }
    }
コード例 #13
0
ファイル: Crypto.cs プロジェクト: mgerasika/portmone-app
    public static string Decrypt(this string text, string lKey)
    {
        try
        {
            using (Aes aes = new AesManaged())
            {
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Encoding.UTF8.GetString(IVa, 0, IVa.Length), Encoding.UTF8.GetBytes(lKey));
                aes.Key = deriveBytes.GetBytes(128 / 8);
                aes.IV = aes.Key;

                using (MemoryStream decryptionStream = new MemoryStream())
                {
                    using (CryptoStream decrypt = new CryptoStream(decryptionStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        byte[] encryptedData = Convert.FromBase64String(text);


                        decrypt.Write(encryptedData, 0, encryptedData.Length);
                        decrypt.Flush();
                    }

                    byte[] decryptedData = decryptionStream.ToArray();
                    string decryptedText = Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);


                    return decryptedText;
                }
            }
        }
        catch
        {
            return String.Empty;
        }
    }
コード例 #14
0
    public bool TryDecrypt(string encryptedItem, string password, out string decryptedItem)
    {
        if (string.IsNullOrEmpty (encryptedItem) ||
            string.IsNullOrEmpty (password)) {
            decryptedItem = "";
            return false;
        }

        try {
            byte[] cipherBytes = Convert.FromBase64String (encryptedItem);

            using (var memoryStream = new MemoryStream(cipherBytes)) {
                var des = new DESCryptoServiceProvider ();

                byte[] iv = new byte[8];
                memoryStream.Read (iv, 0, iv.Length);

                var rfc2898DeriveBytes = new Rfc2898DeriveBytes (password, iv, ITERATIONS);

                byte[] key = rfc2898DeriveBytes.GetBytes (8);

                using (var cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(key, iv), CryptoStreamMode.Read))
                using (var streamReader = new StreamReader(cryptoStream)) {
                    decryptedItem = streamReader.ReadToEnd ();
                    return true;
                }
            }
        } catch (Exception ex) {
            Logger.instance.Log (new Logger.Message (this, ex));

            decryptedItem = "";
            return false;
        }
    }
コード例 #15
0
    public string Encrypt(string item, string password)
    {
        if (item == null) {
            throw new ArgumentNullException ("item");
        }

        if (string.IsNullOrEmpty (password)) {
            throw new ArgumentNullException ("password");
        }

        var des = new DESCryptoServiceProvider ();

        des.GenerateIV ();

        var rfc2898DeriveBytes = new Rfc2898DeriveBytes (password, des.IV, ITERATIONS);

        byte[] key = rfc2898DeriveBytes.GetBytes (8);

        using (var memoryStream = new MemoryStream()) {
            using (var cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(key, des.IV), CryptoStreamMode.Write)) {
                memoryStream.Write (des.IV, 0, des.IV.Length);

                byte[] bytes = Encoding.UTF8.GetBytes (item);

                cryptoStream.Write (bytes, 0, bytes.Length);
                cryptoStream.FlushFinalBlock ();

                return Convert.ToBase64String (memoryStream.ToArray ());
            }
        }
    }
コード例 #16
0
ファイル: aesEncrypt.cs プロジェクト: kkrnt/decryptPassword
 public byte[] encrypt(string plainText, string ivCode16, string pass8, string salt8)
 {
     var num = 256;
     var bytes = Encoding.ASCII.GetBytes(ivCode16);
     var rfc2898DeriveBytes = new Rfc2898DeriveBytes(pass8, Encoding.ASCII.GetBytes(salt8));
     var bytes2 = rfc2898DeriveBytes.GetBytes(num/8);
     return encryptStringToBytes_AES(plainText, bytes2, bytes);
 }
コード例 #17
0
ファイル: aesEncrypt.cs プロジェクト: kkrnt/decryptPassword
 public string decrypt(byte[] cipherText, string ivCode16, string pass8, string salt8)
 {
     var num = 256;
     var bytes = Encoding.ASCII.GetBytes(ivCode16);
     var rfc2898DeriveBytes = new Rfc2898DeriveBytes(pass8, Encoding.ASCII.GetBytes(salt8));
     var bytes2 = rfc2898DeriveBytes.GetBytes(num/8);
     return decryptStringFromBytes_AES(cipherText, bytes2, bytes);
 }
コード例 #18
0
ファイル: EncryptDecrypt.cs プロジェクト: scottw12/RootCellar
    public static string DecryptPasswordMD5(string cipherText, string p_strSaltValue)
    {
        string strReturn = string.Empty;

        try
        {
            byte[] initVectorBytes = null;
            initVectorBytes = System.Text.Encoding.ASCII.GetBytes(m_strInitVector);
            byte[] saltValueBytes = null;
            saltValueBytes = System.Text.Encoding.ASCII.GetBytes(p_strSaltValue);

            byte[] cipherTextBytes = null;
            cipherTextBytes = Convert.FromBase64String(cipherText.ToString());

            Rfc2898DeriveBytes password = default(Rfc2898DeriveBytes);
            password = new Rfc2898DeriveBytes(m_strPassPhrase, saltValueBytes, m_strPasswordIterations);
            //
            byte[] keyBytes = null;
            int intKeySize = 0;
            //Integer
            intKeySize = Convert.ToInt32((m_intKeySize / 8));
            keyBytes = password.GetBytes(intKeySize);

            System.Security.Cryptography.RijndaelManaged symmetricKey = null;
            symmetricKey = new System.Security.Cryptography.RijndaelManaged();

            symmetricKey.Mode = System.Security.Cryptography.CipherMode.CBC;

            System.Security.Cryptography.ICryptoTransform decryptor = null;
            decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);

            System.IO.MemoryStream memoryStream = null;
            memoryStream = new System.IO.MemoryStream(cipherTextBytes);

            System.Security.Cryptography.CryptoStream cryptoStream = null;
            cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, decryptor, System.Security.Cryptography.CryptoStreamMode.Read);

            byte[] plainTextBytes = null;
            plainTextBytes = new byte[cipherTextBytes.Length + 1];

            int decryptedByteCount = 0;
            decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);

            memoryStream.Close();
            cryptoStream.Close();

            string plainText = null;
            plainText = System.Text.Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);

            strReturn = plainText;
        }
        catch (Exception ex)
        {
            strReturn = null;
        }
        return strReturn;
    }
コード例 #19
0
ファイル: KeyGen.cs プロジェクト: allanckw/GEMS-Web
    static KeyGen()
    {
        //We create the Rfc2898DerveBytes once as Rfc2898DeriveBytes uses a pseudo-random number generator based on HMACSHA1.

        rfcKeyGen = new Rfc2898DeriveBytes(seedToUse, SALT);
        //When calling GetBytes it initializes a new instance of HMAC, Later calls to GetBytes does not need to do this.
        key = rfcKeyGen.GetBytes(32);
        //Generate Initialization Vector - This will be less expensive as we have already intialized Rfc2898DeriveBytes
        initVector = rfcKeyGen.GetBytes(16);
    }
コード例 #20
0
ファイル: MyHelper.cs プロジェクト: raazalok/IntranetHome
 static MyHelper()
 {
     //We create the Rfc2898DerveBytes once as
     //Rfc2898DeriveBytes uses a pseudo-random number generator based on HMACSHA1.
     //When calling GetBytes it initializes a new instance of HMAC which takes some time.
     //Subsequent calls to GetBytes does not need to do this initialization.
     keyGenerator = new Rfc2898DeriveBytes(ENCRYPTION_KEY, SALT);
     key = keyGenerator.GetBytes(32);
     //Generate Initialization Vector - This will be less expensive as we have already intialized Rfc2898DeriveBytes
     iv = keyGenerator.GetBytes(16);
 }
コード例 #21
0
ファイル: Crypto.cs プロジェクト: JJJohan/RTS
    private ICryptoTransform InitDecrypt(string a_key)
    {
        byte[] keyBytes = Encoding.Unicode.GetBytes(a_key);
        Rfc2898DeriveBytes derivedKey = new Rfc2898DeriveBytes(a_key, keyBytes);

        RijndaelManaged rijndaelCSP = new RijndaelManaged();
        rijndaelCSP.Key = derivedKey.GetBytes(rijndaelCSP.KeySize / 8);
        rijndaelCSP.IV = derivedKey.GetBytes(rijndaelCSP.BlockSize / 8);
        ICryptoTransform decryptor = rijndaelCSP.CreateDecryptor();
        rijndaelCSP.Clear();
        return decryptor;
    }
コード例 #22
0
ファイル: Encryption.cs プロジェクト: pbalint/Playground
    /// <summary> 
    /// Decrypt the given string.  Assumes the string was encrypted using  
    /// EncryptStringAES(), using an identical sharedSecret. 
    /// </summary> 
    /// <param name="cipherText">The text to decrypt.</param> 
    /// <param name="sharedSecret">A password used to generate a key for decryption.</param> 
    public static string DecryptStringAES( string cipherText, string sharedSecret )
    {
        if ( string.IsNullOrEmpty( cipherText ) )
            throw new ArgumentNullException( "cipherText" );
        if ( string.IsNullOrEmpty( sharedSecret ) )
            throw new ArgumentNullException( "sharedSecret" );

        // Declare the RijndaelManaged object
        // used to decrypt the data.
        RijndaelManaged aesAlg = null;

        // Declare the string used to hold
        // the decrypted text.
        string plaintext = null;

        try
        {
            // generate the key from the shared secret and the salt
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes( sharedSecret, _salt );

            // Create the streams used for decryption.
            byte[] bytes = Convert.FromBase64String( cipherText );
            using ( MemoryStream msDecrypt = new MemoryStream( bytes ) )
            {
                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg = new RijndaelManaged();
                aesAlg.Key = key.GetBytes( aesAlg.KeySize / 8 );
                // Get the initialization vector from the encrypted stream
                aesAlg.IV = ReadByteArray( msDecrypt );
                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor( aesAlg.Key, aesAlg.IV );
                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.
                        plaintext = srDecrypt.ReadToEnd();
                }
            }
        }
        finally
        {
            // Clear the RijndaelManaged object.
            if ( aesAlg != null )
                aesAlg.Clear();
        }

        return plaintext;
    }
コード例 #23
0
    public static SqlString HashPassword(string password)
    {
        if (password == null) throw new ArgumentNullException("password");
        byte[] salt;
        byte[] bytes;
        Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, 16, 1000);

        salt = rfc2898DeriveBytes.Salt;
        bytes = rfc2898DeriveBytes.GetBytes(32);

        byte[] array = new byte[49];
        Buffer.BlockCopy(salt, 0, array, 1, 16);
        Buffer.BlockCopy(bytes, 0, array, 17, 32);

        return new SqlString(Convert.ToBase64String(array));
    }
コード例 #24
0
    public static string Decrypt(string encryptedText)
    {
        byte[] cipherTextBytes = Convert.FromBase64String(encryptedText);
        byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
        var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };

        var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
        var memoryStream = new MemoryStream(cipherTextBytes);
        var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
        byte[] plainTextBytes = new byte[cipherTextBytes.Length];

        int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
        memoryStream.Close();
        cryptoStream.Close();
        return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
    }
コード例 #25
0
ファイル: DESEncryption.cs プロジェクト: Doychev/RunningBack
    public bool TryDecrypt(string cipherText, string password, out string plainText)
    {
        // its pointless trying to decrypt if the cipher text
        // or password has not been supplied
        if (string.IsNullOrEmpty(cipherText) ||
            string.IsNullOrEmpty(password))
        {
            plainText = "";
            return false;
        }

        try
        {
            byte[] cipherBytes = Convert.FromBase64String(cipherText);

            using (var memoryStream = new MemoryStream(cipherBytes))
            {
                // create instance of the DES crypto provider
                var des = new DESCryptoServiceProvider();

                // get the IV
                byte[] iv = new byte[8];
                memoryStream.Read(iv, 0, iv.Length);

                // use derive bytes to generate key from password and IV
                var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, iv, Iterations);

                byte[] key = rfc2898DeriveBytes.GetBytes(8);

                using (var cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(key, iv), CryptoStreamMode.Read))
                using (var streamReader = new StreamReader(cryptoStream))
                {
                    plainText = streamReader.ReadToEnd();
                    return true;
                }
            }
        }
        catch (Exception ex)
        {
            // TODO: log exception
            Console.WriteLine(ex);

            plainText = "";
            return false;
        }
    }
コード例 #26
0
    public string Encrypt(string plainText, string password)
    {
        if (plainText == null)
        {
            throw new ArgumentNullException("plainText");
        }

        if (string.IsNullOrEmpty(password))
        {
            throw new ArgumentNullException("password");
        }

        // generate a random IV will be used a salt value for generating key
        cryptoProvider.GenerateIV();

        // use derive bytes to generate a key from the password and IV
        var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, cryptoProvider.IV, Iterations);

        // generate a key from the password provided
        if (SecurePlayerPrefs.useAES)
        {
            keyBytes = 16;
        }
        else
        {
            keyBytes = 8;
        }
        byte[] key = rfc2898DeriveBytes.GetBytes(keyBytes);

        // encrypt the plainText
        using (var memoryStream = new MemoryStream())
        using (var cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(key, cryptoProvider.IV), CryptoStreamMode.Write))
        {
            // write the salt first not encrypted
            memoryStream.Write(cryptoProvider.IV, 0, cryptoProvider.IV.Length);

            // convert the plain text string into a byte array
            byte[] bytes = Encoding.UTF8.GetBytes(plainText);

            // write the bytes into the crypto stream so that they are encrypted bytes
            cryptoStream.Write(bytes, 0, bytes.Length);
            cryptoStream.FlushFinalBlock();

            return Convert.ToBase64String(memoryStream.ToArray());
        }
    }
コード例 #27
0
    public string Decrypt(string cipherText)
    {
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
        //PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
		Rfc2898DeriveBytes password = new Rfc2898DeriveBytes(passPhrase, System.Text.Encoding.UTF8.GetBytes(salt));
        byte[] keyBytes = password.GetBytes(keysize / 8);
        RijndaelManaged symmetricKey = new RijndaelManaged();
        symmetricKey.Mode = CipherMode.CBC;
        ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
        MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
        CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
        byte[] plainTextBytes = new byte[cipherTextBytes.Length];
        int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
        memoryStream.Close();
        cryptoStream.Close();
        return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
    }
コード例 #28
0
    public string Encrypt(string plainText)
    {
        byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        //PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
		Rfc2898DeriveBytes password = new Rfc2898DeriveBytes(passPhrase, System.Text.Encoding.UTF8.GetBytes(salt));
        byte[] keyBytes = password.GetBytes(keysize / 8);
        RijndaelManaged symmetricKey = new RijndaelManaged();
        symmetricKey.Mode = CipherMode.CBC;
        ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
        cryptoStream.FlushFinalBlock();
        byte[] cipherTextBytes = memoryStream.ToArray();
        memoryStream.Close();
        cryptoStream.Close();
        return Convert.ToBase64String(cipherTextBytes);
    }
コード例 #29
0
ファイル: Crypto.cs プロジェクト: Akashhhhh/UIU_HRM
        /* =======================
         * HASHED PASSWORD FORMATS
         * =======================
         * 
         * Version 0:
         * PBKDF2 with HMAC-SHA1, 128-bit salt, 256-bit subkey, 1000 iterations.
         * (See also: SDL crypto guidelines v5.1, Part III)
         * Format: { 0x00, salt, subkey }
         */

        public static string HashPassword(string password)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            byte[] salt;
            byte[] subkey;
            using (var deriveBytes = new Rfc2898DeriveBytes(password, SaltSize, Pbkdf2Count))
            {
                salt = deriveBytes.Salt;
                subkey = deriveBytes.GetBytes(Pbkdf2SubkeyLength);
            }

            byte[] outputBytes = new byte[1 + SaltSize + Pbkdf2SubkeyLength];
            Buffer.BlockCopy(salt, 0, outputBytes, 1, SaltSize);
            Buffer.BlockCopy(subkey, 0, outputBytes, 1 + SaltSize, Pbkdf2SubkeyLength);
            return Convert.ToBase64String(outputBytes);
        }
コード例 #30
0
        /// <summary>
        /// Decrypt data using a passphrase and a given algorithm.
        /// </summary>
        /// <typeparam name="T">Algorithm to use.</typeparam>
        /// <param name="bytes">Bytes to decrypt.</param>
        /// <param name="passphrase">Passphrase to use.</param>
        /// <returns>Decrypted data.</returns>
        public static byte[] Decrypt <T>(byte[] bytes, string passphrase) where T : SymmetricAlgorithm, new()
        {
            using var cipher = new T();

            var pwdBytes = new Rfc2898DeriveBytes(
                Encoding.UTF7.GetBytes(passphrase),
                Salt,
                Iterations);

            var keyBytes = pwdBytes.GetBytes(KeySize / 8);

            cipher.Mode = CipherMode.CBC;

            using var decryptor = cipher.CreateDecryptor(keyBytes, pwdBytes.GetBytes(16));
            using var stream    = new MemoryStream(bytes);
            using var reader    = new CryptoStream(stream, decryptor, CryptoStreamMode.Read);

            var data = new byte[stream.Length];

            reader.Read(data, 0, data.Length);

            cipher.Clear();

            while (true)
            {
                if (data.Last() != 0x00)
                {
                    break;
                }

                data = data
                       .Take(data.Length - 1)
                       .ToArray();
            }

            return(data);
        }
コード例 #31
0
ファイル: AesHelper.cs プロジェクト: chenchungit/ky
        /// <summary>
        /// AES解密字节流
        /// </summary>
        /// <param name="encryptData">密文字节流</param>
        /// <param name="passwd">密码</param>
        /// <param name="saltValue">盐值</param>
        /// <returns>解密后的明文字节流</returns>
        public static byte[] AesDecryptBytes(byte[] encryptData, string passwd, string saltValue)
        {
            // 盐值(与加密时设置的值必须一致)
            // 密码值(与加密时设置的值必须一致)
            byte[] saltBytes = Encoding.UTF8.GetBytes(saltValue);

            AesManaged         aes = new AesManaged();
            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(passwd, saltBytes);

            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize   = aes.LegalKeySizes[0].MaxSize;
            aes.Key       = rfc.GetBytes(aes.KeySize / 8);
            aes.IV        = rfc.GetBytes(aes.BlockSize / 8);

            // 用当前的 Key 属性和初始化向量 IV 创建对称解密器对象
            ICryptoTransform decryptTransform = aes.CreateDecryptor();

            // 解密后的输出流
            MemoryStream decryptStream = new MemoryStream();

            // 将解密后的目标流(decryptStream)与解密转换(decryptTransform)相连接
            CryptoStream decryptor = new CryptoStream(decryptStream, decryptTransform, CryptoStreamMode.Write);

            try
            {
                // 将一个字节序列写入当前 CryptoStream (完成解密的过程)
                decryptor.Write(encryptData, 0, encryptData.Length);
                decryptor.Close();
            }
            catch (System.Exception)
            {
                return(null); //解密失败
            }

            // 将解密后所得到的流转换为字符串
            return(decryptStream.ToArray());
        }
コード例 #32
0
    /// <summary>
    /// Decrypts a byte array previously encrypted with RhinoScriptEncrypter.
    /// </summary>
    private byte[] Decrypt(byte[] encryptedBuffer, string password)
    {
        if (null == encryptedBuffer || 0 == encryptedBuffer.Length || string.IsNullOrEmpty(password))
        {
            return(null);
        }

        byte[]       buffer       = null;
        CryptoStream cryptoStream = null;

        try
        {
            Rfc2898DeriveBytes secretKey    = new Rfc2898DeriveBytes(password, _keySalt);
            RijndaelManaged    cipher       = new RijndaelManaged();
            ICryptoTransform   transform    = cipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16));
            MemoryStream       memoryStream = new MemoryStream();
            cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write);
            cryptoStream.Write(encryptedBuffer, 0, encryptedBuffer.Length);
            cryptoStream.FlushFinalBlock();
            buffer = memoryStream.ToArray();
        }

        catch
        {
            buffer = null;
        }

        finally
        {
            if (null != cryptoStream)
            {
                cryptoStream.Close();
            }
        }

        return(buffer);
    }
コード例 #33
0
    // hashedPassword must be of the format of HashWithPassword (salt + Hash(salt+input)
    public bool VerifyHashedPassword(string hashedPassword, string password)
    {
        const int PBKDF2IterCount    = 1000;    // default for Rfc2898DeriveBytes
        const int PBKDF2SubkeyLength = 256 / 8; // 256 bits
        const int SaltSize           = 128 / 8; // 128 bits

        if (hashedPassword == null)
        {
            throw new ArgumentNullException("hashedPassword");
        }
        if (password == null)
        {
            throw new ArgumentNullException("password");
        }

        byte[] hashedPasswordBytes = Convert.FromBase64String(hashedPassword);

        // Verify a version 0 (see comment above) password hash.

        if (hashedPasswordBytes.Length != (1 + SaltSize + PBKDF2SubkeyLength) || hashedPasswordBytes[0] != 0x00)
        {
            // Wrong length or version header.
            return(false);
        }

        byte[] salt = new byte[SaltSize];
        Buffer.BlockCopy(hashedPasswordBytes, 1, salt, 0, SaltSize);
        byte[] storedSubkey = new byte[PBKDF2SubkeyLength];
        Buffer.BlockCopy(hashedPasswordBytes, 1 + SaltSize, storedSubkey, 0, PBKDF2SubkeyLength);

        byte[] generatedSubkey;
        using (var deriveBytes = new Rfc2898DeriveBytes(password, salt, PBKDF2IterCount))
        {
            generatedSubkey = deriveBytes.GetBytes(PBKDF2SubkeyLength);
        }
        return(ByteArraysEqual(storedSubkey, generatedSubkey));
    }
コード例 #34
0
        internal string Encrypt(string plainText, string password, string saltBase64Text, int passwordIterations,
                                string initializationVector, KeySize keySize)
        {
            if (initializationVector.Length != 16)
            {
                throw new ArgumentException("initializationVector parameter length must be 16.");
            }
            var initializationVectorBytes = Encoding.ASCII.GetBytes(initializationVector);
            var saltValueBytes            = Encoding.ASCII.GetBytes(saltBase64Text);
            var plainTextBytes            = Encoding.UTF8.GetBytes(plainText);
            var derivedPassword           = new Rfc2898DeriveBytes(password, saltValueBytes, passwordIterations);
            var keyBytes = derivedPassword.GetBytes((int)keySize / 8);

            var symmetricKey = new RijndaelManaged
            {
                Mode = CipherMode.CBC
            };

            byte[] cipherTextBytes;

            using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, initializationVectorBytes))
            {
                using (var memStream = new MemoryStream())
                {
                    using (var cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                        cryptoStream.FlushFinalBlock();
                        cipherTextBytes = memStream.ToArray();
                        memStream.Close();
                        cryptoStream.Close();
                    }
                }
            }

            return(Convert.ToBase64String(cipherTextBytes));
        }
コード例 #35
0
        public static string Decrypt(string cipherText, string passPhrase)
        {
            // Get the complete stream of bytes that represent:
            // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
            var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
            // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
            var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
            // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
            var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
            // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
            var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();

            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = password.GetBytes(Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = 256;
                    symmetricKey.Mode      = CipherMode.CBC;
                    symmetricKey.Padding   = PaddingMode.PKCS7;
                    using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream(cipherTextBytes))
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                            {
                                var plainTextBytes     = new byte[cipherTextBytes.Length];
                                var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                                memoryStream.Close();
                                cryptoStream.Close();
                                return(Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount));
                            }
                        }
                    }
                }
            }
        }
コード例 #36
0
        private static string CifraStringa(string strInChiaro, string secret)
        {
            string          stringa = null;
            RijndaelManaged aesAlg  = null;

            try
            {
                Rfc2898DeriveBytes chiave = new Rfc2898DeriveBytes(secret, _salt);
                aesAlg     = new RijndaelManaged();
                aesAlg.Key = chiave.GetBytes(aesAlg.KeySize / 8);

                ICryptoTransform cifratore = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream ms = new MemoryStream())
                {
                    ms.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                    ms.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                    using (CryptoStream csEncrypt = new CryptoStream(ms, cifratore, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(strInChiaro);
                        }
                    }
                    stringa = Convert.ToBase64String(ms.ToArray());
                }
            }
            finally
            {
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }

            return(stringa);
        }
コード例 #37
0
        public static PasswordVerificationResult VerifyHashedPassword(string hashedPassword, [NotNull] string password)
        {
            if (string.IsNullOrEmpty(hashedPassword))
            {
                return(PasswordVerificationResult.Failed);
            }

            var passwordBytes = Convert.FromBase64String(hashedPassword);

            if (passwordBytes.Length < 1)
            {
                return(PasswordVerificationResult.Failed);
            }

            var version = passwordBytes[0];

            if (version > Version)
            {
                return(PasswordVerificationResult.Failed);
            }

            var salt = new byte[SaltSize];

            Buffer.BlockCopy(passwordBytes, 1, salt, 0, SaltSize);
            var subKey = new byte[Pbkdf2SubkeyLength];

            Buffer.BlockCopy(passwordBytes, 1 + SaltSize, subKey, 0, Pbkdf2SubkeyLength);

            byte[] bytes;

            using (var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, salt, Pbkdf2IterCount, HashAlgorithmName))
            {
                bytes = rfc2898DeriveBytes.GetBytes(Pbkdf2SubkeyLength);
            }

            return(FixedTimeEquals(subKey, bytes) ? PasswordVerificationResult.Success : PasswordVerificationResult.Failed);
        }
コード例 #38
0
        public string Encrypt(string plainText)
        {
            if (string.IsNullOrEmpty(plainText))
            {
                return(plainText);
            }
            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            using (var password = new Rfc2898DeriveBytes(_passPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = password.GetBytes(_Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = _Keysize;
                    symmetricKey.Mode      = CipherMode.CBC;
                    symmetricKey.Padding   = PaddingMode.PKCS7;
                    using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                            {
                                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                                cryptoStream.FlushFinalBlock();
                                // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                                var cipherTextBytes = saltStringBytes;
                                cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                                cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                                memoryStream.Close();
                                cryptoStream.Close();
                                return(Convert.ToBase64String(cipherTextBytes));
                            }
                        }
                    }
                }
            }
        }
コード例 #39
0
ファイル: EncryptHelper.cs プロジェクト: oclockvn/ext
        /// <summary>
        /// Decrypts the ciphertext using the Key.
        /// </summary>
        /// <param name="ciphertext">The ciphertext to decrypt.</param>
        /// <param name="key">The plain text encryption key.</param>
        /// <returns>The decrypted text.</returns>
        public static string AesDecrypt(string ciphertext, string key)
        {
            if (string.IsNullOrEmpty(ciphertext))
            {
                return(string.Empty);
            }

            if (string.IsNullOrEmpty(key))
            {
                key = string.Empty;
            }

            // Extract the salt from our ciphertext
            var allTheBytes     = Convert.FromBase64String(ciphertext);
            var saltBytes       = allTheBytes.Take(_saltSize).ToArray();
            var ciphertextBytes = allTheBytes.Skip(_saltSize).Take(allTheBytes.Length - _saltSize).ToArray();

            using (var keyDerivationFunction = new Rfc2898DeriveBytes(key, saltBytes))
            {
                // Derive the previous IV from the Key and Salt
                var keyBytes = keyDerivationFunction.GetBytes(32);
                var ivBytes  = keyDerivationFunction.GetBytes(16);

                // Create a decrytor to perform the stream transform.
                // Create the streams used for decryption.
                // The default Cipher Mode is CBC and the Padding is PKCS7 which are both good
                using (var aesManaged = new AesManaged())
                    using (var decryptor = aesManaged.CreateDecryptor(keyBytes, ivBytes))
                        using (var memoryStream = new MemoryStream(ciphertextBytes))
                            using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                                using (var streamReader = new StreamReader(cryptoStream))
                                {
                                    // Return the decrypted bytes from the decrypting stream.
                                    return(streamReader.ReadToEnd());
                                }
            }
        }
コード例 #40
0
    static string Decrypt(string strEncript, string password)
    {
        if (!useSecure)
        {
            return(strEncript);
        }

        try
        {
            byte[] cipherBytes = Convert.FromBase64String(strEncript);

            using (var memoryStream = new MemoryStream(cipherBytes))
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                byte[] iv = GetIV();
                memoryStream.Read(iv, 0, iv.Length);

                // use derive bytes to generate key from password and IV
                var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, iv, Iterations);

                byte[] key = rfc2898DeriveBytes.GetBytes(8);

                using (var cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(key, iv), CryptoStreamMode.Read))
                    using (var streamReader = new StreamReader(cryptoStream))
                    {
                        string strPlain = streamReader.ReadToEnd();
                        return(strPlain);
                    }
            }
        }
        catch (Exception e)
        {
            Debug.LogWarning("Decrypt Exception: " + e);
            return(strEncript);
        }
    }
コード例 #41
0
    // did this for nothing TT; forgot that server does not know user's data so check is pointless; at least it knows the username tho TT
    //    protected void existingNric_validate(object source, ServerValidateEventArgs args)
    //    {
    //
    //        UserCustomer customer = new UserCustomer();
    //        List<string> cusList = customer.getAllNric();
    //        System.Diagnostics.Debug.WriteLine("nric in list :" + cusList.Count);
    //
    //        string currentnirc = nricInput.Text;
    //        System.Diagnostics.Debug.WriteLine("curr nric :" + currentnirc);
    //
    //        int validateme = 0;
    //
    //        for (int i = 0; i < cusList.Count; i++)
    //        {
    //            if (currentnirc.Equals(cusList[i]))
    //            {
    //                validateme++;
    //            }
    //
    //
    //
    //
    //
    //        }
    //        if (validateme != 0)
    //        {
    //            args.IsValid = false;
    //        }
    //        else
    //        {
    //            args.IsValid = true;
    //        }
    //
    //
    //
    //    }


    protected string encryptData(string data, string hash, byte[] salttoByte)
    {
        byte[] cipherText;

        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(hash, salttoByte);

        RijndaelManaged cipher = new RijndaelManaged();

        cipher.Key = pdb.GetBytes(32);
        cipher.IV  = pdb.GetBytes(16);
        ICryptoTransform enCryptoTransform = cipher.CreateEncryptor();

        byte[] plainText = Encoding.UTF8.GetBytes(data);
        cipherText = enCryptoTransform.TransformFinalBlock(plainText, 0, plainText.Length);



        string sendback = Convert.ToBase64String(cipherText);

        System.Diagnostics.Debug.WriteLine("Encrypted cipher test " + sendback);

        byte[] testingtodelete = Convert.FromBase64String(sendback);
        string testing2        = Convert.ToBase64String(testingtodelete);

        System.Diagnostics.Debug.WriteLine("Encrypted cipher testINGGG " + testing2);



        //decrypt testing
//        string decrdfs = decryptData(sendback, hash, salttoByte);
//
//        System.Diagnostics.Debug.WriteLine("Original " + data);
//        System.Diagnostics.Debug.WriteLine("decrypted cipher test " + decrdfs);


        return(sendback);
    }
コード例 #42
0
        /// <summary>
        /// Incrypt the input using password provided
        /// </summary>
        /// <param name="input">Input string to encrypt</param>
        /// <param name="password">Password to use</param>
        /// <returns>Encrypted string</returns>
        public static string Encrypt(string input, string password)
        {
            string data = input;

            byte[] utfdata   = UTF8Encoding.UTF8.GetBytes(data);
            byte[] saltBytes = UTF8Encoding.UTF8.GetBytes(password);



            // Our symmetric encryption algorithm
            AesManaged aes = new AesManaged();

            // We're using the PBKDF2 standard for password-based key generation
            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(password, saltBytes);

            // Setting our parameters
            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize   = aes.LegalKeySizes[0].MaxSize;
            aes.Key       = rfc.GetBytes(aes.KeySize / 8);
            aes.IV        = rfc.GetBytes(aes.BlockSize / 8);

            // Encryption
            ICryptoTransform encryptTransf = aes.CreateEncryptor();

            // Output stream, can be also a FileStream
            MemoryStream encryptStream = new MemoryStream();
            CryptoStream encryptor     = new CryptoStream(encryptStream, encryptTransf, CryptoStreamMode.Write);

            encryptor.Write(utfdata, 0, utfdata.Length);
            encryptor.Flush();
            encryptor.Close();

            byte[] encryptBytes    = encryptStream.ToArray();
            string encryptedString = Convert.ToBase64String(encryptBytes);

            return(encryptedString);
        }
コード例 #43
0
ファイル: EncryptionWeak.cs プロジェクト: dbartels13/Common
        protected static byte[] Decrypt(byte[] encryptedMessage, string password, int nonSecretPayloadLength = 0)
        {
            // Parameter checking
            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));
            }

            var cryptSalt = new byte[SaltBitSize / 8];
            var authSalt  = new byte[SaltBitSize / 8];

            // Grab Salt from Non-Secret Payload
            Array.Copy(encryptedMessage, nonSecretPayloadLength, cryptSalt, 0, cryptSalt.Length);
            Array.Copy(encryptedMessage, nonSecretPayloadLength + cryptSalt.Length, authSalt, 0, authSalt.Length);

            byte[] cryptKey;
            byte[] authKey;

            // Generate crypt key
            using (var generator = new Rfc2898DeriveBytes(password, cryptSalt, Iterations))
            {
                cryptKey = generator.GetBytes(KeyBitSize / 8);
            }

            // Generate auth key
            using (var generator = new Rfc2898DeriveBytes(password, authSalt, Iterations))
            {
                authKey = generator.GetBytes(KeyBitSize / 8);
            }

            return(Decrypt(encryptedMessage, cryptKey, authKey, cryptSalt.Length + authSalt.Length + nonSecretPayloadLength));
        }
コード例 #44
0
ファイル: Cipher.cs プロジェクト: PipeRift/Pipeshot
 public static string Encrypt(string plainText, string passPhrase)
 {
     try {
         byte[] saltStringBytes = Generate256BitsOfRandomEntropy();
         byte[] ivStringBytes   = Generate256BitsOfRandomEntropy();
         byte[] plainTextBytes  = Encoding.UTF8.GetBytes(plainText);
         using (
             Rfc2898DeriveBytes password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes,
                                                                  DerivationIterations)) {
             byte[] keyBytes = password.GetBytes(Keysize / 8);
             using (RijndaelManaged symmetricKey = new RijndaelManaged()) {
                 symmetricKey.BlockSize = 256;
                 symmetricKey.Mode      = CipherMode.CBC;
                 symmetricKey.Padding   = PaddingMode.PKCS7;
                 using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes)) {
                     using (MemoryStream memoryStream = new MemoryStream()) {
                         using (
                             CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor,
                                                                          CryptoStreamMode.Write)) {
                             cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                             cryptoStream.FlushFinalBlock();
                             byte[] cipherTextBytes = saltStringBytes;
                             cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                             cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                             memoryStream.Close();
                             cryptoStream.Close();
                             return(Convert.ToBase64String(cipherTextBytes));
                         }
                     }
                 }
             }
         }
     }
     catch {
         return(null);
     }
 }
コード例 #45
0
        public static byte[] SimpleDecryptWithPassword(byte[] encryptedMessage, string password,
                                                       int nonSecretPayloadLength = 0)
        {
            //User Error Checks
            if (string.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)
            {
                throw new ArgumentException(String.Format("Must have a password of at least {0} characters!", MinPasswordLength), "password");
            }

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

            var cryptSalt = new byte[SaltBitSize / 8];
            var authSalt  = new byte[SaltBitSize / 8];

            //Grab Salt from Non-Secret Payload
            Array.Copy(encryptedMessage, nonSecretPayloadLength, cryptSalt, 0, cryptSalt.Length);
            Array.Copy(encryptedMessage, nonSecretPayloadLength + cryptSalt.Length, authSalt, 0, authSalt.Length);

            byte[] cryptKey;
            byte[] authKey;

            //Generate crypt key
            using (var generator = new Rfc2898DeriveBytes(password, cryptSalt, Iterations))
            {
                cryptKey = generator.GetBytes(KeyBitSize / 8);
            }
            //Generate auth key
            using (var generator = new Rfc2898DeriveBytes(password, authSalt, Iterations))
            {
                authKey = generator.GetBytes(KeyBitSize / 8);
            }

            return(SimpleDecrypt(encryptedMessage, cryptKey, authKey, cryptSalt.Length + authSalt.Length + nonSecretPayloadLength));
        }
コード例 #46
0
        public byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
        {
            byte[] decryptedBytes = null;

            // Set your salt here, change it to meet your flavor:
            // The salt bytes must be at least 8 bytes.
            byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (RijndaelManaged AES = new RijndaelManaged())
                    {
                        AES.KeySize   = 256;
                        AES.BlockSize = 128;

                        var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
                        AES.Key = key.GetBytes(AES.KeySize / 8);
                        AES.IV  = key.GetBytes(AES.BlockSize / 8);

                        AES.Mode = CipherMode.CBC;

                        using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
                        {
                            cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
                            cs.Close();
                        }
                        decryptedBytes = ms.ToArray();
                    }
                }
                return(decryptedBytes);
            }
            catch (CryptographicException)
            {
                return(Encoding.UTF8.GetBytes("    FailedToDecrypt"));
            }
        }
コード例 #47
0
        public static string GetMusic(string cipherText, string sharedSecret)
        {
            if (string.IsNullOrEmpty(cipherText))
            {
                throw new ArgumentNullException("cipherText");
            }
            if (string.IsNullOrEmpty(sharedSecret))
            {
                throw new ArgumentNullException("sharedSecret");
            }
            RijndaelManaged aesAlg    = null;
            string          plaintext = null;

            try
            {
                Rfc2898DeriveBytes key   = new Rfc2898DeriveBytes(sharedSecret, _salt);
                byte[]             bytes = Convert.FromBase64String(cipherText);
                using (MemoryStream msDecrypt = new MemoryStream(bytes))
                {
                    aesAlg     = new RijndaelManaged();
                    aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                    aesAlg.IV  = ReadByteArray(msDecrypt);
                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                            plaintext = srDecrypt.ReadToEnd();
                }
            }
            finally
            {
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }
            return(plaintext);
        }
コード例 #48
0
        public static string Decrypt(string cipherText)
        {
            if (cipherText == "" || cipherText == null)
            {
                return("");
            }

            var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
            var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
            var ivStringBytes   = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
            var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();

            using (var password = new Rfc2898DeriveBytes(EncrytionKey(), saltStringBytes, DerivationIterations))
            {
                var keyBytes = password.GetBytes(Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = 256;
                    symmetricKey.Mode      = CipherMode.CBC;
                    symmetricKey.Padding   = PaddingMode.PKCS7;
                    using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream(cipherTextBytes))
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                            {
                                var plainTextBytes     = new byte[cipherTextBytes.Length];
                                var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                                memoryStream.Close();
                                cryptoStream.Close();
                                return(Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount));
                            }
                        }
                    }
                }
            }
        }
コード例 #49
0
        public static string Encrypt(string plainText)
        {
            if (string.IsNullOrWhiteSpace(plainText))
            {
                return(plainText);
            }
            try
            {
                byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

                byte[] keyBytes     = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
                var    symmetricKey = new RijndaelManaged()
                {
                    Mode = CipherMode.CBC, Padding = PaddingMode.Zeros
                };
                var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));

                byte[] cipherTextBytes;

                using (var memoryStream = new MemoryStream())
                {
                    using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                        cryptoStream.FlushFinalBlock();
                        cipherTextBytes = memoryStream.ToArray();
                        cryptoStream.Close();
                    }
                    memoryStream.Close();
                }
                return(ByteArrayToString(cipherTextBytes));// Convert.ToBase64String(cipherTextBytes);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
コード例 #50
0
ファイル: Helper.cs プロジェクト: xiexueyong/Knowledge
        private static SymmetricAlgorithm getRijndaelForKey(string key)
        {
            if (rijndaelDict == null)
            {
                rijndaelDict = new Dictionary <string, SymmetricAlgorithm>();
            }
            SymmetricAlgorithm symmetricAlgorithm;

            if (rijndaelDict.ContainsKey(key))
            {
                symmetricAlgorithm = rijndaelDict[key];
            }
            else
            {
                Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(key, new byte[13]
                {
                    73,
                    97,
                    110,
                    32,
                    77,
                    100,
                    118,
                    101,
                    101,
                    100,
                    101,
                    118,
                    118
                });
                symmetricAlgorithm     = Rijndael.Create();
                symmetricAlgorithm.Key = rfc2898DeriveBytes.GetBytes(32);
                symmetricAlgorithm.IV  = rfc2898DeriveBytes.GetBytes(16);
                rijndaelDict.Add(key, symmetricAlgorithm);
            }
            return(symmetricAlgorithm);
        }
コード例 #51
0
        public static string EncryptString(string plainText, string sharedSecret)
        {
            string          result = null;
            RijndaelManaged aesAlg = null;

            try
            {
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, salt);
                aesAlg     = new RijndaelManaged();
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, aesAlg.IV.Length);
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(plainText);
                        }
                    }

                    result = Convert.ToBase64String(msEncrypt.ToArray());
                }
            }
            finally
            {
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }

            return(result);
        }
コード例 #52
0
        /// <summary>
        /// Constructor for an encrypted watermark.
        /// </summary>
        /// <param name="mark">The watermark to encrypt.</param>
        /// <param name="password">The password which is used to derive the encryption key.</param>
        public EncryptedWatermark(Watermark mark, string password)
        {
            /*if (mark.GetMarkType() == this.GetMarkType())
             * {
             *  throw new ArgumentException("You cannot next encrypted watermarks!");
             * }*/
            // get the base marks bytes
            byte[] markBytes = mark.GetBytes();

            bytes     = new Rfc2898DeriveBytes(password, 8);
            this.salt = bytes.Salt;

            key = bytes.GetBytes(Algorithm.KeySize / 8);

            if (Algorithm.IV == null)
            {
                Algorithm.IV = bytes.GetBytes(Algorithm.BlockSize);
            }
            Algorithm.Key = key;
            byte[] iv = Algorithm.IV;

            byte[] cryptData = Encrypt(markBytes, Algorithm);

            MemoryStream ms = new MemoryStream();

            byte[] ivLength = BitConverter.GetBytes(iv.Length);
            ms.Write(ivLength, 0, ivLength.Length);

            ms.Write(iv, 0, iv.Length);

            byte[] dataLength = BitConverter.GetBytes(cryptData.Length);
            ms.Write(dataLength, 0, dataLength.Length);

            ms.Write(cryptData, 0, cryptData.Length);

            cryptedData = ms.ToArray();
        }
コード例 #53
0
        public byte[] AES_Encryption(byte[] Msg, byte[] Key)
        {
            byte[] encryptedBytes = null;

            //salt is generated randomly as an additional number to hash password or message in order o dictionary attack
            //against pre computed rainbow table
            //dictionary attack is a systematic way to test all of possibilities words in dictionary wheather or not is true?
            //to find decryption key
            //rainbow table is precomputed key for cracking password
            // Set your salt here, change it to meet your flavor:
            // The salt bytes must be at least 8 bytes.  == 16 bits
            byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    AES.KeySize   = 256;
                    AES.BlockSize = 128;

                    var key = new Rfc2898DeriveBytes(Key, saltBytes, 1000);
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV  = key.GetBytes(AES.BlockSize / 8);

                    AES.Mode = CipherMode.CBC;

                    using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(Msg, 0, Msg.Length);
                        cs.Close();
                    }
                    encryptedBytes = ms.ToArray();
                }
            }

            return(encryptedBytes);
        }
コード例 #54
0
        public static string Encrypt(string plainText)
        {
            // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
            // so that the same Salt and IV values can be used when decrypting.
            var saltStringBytes = Generate256BitsOfRandomEntropy();
            var ivStringBytes   = Generate256BitsOfRandomEntropy();
            var plainTextBytes  = Encoding.UTF8.GetBytes(plainText);

            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = password.GetBytes(Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = 256;
                    symmetricKey.Mode      = CipherMode.CBC;
                    symmetricKey.Padding   = PaddingMode.PKCS7;
                    using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                            {
                                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                                cryptoStream.FlushFinalBlock();
                                // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                                var cipherTextBytes = saltStringBytes;
                                cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                                cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                                memoryStream.Close();
                                cryptoStream.Close();
                                return(Convert.ToBase64String(cipherTextBytes));
                            }
                        }
                    }
                }
            }
        }
コード例 #55
0
        /// <summary>
        /// Verify a password against a hash
        /// </summary>
        /// <param name="password"></param>
        /// <param name="hashedPassword"></param>
        /// <returns></returns>
        public static bool Verify(string password, string hashedPassword)
        {
            // check hash
            if (!IsHashSupported(hashedPassword))
            {
                throw new NotSupportedException("The hashtype is not supported");
            }

            // extract iteration and Base64 string
            var splittedHashString = hashedPassword.Replace("$MYHASH$V1$", "").Split('$');
            var iterations         = int.Parse(splittedHashString[0]);
            var base64Hash         = splittedHashString[1];

            // get hashbytes
            var hashBytes = Convert.FromBase64String(base64Hash);

            // get salt
            var salt = new byte[SaltSize];

            Array.Copy(hashBytes, 0, salt, 0, SaltSize);

            // create hash with given salt
            var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations);

            byte[] hash = pbkdf2.GetBytes(HashSize);

            // get result
            for (var i = 0; i < HashSize; i++)
            {
                if (hashBytes[i + SaltSize] != hash[i])
                {
                    return(false);
                }
            }

            return(true);
        }
コード例 #56
0
        public static void DecompressAndDecryptAES(Stream fileToDecrypt, string outputFilePath, string password)
        {
            byte[] ReadBuff = new byte[4096];
            if (fileToDecrypt.Read(ReadBuff, 0, 20) != 20)
            {
                throw new Exception("file too small");
            }


            //var Crc = BitConverter.ToUInt32(ReadBuff, 0);
            var length = BitConverter.ToInt32(ReadBuff.Take(4).ToArray(), 0);
            var rfc    = new Rfc2898DeriveBytes(password, ReadBuff.Skip(4).Take(16).ToArray());


            byte[] Key = rfc.GetBytes(16);
            byte[] IV  = rfc.GetBytes(16);
            Directory.CreateDirectory(outputFilePath.Substring(0, outputFilePath.LastIndexOf('\\')));
            using (FileStream outputFile = new FileStream(outputFilePath, FileMode.Create))
            {
                if (length > 0)
                {
                    using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider()
                    {
                        Padding = PaddingMode.None
                    })
                        using (CryptoStream cryptoStream = new CryptoStream(fileToDecrypt, aesProvider.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
                            using (DeflateStream decompressor = new DeflateStream(cryptoStream, CompressionMode.Decompress))
                            {
                                int read = 0;
                                while ((read = decompressor.Read(ReadBuff, 0, ReadBuff.Length)) != 0)
                                {
                                    outputFile.Write(ReadBuff, 0, read);
                                }
                            }
                }
            }
        }
コード例 #57
0
ファイル: Form1.cs プロジェクト: celsec/clinicaboaesperanca
        private bool validatePassword(string username, string password)
        {
            string qs = "SELECT * FROM usuarios WHERE username=@username;";

            MySqlParameter        pam2          = new MySqlParameter("username", username);
            List <MySqlParameter> sqlParameters = new List <MySqlParameter> {
                pam2
            };

            DataTable userTable = executeSelect(qs, sqlParameters);

            if (userTable.Rows.Count == 1)
            {
                string savedPassHash = userTable.Rows[0][2].ToString();
                byte[] hashBytes     = Convert.FromBase64String(savedPassHash);

                byte[] salt = new byte[16];
                Array.Copy(hashBytes, 0, salt, 0, 16);
                var    pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000);
                byte[] hash   = pbkdf2.GetBytes(20);

                bool loginOk = true;
                for (int i = 0; i < 20; i++)
                {
                    if (hashBytes[i + 16] != hash[i])
                    {
                        loginOk = false;
                    }
                }

                return(loginOk);
            }
            else
            {
                return(false);
            }
        }
コード例 #58
0
    public bool TryDecrypt(string cipherText, string password, out string plainText)
    {
        if (string.IsNullOrEmpty(cipherText) || string.IsNullOrEmpty(password))
        {
            plainText = string.Empty;
            return(false);
        }
        bool result;

        try
        {
            byte[] array = Convert.FromBase64String(cipherText);
            using (MemoryStream memoryStream = new MemoryStream(array))
            {
                DESCryptoServiceProvider dESCryptoServiceProvider = new DESCryptoServiceProvider();
                byte[] array2 = new byte[8];
                memoryStream.Read(array2, 0, array2.Length);
                Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, array2, 1000);
                byte[]             bytes = rfc2898DeriveBytes.GetBytes(8);
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, dESCryptoServiceProvider.CreateDecryptor(bytes, array2), 0))
                {
                    using (StreamReader streamReader = new StreamReader(cryptoStream))
                    {
                        plainText = streamReader.ReadToEnd();
                        result    = true;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            plainText = string.Empty;
            result    = false;
        }
        return(result);
    }
コード例 #59
0
        public static void Main(string[] args)
        {
            //byte[] key = { 0x01, 0x23, 0x45, 0x67, 0x89, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xAB, 0xCD, 0xEF, 0x01, 0xCD, 0xEF };
            //byte[] IV = { 0x67, 0x89, 0xAB, 0xAB, 0xCD, 0x01, 0x23, 0x45, 0x67, 0x89, 0x23, 0x45, 0xEF, 0x01, 0xCD, 0xEF };

            if (args.Length != 2)
            {
                Console.WriteLine("usage: dotnet Encrypt <<file name>> <<password>>");
            }

            byte[] IV   = new byte[16];
            byte[] salt = new byte[16];
            RandomNumberGenerator rng = RandomNumberGenerator.Create();

            rng.GetBytes(IV);
            rng.GetBytes(salt);
            string             password = "******";
            Rfc2898DeriveBytes hasher   = new Rfc2898DeriveBytes(password, salt);

            byte[] key = hasher.GetBytes(16);

            using (FileStream inputStream = File.OpenRead(@"Encryptor.cs"))
                using (StreamReader reader = new StreamReader(inputStream))
                {
                    using (Aes algorithm = Aes.Create())
                        using (FileStream outputStream = File.Create(@"..\Encryptor.bin"))
                            using (CryptoStream encryptedStream = new CryptoStream(
                                       outputStream,
                                       algorithm.CreateEncryptor(key, IV),
                                       CryptoStreamMode.Write))
                                using (StreamWriter writer = new StreamWriter(encryptedStream))
                                {
                                    writer.Write(reader.ReadToEnd());
                                }
                }
            Console.WriteLine("You have been encrypted.");
        }
コード例 #60
-1
ファイル: EncryptDecrypt.cs プロジェクト: swapneshpal/HRIMS
        public static string Decrypt(string cipherText)
        {

            try
            {
                string EncryptionKey = "MAKV2SPBNI99212";
                cipherText = cipherText.Replace(" ", "+");
                byte[] cipherBytes = Convert.FromBase64String(cipherText);
                using (Aes encryptor = Aes.Create())
                {
                    Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                    encryptor.Key = pdb.GetBytes(32);
                    encryptor.IV = pdb.GetBytes(16);
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                        {
                            cs.Write(cipherBytes, 0, cipherBytes.Length);
                            cs.Close();
                        }
                        cipherText = Encoding.Unicode.GetString(ms.ToArray());
                    }
                }
                return cipherText;
            }
            catch (Exception ex)
            {

                return "0";
            }
        }