public static string EncryptPassword(string _password)
        {
            Chilkat.Crypt2 _encrypt = new Chilkat.Crypt2();
            bool isUnlocked = _encrypt.UnlockComponent("SCOTTGCrypt_FdXsYk2WWPjN");
            string password;
            password = "******";

            _encrypt.CryptAlgorithm = "aes";
            _encrypt.CipherMode = "cbc";
            _encrypt.KeyLength = 128;

            //  Generate a binary secret key from a password string
            //  of any length.  For 128-bit encryption, GenEncodedSecretKey
            //  generates the MD5 hash of the password and returns it
            //  in the encoded form requested.  The 2nd param can be
            //  "hex", "base64", "url", "quoted-printable", etc.
            string hexKey;
            hexKey = _encrypt.GenEncodedSecretKey(password, "hex");
            _encrypt.SetEncodedKey(hexKey, "hex");

            _encrypt.EncodingMode = "base64";

            //  Encrypt a string and return the binary encrypted data
            //  in a base-64 encoded string.
            string s1 = _encrypt.DecryptStringENC(_password);
            return _encrypt.EncryptStringENC(_password);
        }
        /// <summary>
        /// verifica la firma ed estrae il file originale
        /// </summary>
        /// <param name="pathFileSign">documento firmato</param>
        /// <param name="pathFile">path e nome file</param>
        /// <param name="lastError">ultimo errore nella funzionalità</param>
        /// <returns>verifica e estrazione avvenuta con successo</returns>
        /// <example>
        /// string pathFileOut = "c:\file\test.xml"
        /// Utilities.VerificaEstraiFirma(@"c:\temp\IT01234567890_FPA01.xml.p7m", pathFileOut, ref lastError))
        ///
        /// c:\file\test.xml file estratto
        ///
        /// </example>
        public static bool VerificaEstraiFirma(string pathFileSign, string pathFile, ref string lastError)
        {
            bool success = false;

            try
            {
                if (Utilities.glob.UnlockStatus == 0)
                {
                    lastError = "Licenza bloccata";
                    return(success);
                }

                Chilkat.Crypt2 crypt = new Chilkat.Crypt2();

                //  Verify and restore the original file:
                success = crypt.VerifyP7M(pathFileSign, pathFile);

                if (!success)
                {
                    lastError = crypt.LastErrorText;
                    return(success);
                }

                success = true;
            }
            catch
            {
                throw;
            }

            return(success);
        }
Ejemplo n.º 3
0
        private void button2_Click(object sender, EventArgs e)
        {
            string ivHex = textBox2.Text;

            // The secret key must equal the size of the key.  For
            // 256-bit encryption, the binary secret key is 32 bytes.
            // For 128-bit encryption, the binary secret key is 16 bytes.
            string keyHex = textBox1.Text;

            // Encrypt a string...
            // The input string is 44 ANSI characters (i.e. 44 bytes), so
            // the output should be 48 bytes (a multiple of 16).
            // Because the output is a hex string, it should
            // be 96 characters long (2 chars per byte).

            Chilkat.Crypt2 decrypt = new Chilkat.Crypt2();

            decrypt.CryptAlgorithm = "aes";
            decrypt.CipherMode     = "ctr";
            decrypt.KeyLength      = 256;
            decrypt.EncodingMode   = "base64";
            decrypt.SetEncodedIV(ivHex, "ascii");
            decrypt.SetEncodedKey(keyHex, "ascii");

            // Now decrypt:
            string decStr = decrypt.DecryptStringENC(richTextBox1.Text);

            richTextBox2.Text = decStr;
        }
Ejemplo n.º 4
0
        private void loginWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Chilkat.Crypt2 crypt = new Chilkat.Crypt2();
            crypt.UnlockComponent("Crypt!TEAM!BEAN_34F4144DpR6G");
            crypt.CryptAlgorithm = "aes";
            crypt.CipherMode = "cbc";
            crypt.KeyLength = 128;
            crypt.SecretKey = crypt.GenerateSecretKey(txtUser.Text);
            crypt.EncodingMode = "base64";

            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            if (frmStatusBar != null)
            {
                frmStatusBar.Close();
            }

            if (Kalibrasi.global_variable.global.gcPASSWORD == crypt.EncryptStringENC(txtPassword.Text))
            {
                this.Close();
            }
            else
            {
                Kalibrasi.global_variable.global.gcUSERID = lcUserId;
            }
        }
Ejemplo n.º 5
0
        public string algoritmoHash(byte[] pArchivo, string algorithm)
        {
            Chilkat.Crypt2 crypt  = new Chilkat.Crypt2();
            bool           succes = crypt.UnlockComponent("Anything for 30-day trial");

            if (succes != true)
            {
                Console.WriteLine(crypt.LastErrorText);
                return("");
            }
            //  Set the name of the hash algorithm.
            //  Other choices include "sha1", "sha256", "sha384", "sha512", "md2", "md5", and "haval".
            crypt.HashAlgorithm = algorithm;

            //  EncodingMode specifies the encoding of the hash output.
            //  It may be "hex", "url", "base64", or "quoted-printable".
            crypt.EncodingMode = "hex";

            //  Files of any type may be hashed -- it doesn't matter
            //  if the file is binary or text...
            string hashStr;

            hashStr = crypt.HashBytesENC(pArchivo);
            if (crypt.LastMethodSuccess != true)
            {
                Console.WriteLine(crypt.LastErrorText);
                return("");
            }

            Console.WriteLine(hashStr);
            return(hashStr);
        }
Ejemplo n.º 6
0
        public static void performPoly1305MAC(string text)
        {
            Chilkat.Crypt2 crypt = new Chilkat.Crypt2();

            bool success = crypt.UnlockComponent("Anything for 30-day trial");

            if (success != true)
            {
                Console.WriteLine(crypt.LastErrorText);
                return;
            }

            //  Set the MAC algorithm to poly1305
            crypt.MacAlgorithm = "poly1305";

            //  EncodingMode specifies the encoding of the output for
            //  encryption, and the input for decryption.
            //  Valid modes are (case insensitive) "Base64", "modBase64", "Base32", "Base58", "UU",
            //  "QP" (for quoted-printable), "URL" (for url-encoding), "Hex",
            //  "Q", "B", "url_oauth", "url_rfc1738", "url_rfc2396", and "url_rfc3986".
            crypt.EncodingMode = "hex";

            //  Poly1305 always uses a 32-byte (256-bit) MAC key.
            string keyHex = "1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0";

            success = crypt.SetMacKeyEncoded(keyHex, "hex");

            string plainText = "'Twas brillig, and the slithy toves\nDid gyre and gimble in the wabe:\nAll mimsy were the borogoves,\nAnd the mome raths outgrabe.";

            //  The computed tag should match the Tag shown below.
            //  (Note: hexidecimal encoding is case insensitive.)
            string encTag = crypt.MacStringENC(text);
            //Console.WriteLine(encTag);
        }
Ejemplo n.º 7
0
        public static void perform3DES(string text)
        {
            Chilkat.Crypt2 crypt = new Chilkat.Crypt2();

            bool success = crypt.UnlockComponent("Anything for 30-day trial");

            if (success != true)
            {
                Console.WriteLine(crypt.LastErrorText);
                return;
            }

            //  Specify 3DES for the encryption algorithm:
            crypt.CryptAlgorithm = "3des";

            //  CipherMode may be "ecb" or "cbc"
            crypt.CipherMode = "cbc";

            //  KeyLength must be 192.  3DES is technically 168-bits;
            //  the most-significant bit of each key byte is a parity bit,
            //  so we must indicate a KeyLength of 192, which includes
            //  the parity bits.
            crypt.KeyLength = 192;

            //  The padding scheme determines the contents of the bytes
            //  that are added to pad the result to a multiple of the
            //  encryption algorithm's block size.  3DES has a block
            //  size of 8 bytes, so encrypted output is always
            //  a multiple of 8.
            crypt.PaddingScheme = 0;

            //  EncodingMode specifies the encoding of the output for
            //  encryption, and the input for decryption.
            //  It may be "hex", "url", "base64", or "quoted-printable".
            crypt.EncodingMode = "hex";

            //  An initialization vector is required if using CBC or CFB modes.
            //  ECB mode does not use an IV.
            //  The length of the IV is equal to the algorithm's block size.
            //  It is NOT equal to the length of the key.
            string ivHex = "0001020304050607";

            crypt.SetEncodedIV(ivHex, "hex");

            //  The secret key must equal the size of the key.  For
            //  3DES, the key must be 24 bytes (i.e. 192-bits).
            string keyHex = "000102030405060708090A0B0C0D0E0F0001020304050607";

            crypt.SetEncodedKey(keyHex, "hex");


            string encStr = crypt.EncryptStringENC(text);
            //Console.WriteLine(encStr);

            //  Now decrypt:
            string decStr = crypt.DecryptStringENC(encStr);
            // Console.WriteLine(decStr);
        }
Ejemplo n.º 8
0
        public static void performChaChaEncryption(string text)
        {
            Chilkat.Crypt2 crypt = new Chilkat.Crypt2();
            //  Set the encryption algorithm to chacha20
            //  chacha20 is a stream cipher, and therefore no cipher mode applies.

            //  Set the encryption algorithm to chacha20
            //  chacha20 is a stream cipher, and therefore no cipher mode applies.
            crypt.CryptAlgorithm = "chacha20";

            //  The key length for chacha20 is always 256-bits.
            crypt.KeyLength = 256;

            //  Note: "padding" only applies to block encryption algorithmns.
            //  Since chacha20 is a stream cipher, there is no padding and the output
            //  number of bytes is exactly equal to the input.

            //  EncodingMode specifies the encoding of the output for
            //  encryption, and the input for decryption.
            //  Valid modes are (case insensitive) "Base64", "modBase64", "Base32", "Base58", "UU",
            //  "QP" (for quoted-printable), "URL" (for url-encoding), "Hex",
            //  "Q", "B", "url_oauth", "url_rfc1738", "url_rfc2396", and "url_rfc3986".
            crypt.EncodingMode = "hex";

            //  The inputs to ChaCha20 encryption, specified by RFC 7539, are:
            //  1) A 256-bit secret key.
            //  2) A 96-bit nonce.
            //  3) A 32-bit initial count.
            //  The IV property is used to specify the chacha20 nonce.
            //  For a 96-bit nonce, the IV should be 12 bytes in length.
            //
            //  Note: Some implementations of chacha20, such as that used internally by SSH,
            //  use a 64-bit nonce and 64-bit count.  To do chacha20 encryption in this way,
            //  simply provide 8 bytes for the IV instead of 12 bytes.  Chilkat will then automatically
            //  use 8 bytes (64-bits) for the count.

            //  This example duplicates Test Vector #3 (for ChaCha20 encryption) from RFC 7539.
            string ivHex = "000000000000000000000002";

            crypt.SetEncodedIV(ivHex, "hex");

            crypt.InitialCount = 42;

            string keyHex = "1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0";

            crypt.SetEncodedKey(keyHex, "hex");

            // string plainText = "'Twas brillig, and the slithy toves\nDid gyre and gimble in the wabe:\nAll mimsy were the borogoves,\nAnd the mome raths outgrabe.";


            string encStr = crypt.EncryptStringENC(text);
            //Console.WriteLine(encStr);
            //Console.WriteLine("I am wor");

            //  Now decrypt:
            string decStr = crypt.DecryptStringENC(encStr);
            //Console.WriteLine(decStr);
        }
Ejemplo n.º 9
0
        public string HashContent(string content)
        {
            var crypt = new Chilkat.Crypt2 {
                HashAlgorithm = "sha256"
            };
            var hash = crypt.HashStringENC(content);

            return(hash);
        }
Ejemplo n.º 10
0
        public string HashContent <T>(T content)
        {
            var crypt = new Chilkat.Crypt2 {
                HashAlgorithm = "sha256"
            };
            var serializedContent = JsonConvert.SerializeObject(content);

            var hash = crypt.HashStringENC(serializedContent);

            return(hash);
        }
Ejemplo n.º 11
0
        public static void performBlowfish2(string text)
        {
            Chilkat.Crypt2 crypt = new Chilkat.Crypt2();

            //  Attention: use "blowfish2" for the algorithm name:
            crypt.CryptAlgorithm = "blowfish2";

            //  CipherMode may be "ecb", "cbc", or "cfb"
            crypt.CipherMode = "cbc";

            //  KeyLength (in bits) may be a number between 32 and 448.
            //  128-bits is usually sufficient.  The KeyLength must be a
            //  multiple of 8.
            crypt.KeyLength = 128;

            //  The padding scheme determines the contents of the bytes
            //  that are added to pad the result to a multiple of the
            //  encryption algorithm's block size.  Blowfish has a block
            //  size of 8 bytes, so encrypted output is always
            //  a multiple of 8.
            crypt.PaddingScheme = 0;

            //  EncodingMode specifies the encoding of the output for
            //  encryption, and the input for decryption.
            //  It may be "hex", "url", "base64", or "quoted-printable".
            crypt.EncodingMode = "hex";

            //  An initialization vector is required if using CBC or CFB modes.
            //  ECB mode does not use an IV.
            //  The length of the IV is equal to the algorithm's block size.
            //  It is NOT equal to the length of the key.
            string ivHex = "0001020304050607";

            crypt.SetEncodedIV(ivHex, "hex");

            //  The secret key must equal the size of the key.  For
            //  256-bit encryption, the binary secret key is 32 bytes.
            //  For 128-bit encryption, the binary secret key is 16 bytes.
            string keyHex = "000102030405060708090A0B0C0D0E0F";

            crypt.SetEncodedKey(keyHex, "hex");

            //  Encrypt a string...
            //  The input string is 44 ANSI characters (i.e. 44 bytes), so
            //  the output should be 48 bytes (a multiple of 8).
            //  Because the output is a hex string, it should
            //  be 96 characters long (2 chars per byte).
            string encStr = crypt.EncryptStringENC(text);
            //Console.WriteLine(encStr);

            //  Now decrypt:
            string decStr = crypt.DecryptStringENC(encStr);
            //Console.WriteLine(decStr);
        }
Ejemplo n.º 12
0
        public static void performTwoFish(string text)
        {
            Chilkat.Crypt2 crypt = new Chilkat.Crypt2();

            //  Set the encryption algorithm = "twofish"
            crypt.CryptAlgorithm = "twofish";

            //  CipherMode may be "ecb" or "cbc"
            crypt.CipherMode = "cbc";

            //  KeyLength may be 128, 192, 256
            crypt.KeyLength = 256;

            //  The padding scheme determines the contents of the bytes
            //  that are added to pad the result to a multiple of the
            //  encryption algorithm's block size.  Twofish has a block
            //  size of 16 bytes, so encrypted output is always
            //  a multiple of 16.
            crypt.PaddingScheme = 0;

            //  EncodingMode specifies the encoding of the output for
            //  encryption, and the input for decryption.
            //  It may be "hex", "url", "base64", or "quoted-printable".
            crypt.EncodingMode = "hex";

            //  An initialization vector is required if using CBC mode.
            //  ECB mode does not use an IV.
            //  The length of the IV is equal to the algorithm's block size.
            //  It is NOT equal to the length of the key.
            string ivHex = "000102030405060708090A0B0C0D0E0F";

            crypt.SetEncodedIV(ivHex, "hex");

            //  The secret key must equal the size of the key.  For
            //  256-bit encryption, the binary secret key is 32 bytes.
            //  For 128-bit encryption, the binary secret key is 16 bytes.
            string keyHex = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F";

            crypt.SetEncodedKey(keyHex, "hex");

            //  Encrypt a string...
            //  The input string is 44 ANSI characters (i.e. 44 bytes), so
            //  the output should be 48 bytes (a multiple of 16).
            //  Because the output is a hex string, it should
            //  be 96 characters long (2 chars per byte).
            string encStr = crypt.EncryptStringENC(text);
            //  Console.WriteLine(encStr);

            //  Now decrypt:
            string decStr = crypt.DecryptStringENC(encStr);
            //  Console.WriteLine(decStr);
        }
Ejemplo n.º 13
0
        private Chilkat.Crypt2 m_encoder = null;        // We'll use this for encoding/decoding

        public Form1()
        {
            InitializeComponent();

            Chilkat.Global glob = new Chilkat.Global();
            if (!glob.UnlockBundle("Anything for 30-day trial"))
            {
                MessageBox.Show("Failed to unlock Chilkat.");
            }

            m_prng    = new Chilkat.Prng();
            m_encoder = new Chilkat.Crypt2();
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 登录密码加密
        /// </summary>
        /// <param name="password">登录密码</param>
        /// <param name="encryptType">加密方式</param>
        /// <returns></returns>
        public static string GetPasswordMD5Value(string password, string encryptType = "")
        {
            Chilkat.Crypt2 crypt = new Chilkat.Crypt2();

            if (encryptType == "m")
            {
                crypt.HashAlgorithm = "md5";
                crypt.EncodingMode  = "base64";
                crypt.Charset       = "Unicode";
            }


            return(crypt.HashStringENC(str: password));
        }
Ejemplo n.º 15
0
        private void button1_Click(object sender, EventArgs e)
        {
            Chilkat.Crypt2 crypt = new Chilkat.Crypt2();

            // AES is also known as Rijndael.
            crypt.CryptAlgorithm = "aes";

            // CipherMode may be "ctr", "cfb", "ecb" or "cbc"
            crypt.CipherMode = "ctr";

            // KeyLength may be 128, 192, 256
            crypt.KeyLength = 256;

            // Counter mode emits the exact number of bytes input, and therefore
            // padding is not used.  The PaddingScheme property does not apply with CTR mode.

            // EncodingMode specifies the encoding of the output for
            // encryption, and the input for decryption.
            // It may be "hex", "url", "base64", "quoted-printable", or many other choices.
            crypt.EncodingMode = "base64";

            // An initialization vector (nonce) is required if using CTR mode.
            // The length of the IV is equal to the algorithm's block size.
            // It is NOT equal to the length of the key.
            string ivHex = textBox2.Text;

            crypt.SetEncodedIV(ivHex, "ascii");

            // The secret key must equal the size of the key.  For
            // 256-bit encryption, the binary secret key is 32 bytes.
            // For 128-bit encryption, the binary secret key is 16 bytes.
            string keyHex = textBox1.Text;

            crypt.SetEncodedKey(keyHex, "ascii");

            // Encrypt a string...
            // The input string is 44 ANSI characters (i.e. 44 bytes), so
            // the output should be 48 bytes (a multiple of 16).
            // Because the output is a hex string, it should
            // be 96 characters long (2 chars per byte).
            string encStr = crypt.EncryptStringENC(richTextBox2.Text);

            //Debug.WriteLine(encStr);



            richTextBox1.Text = encStr;
        }
Ejemplo n.º 16
0
        private void cmdOK_Click(object sender, EventArgs e)
        {
            Chilkat.Crypt2 crypt = new Chilkat.Crypt2();
            crypt.UnlockComponent("Crypt!TEAM!BEAN_34F4144DpR6G");
            crypt.CryptAlgorithm = "aes";
            crypt.CipherMode = "cbc";
            crypt.KeyLength = 128;
            crypt.SecretKey = crypt.GenerateSecretKey(txtUser.Text);
            crypt.EncodingMode = "base64";
            lcUserId = Kalibrasi.global_variable.global.gcUSERID;
            Kalibrasi.global_variable.global.gcUSERID = txtUser.Text;

            frmStatusBar = new frmStatusBar();
            frmStatusBar.Show();
            frmStatusBar.CancelButtonClicked += new CancelButtonEventHandler(frmStatusBar_CancelButtonClicked);
            loginWorker.RunWorkerAsync();
        }
Ejemplo n.º 17
0
        public static void performARC4(string text)
        {
            Chilkat.Crypt2 crypt = new Chilkat.Crypt2();

            //  Set the encryption algorithm = "arc4"
            crypt.CryptAlgorithm = "arc4";

            //  KeyLength may range from 1 byte to 256 bytes.
            //  (i.e. 8 bits to 2048 bits)
            //  ARC4 key sizes are typically in the range of
            //  40 to 128 bits.
            //  The KeyLength property is specified in bits:
            crypt.KeyLength = 128;

            //  Note: The PaddingScheme and CipherMode properties
            //  do not apply w/ ARC4.  ARC4 does not encrypt in blocks --
            //  it is a streaming encryption algorithm. The number of output bytes
            //  is exactly equal to the number of input bytes.

            //  EncodingMode specifies the encoding of the output for
            //  encryption, and the input for decryption.
            //  It may be "hex", "url", "base64", or "quoted-printable".
            crypt.EncodingMode = "hex";

            //  Note: ARC4 does not utilize initialization vectors.  IV's only
            //  apply to block encryption algorithms.

            //  The secret key must equal the size of the key.
            //  For 128-bit encryption, the binary secret key is 16 bytes.
            string keyHex = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F";

            crypt.SetEncodedKey(keyHex, "hex");

            //  Encrypt a string...
            //  The output length is exactly equal to the input.  In this
            //  example, the input string is 44 chars (ANSI bytes) so the
            //  output is 44 bytes -- and when hex encoded results in an
            //  88-char string (2 chars per byte for the hex encoding).
            string encStr = crypt.EncryptStringENC(text);
            //Console.WriteLine(encStr);

            //  Now decrypt:
            string decStr = crypt.DecryptStringENC(encStr);
            //Console.WriteLine(decStr);
        }
Ejemplo n.º 18
0
        public string Operation(CryptoRequest req, bool isDecryption)
        {
            Chilkat.Crypt2 crypt = new Chilkat.Crypt2
            {
                CryptAlgorithm = "aes",
                CipherMode     = "cbc",
                KeyLength      = 256,
                PaddingScheme  = 0,
                EncodingMode   = "hex"
            };

            var data = Convert.FromBase64String(req.Data64);

            crypt.SetSecretKeyViaPassword(req.Password);

            var operated = isDecryption ? crypt.DecryptBytes(data) : crypt.EncryptBytes(data);

            return(Convert.ToBase64String(operated));
        }
        /// <summary>
        /// verifica la firma
        /// </summary>
        /// <param name="pathFileSign">documento firmato</param>
        /// <param name="lastError">ultimo errore nella funzionalità</param>
        /// <returns>se true la verifica è avvenuta con successo</returns>
        public static bool VerificaFirma(string pathFileSign, ref string lastError)
        {
            bool success = false;

            try
            {
                if (Utilities.glob.UnlockStatus == 0)
                {
                    lastError = "Licenza bloccata";
                    return(success);
                }

                Chilkat.BinData bd = new Chilkat.BinData();

                success = bd.LoadFile(pathFileSign);
                if (!success)
                {
                    lastError = "Errore a caricare il file";
                    return(success);
                }

                Chilkat.Crypt2 crypt = new Chilkat.Crypt2();

                // Verifica ed estrae il payload contenuto nel .p7m.
                success = crypt.OpaqueVerifyBd(bd);

                if (!success)
                {
                    lastError = crypt.LastErrorText;
                    return(success);
                }

                success = true;
            }
            catch
            {
                throw;
            }

            return(success);
        }
Ejemplo n.º 20
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            Chilkat.Crypt2 crypt = new Chilkat.Crypt2();

            if (!checkUnlocked())
            {
                return;
            }

            crypt.CryptAlgorithm = "chacha20";

            //  The key length for chacha20 is always 256-bits.
            crypt.KeyLength    = 256;
            crypt.EncodingMode = "hex";

            string ivHex = "000000000000000000000002";

            crypt.SetEncodedIV(ivHex, "hex");

            crypt.InitialCount = 42;

            string keyHex = "1c9240a5eb55d38af333888604f6b5f0473917c1402b80099dca5cbc207075c0";

            crypt.SetEncodedKey(keyHex, "hex");

            string plainText = textBox.Text;

            string encStr = crypt.EncryptStringENC(plainText);

            Debug.WriteLine(encStr);
            textBox1.Text = encStr;

            //  Now decrypt:
            string decStr = crypt.DecryptStringENC(encStr);

            Debug.WriteLine(decStr);
        }
        /// <summary>
        /// calcolo hash di un file
        /// </summary>
        /// <param name="pathFile">path and file</param>
        /// <param name="lastError">ultimo errore nella funzionalità</param>
        /// <param name="algorithm">algoritmo da utilizzare</param>
        /// <param name="encode">encode</param>
        /// <returns>hash del file</returns>
        public static string HashFile(string pathFile, ref string lastError, string algorithm = "sha256", string encode = "base64")
        {
            string hash = null;

            try
            {
                if (Utilities.glob.UnlockStatus == 0)
                {
                    lastError = "Licenza bloccata";
                    return(hash);
                }

                Chilkat.Crypt2 crypt = new Chilkat.Crypt2();
                crypt.HashAlgorithm = algorithm;
                crypt.EncodingMode  = encode;
                hash = crypt.HashFileENC(pathFile);
            }
            catch
            {
                throw;
            }

            return(hash);
        }
        /// <summary>
        /// applica la marca temporale al file
        /// </summary>
        /// <param name="pathFileSign">file firmato</param>
        /// <param name="tsaUrl">url TSA</param>
        /// <param name="pathFileTimeStamped">file tsr da TSA</param>
        /// <param name="lastError">ultimo errore nella funzionalità</param>
        /// <param name="userName">user TSA (opzionale)</param>
        /// <param name="password">password TSA (opzionale)</param>
        /// <returns>true se la funzionalità ha avuto successo</returns>
        /// <example>
        ///  if (Utilities.MarcaTemporale(@"c:\temp\IT01234567890_FPA01.xml.p7m", "https://freetsa.org/tsr", out pathFileTimeStamped, ref lastError, "myUser", "myPassword"))
        ///  {
        ///       pathFileTimeStamped -> c:\temp\IT01234567890_FPA01.xml.p7m.tsr
        ///  }
        /// </example>
        public static bool MarcaTemporale(string pathFileSign, string tsaUrl, out string pathFileTimeStamped, ref string lastError, string userName = null, string password = null)
        {
            bool success = false;

            pathFileTimeStamped = null;
            try
            {
                string fileName = Path.GetFileName(pathFileSign);



                if (Utilities.glob.UnlockStatus == 0)
                {
                    lastError = "Licenza bloccata";
                    return(success);
                }

                Chilkat.Crypt2 crypt = new Chilkat.Crypt2();
                crypt.HashAlgorithm = "sha256";
                crypt.EncodingMode  = "base64";

                string base64Hash = crypt.HashFileENC(pathFileSign);

                Chilkat.Http http = new Chilkat.Http();

                Chilkat.BinData requestToken      = new Chilkat.BinData();
                string          optionalPolicyOid = string.Empty;
                bool            addNonce          = false;
                bool            requestTsaCert    = false;

                if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
                {
                    http.Login     = userName;
                    http.Password  = password;
                    http.BasicAuth = true;
                }

                //  Create a time-stamp request token
                success = http.CreateTimestampRequest("sha256", base64Hash, optionalPolicyOid, addNonce, requestTsaCert, requestToken);
                if (!success)
                {
                    lastError = http.LastErrorText;
                    return(success);
                }


                Chilkat.HttpResponse resp = http.PBinaryBd("POST", tsaUrl, requestToken, "application/timestamp-query", false, false);
                if (!http.LastMethodSuccess)
                {
                    lastError = http.LastErrorText;
                    return(success);
                }


                Chilkat.BinData timestampReply = new Chilkat.BinData();
                resp.GetBodyBd(timestampReply);
                if (!timestampReply.LastMethodSuccess)
                {
                    return(success);
                }


                string s = Path.ChangeExtension(fileName, $".{Enum.GetName(typeof(EstensioniFile), EstensioniFile.tsr)}");
                success = timestampReply.WriteFile(s);
                if (success)
                {
                    pathFileTimeStamped = s;
                }
            }
            catch
            {
                throw;
            }

            return(success);
        }
        /// <summary>
        /// Firma del file
        /// </summary>
        /// <param name="SubjectCN">Subject Common Name</param>
        /// <param name="pathFile">file da firmare</param>
        /// <param name="lastError">ultimo errore nella funzionalità</param>
        /// <param name="pin">pin smartcard/usb (opzionale). Se non fornito comparirà una finestra di dialogo del sistema operativo Windows per indicare il pin</param>
        /// <param name="csp">provider csp (opzionale). Se non indicato verrà selezionato automaticamente. Utilizzare questo parametro per indicarne uno specifico. Utilizzare il metodo CSPs per visualizza i csp presenti nel sistema</param>
        /// <returns>firma avvenuta con successo</returns>
        public static bool Firma(string SubjectCN, string pathFile, ref string lastError, string pin = null, string csp = null)
        {
            bool success = false;

            try
            {
                if (Utilities.glob.UnlockStatus == 0)
                {
                    lastError = "Licenza bloccata";
                    return(success);
                }

                Chilkat.Crypt2 crypt = new Chilkat.Crypt2();

                //  Utilizza il certificato su una smartcard o su USB.
                Chilkat.Cert cert = new Chilkat.Cert();

                // cryptographic service provider
                if (!string.IsNullOrWhiteSpace(csp))
                {
                    success = cert.LoadFromSmartcard(csp);
                    if (success != true)
                    {
                        lastError = cert.LastErrorText;
                        return(success);
                    }
                }

                //  Passa il Subject CN del certificato al metodo LoadByCommonName.
                success = cert.LoadByCommonName(SubjectCN);
                if (success != true)
                {
                    lastError = cert.LastErrorText;
                    return(success);
                }

                //  Fornire il PIN della smartcard.
                //  Se il pin non è fornito esplicitamente qui,
                //  Se non fornito dovrebbe comparire una finestra di dialogo del sistema operativo Windows per indicare il pin
                if (!string.IsNullOrWhiteSpace(pin))
                {
                    cert.SmartCardPin = pin;
                }

                //  Fornisce il certificato per firmarlo
                success = crypt.SetSigningCert(cert);
                if (success != true)
                {
                    lastError = crypt.LastErrorText;
                    return(success);
                }

                //  Indica l'algoritmo da utilizzare
                crypt.HashAlgorithm = "sha256";

                //  Specifico gli attributi firmati per essere inclusi.
                //  (Questo è quello che fa un CAdES-BES compliant.)
                Chilkat.JsonObject jsonSignedAttrs = new Chilkat.JsonObject();
                jsonSignedAttrs.UpdateInt("contentType", 1);
                jsonSignedAttrs.UpdateInt("signingTime", 1);
                jsonSignedAttrs.UpdateInt("messageDigest", 1);
                jsonSignedAttrs.UpdateInt("signingCertificateV2", 1);
                crypt.SigningAttributes = jsonSignedAttrs.Emit();


                string sigFile = $"{pathFile}.{Enum.GetName(typeof(EstensioniFile), EstensioniFile.p7m)}";

                //  Creo una firma CAdES-BES, che contiene i dati originali
                success = crypt.CreateP7M(pathFile, sigFile);
                if (!success)
                {
                    lastError = crypt.LastErrorText;
                    return(success);
                }

                success = true;
            }
            catch
            {
                throw;
            }

            return(success);
        }
Ejemplo n.º 24
0
        public static void performDeffieHelman(string text)
        {
            //  Create two separate instances of the DH object.
            Chilkat.Dh dhBob   = new Chilkat.Dh();
            Chilkat.Dh dhAlice = new Chilkat.Dh();

            //  The DH algorithm begins with a large prime, P, and a generator, G.
            //  These don't have to be secret, and they may be transmitted over an insecure channel.
            //  The generator is a small integer and typically has the value 2 or 5.

            //  The Chilkat DH component provides the ability to use known
            //  "safe" primes, as well as a method to generate new safe primes.

            //  This example will use a known safe prime.  Generating
            //  new safe primes is a time-consuming CPU intensive task
            //  and is normally done offline.

            //  Bob will choose to use the 2nd of our 8 pre-chosen safe primes.
            //  It is the Prime for the 2nd Oakley Group (RFC 2409) --
            //  1024-bit MODP Group.  Generator is 2.
            //  The prime is: 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }
            dhBob.UseKnownPrime(2);

            //  The computed shared secret will be equal to the size of the prime (in bits).
            //  In this case the prime is 1024 bits, so the shared secret will be 128 bytes (128 * 8 = 1024).
            //  However, the result is returned as an SSH1-encoded bignum in hex string format.
            //  The SSH1-encoding prepends a 2-byte count, so the result is going  to be 2 bytes
            //  longer: 130 bytes.  This results in a hex string that is 260 characters long (two chars
            //  per byte for the hex encoding).

            string p;
            int    g;

            //  Bob will now send P and G to Alice.
            p = dhBob.P;
            g = dhBob.G;

            //  Alice calls SetPG to set P and G.  SetPG checks
            //  the values to make sure it's a safe prime and will
            //  return false if not.


            //  Each side begins by generating an "E"
            //  value.  The CreateE method has one argument: numBits.
            //  It should be set to twice the size of the number of bits
            //  in the session key.

            //  Let's say we want to generate a 128-bit session key
            //  for AES encryption.  The shared secret generated by the Diffie-Hellman
            //  algorithm will be longer, so we'll hash the result to arrive at the
            //  desired session key length.  However, the length of the session
            //  key we'll utlimately produce determines the value that should be
            //  passed to the CreateE method.

            //  In this case, we'll be creating a 128-bit session key, so pass 256 to CreateE.
            //  This setting is for security purposes only -- the value
            //  passed to CreateE does not change the length of the shared secret
            //  that is produced by Diffie-Hellman.
            //  Also, there is no need to pass in a value larger
            //  than 2 times the expected session key length.  It suffices to
            //  pass exactly 2 times the session key length.

            //  Bob generates a random E (which has the mathematical
            //  properties required for DH).
            string eBob;

            eBob = dhBob.CreateE(256);

            //  Alice does the same:
            string eAlice;

            eAlice = dhAlice.CreateE(256);

            //  The "E" values are sent over the insecure channel.
            //  Bob sends his "E" to Alice, and Alice sends her "E" to Bob.

            //  Each side computes the shared secret by calling FindK.
            //  "K" is the shared-secret.

            string kBob;
            string kAlice;

            //  Bob computes the shared secret from Alice's "E":
            kBob = dhBob.FindK(eAlice);

            //  Alice computes the shared secret from Bob's "E":
            kAlice = dhAlice.FindK(eBob);

            //  Amazingly, kBob and kAlice are identical and the expected
            //  length (260 characters).  The strings contain the hex encoded bytes of
            //  our shared secret:
            // Console.WriteLine("Bob's shared secret:");
            // Console.WriteLine(kBob);
            // Console.WriteLine("Alice's shared secret (should be equal to Bob's)");
            // Console.WriteLine(kAlice);

            //  To arrive at a 128-bit session key for AES encryption, Bob and Alice should
            //  both transform the raw shared secret using a hash algorithm that produces
            //  the size of session key desired.   MD5 produces a 16-byte (128-bit) result, so
            //  this is a good choice for 128-bit AES.

            //  Here's how you would use Chilkat Crypt (a separate Chilkat component) to
            //  produce the session key:
            Chilkat.Crypt2 crypt = new Chilkat.Crypt2();


            crypt.EncodingMode  = "hex";
            crypt.HashAlgorithm = "md5";

            string sessionKey;

            sessionKey = crypt.HashStringENC(kBob);

            // Console.WriteLine("128-bit Session Key:");
            // Console.WriteLine(sessionKey);

            //  Encrypt something...
            crypt.CryptAlgorithm = "aes";
            crypt.KeyLength      = 128;
            crypt.CipherMode     = "cbc";

            //  Use an IV that is the MD5 hash of the session key...
            string iv;

            iv = crypt.HashStringENC(sessionKey);

            //  AES uses a 16-byte IV:
            //Console.WriteLine("Initialization Vector:");
            //Console.WriteLine(iv);

            crypt.SetEncodedKey(sessionKey, "hex");
            crypt.SetEncodedIV(iv, "hex");

            //  Encrypt some text:
            string cipherText64;

            crypt.EncodingMode = "base64";
            cipherText64       = crypt.EncryptStringENC(text);
            //Console.WriteLine(cipherText64);

            string plainText;

            plainText = crypt.DecryptStringENC(cipherText64);

            //Console.WriteLine(plainText);
        }
        private void EncDecButton_Click(object sender, EventArgs e)
        {
            try{
                if (StringTextEditor.Text != "" && SecretKeyTextBox.Text != "")
                {
                    Chilkat.Crypt2 crypt = new Chilkat.Crypt2();



                    // AES
                    crypt.CryptAlgorithm = "aes";

                    // CipherMode may be "ecb", "cbc", "ofb", "cfb", "gcm", etc.
                    // Note: Check the online reference documentation to see the Chilkat versions
                    // when certain cipher modes were introduced.
                    crypt.CipherMode = cipherModeMenu.Text;

                    // KeyLength may be 128, 192, 256
                    crypt.KeyLength = Convert.ToInt32(keyLengthDropDownList.Text);

                    // The padding scheme determines the contents of the bytes
                    // that are added to pad the result to a multiple of the
                    // encryption algorithm's block size.  AES has a block
                    // size of 16 bytes, so encrypted output is always
                    // a multiple of 16.
                    crypt.PaddingScheme = 0;

                    // EncodingMode specifies the encoding of the output for
                    // encryption, and the input for decryption.
                    // It may be "hex", "url", "base64", or "quoted-printable".


                    crypt.EncodingMode = encodingModeDropDownList.Text;

                    // An initialization vector is required if using CBC mode.
                    // ECB mode does not use an IV.
                    // The length of the IV is equal to the algorithm's block size.
                    // It is NOT equal to the length of the key.
                    string ivHex = "000102030405060708090A0B0C0D0E0F";
                    crypt.SetEncodedIV(ivHex, "hex");

                    string keyHex = crypt.HashStringENC(SecretKeyTextBox.Text);

                    // The secret key must equal the size of the key.  For
                    // 256-bit encryption, the binary secret key is 32 bytes.
                    // For 128-bit encryption, the binary secret key is 16 bytes.
//                    string keyHex = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F";
                    crypt.SetEncodedKey(keyHex, "hex");
                    crypt.Charset = "utf-8";
                    string encStr = "";
                    string decStr = "";

                    if (EncryptToggleSwitch.Value == true)
                    {
                        // Encrypt
                        radProgressBar1.Value2 = 0;
                        encStr = crypt.EncryptStringENC(StringTextEditor.Text);
                        ResultTextEditor.Text  = encStr;
                        radProgressBar1.Value2 = 100;



                        this.radDesktopAlert1.CaptionText = "Abdal AES Encryption";
                        this.radDesktopAlert1.ContentText = "Encryption has been successful.";
                        this.radDesktopAlert1.Show();
                    }
                    else
                    {
                        // Now decrypt:
                        radProgressBar1.Value2 = 0;
                        decStr = crypt.DecryptStringENC(StringTextEditor.Text);
                        ResultTextEditor.Text             = decStr;
                        radProgressBar1.Value2            = 100;
                        this.radDesktopAlert1.CaptionText = "Abdal AES Encryption";
                        this.radDesktopAlert1.ContentText = "Decryption has been successful.";
                        this.radDesktopAlert1.Show();
                    }
                }
                else
                {
                    MessageBox.Show("The String and Secret Password fields must be filled");
                }
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }
        }
Ejemplo n.º 26
0
        public static void performAESGCM(string text)
        {
            Chilkat.Crypt2 crypt = new Chilkat.Crypt2();

            bool success = crypt.UnlockComponent("Anything for 30-day trial");

            if (success != true)
            {
                Console.WriteLine(crypt.LastErrorText);
                return;
            }

            //  Set the encryption algorithm to "AES"
            crypt.CryptAlgorithm = "aes";

            //  Indicate that the Galois/Counter Mode (GCM) should be used:
            crypt.CipherMode = "gcm";

            //  KeyLength may be 128, 192, 256
            crypt.KeyLength = 128;

            //  This is the 128-bit AES secret key (in hex format)
            string K = "feffe9928665731c6d6a8f9467308308";

            //  This is the 16-byte initialization vector:
            string IV = "cafebabefacedbaddecaf888";

            //  This is the additional data to be used as input to the GCM AEAD algorithm,
            //  but is not included in the output.  It plays a role in the computation of the
            //  resulting authenticated tag.
            string AAD = "feedfacedeadbeeffeedfacedeadbeefabaddad2";

            //  The plain-text bytes (in hex format) to be encrypted.
            string PT = "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39";

            PT = text;

            //  The expected cipher text (in hex format)
            string CT = "42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091";

            //  The expected authenticated tag given the above inputs.
            string T = "5bc94fbc3221a5db94fae95ae7121a47";

            //  Note: The above data are the values for test vector #4 from
            //  the PDF document at: http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-spec.pdf

            //  EncodingMode specifies the encoding of the output for
            //  encryption, and the input for decryption.
            //  It may be "hex", "url", "base64", or "quoted-printable".
            crypt.EncodingMode = "hex";

            //  Set the secret key and IV
            crypt.SetEncodedIV(IV, "hex");
            crypt.SetEncodedKey(K, "hex");

            //  Set the additional authenticated data (AAD)
            success = crypt.SetEncodedAad(AAD, "hex");

            //  For the purpose of duplicating the test vectors, we are using the EncryptEncoded method.
            //  This method decodes the input string according to the encoding specified by the EncodingMode
            //  property, which in this case is "hex".  The decoded bytes are encrypted using the mode specified
            //  by the CipherMode property.  The resulting
            //  encrypted bytes are encoded (again using the encoding mode specified by EncodingMode),
            //  and the result is returned.
            //  <b>Note:</b> The CipherMode property sets the block mode of operation (gcm, cfb, cbc, ofb, ecb, etc.)
            //  for any of the Chilkat encryption/decryption methods (such as EncryptBytes, EncryptString,
            //  CkEncryptFile, etc.)   Just because GCM mode is demonstrated with EncryptEncoded/DecryptEncoded,
            //  does not imply that GCM mode is specific to only these methods.
            string ctResult = crypt.EncryptEncoded(PT);

            if (crypt.LastMethodSuccess != true)
            {
                //   Console.WriteLine(crypt.LastErrorText);
                return;
            }

            //  Examine the result.  It should be the same (case insensitive) as our expected result:
            // Console.WriteLine("computed result: " + ctResult);
            // Console.WriteLine("expected result: " + CT);

            //  Examine the authenticated tag. It should be the same (case insensitive) as our expected authenticated tag:
            string tResult = crypt.GetEncodedAuthTag("hex");

            //Console.WriteLine("computed authTag: " + tResult);
            //Console.WriteLine("expected authTag: " + T);

            //  -------------------------------------------------------------------------------------
            //  Now let's GCM decrypt...
            //  -------------------------------------------------------------------------------------

            //  Before GCM decrypting, we must set the authenticated tag to the value that is expected.
            //  The decryption will fail if the resulting authenticated tag is not equal (case insensitive) to
            //  the expected result.
            //  Note: The return value of SetEncodedAuthTag indicates whether the string passed was a valid
            //  representation of the encoding specified in the 2nd arg.
            success = crypt.SetEncodedAuthTag(T, "hex");

            //  All of our properties (IV, secret key, cipher mode, and AAD) are already set from the code above...

            //  So let's decrypt CT to and check to see if we get PT.
            string ptResult = crypt.DecryptEncoded(CT);

            if (crypt.LastMethodSuccess != true)
            {
                //  Failed.  The resultant authenticated tag did not equal the expected authentication tag.
                // Console.WriteLine(crypt.LastErrorText);
                return;
            }

            //  Examine the decrypted result.  It should be the same as our expected plaintext (case insensitive)
            //Console.WriteLine("plaintext decrypted: " + ptResult);
            //Console.WriteLine("plaintext expected:  " + PT);

            //  Let's intentionally set the expected authenticated tag to an incorrect value.
            //  The decrypt operation should fail:
            string tInvalid = "ffaabbbc3221a5db94fae95ae7121a47";

            success = crypt.SetEncodedAuthTag(tInvalid, "hex");

            ptResult = crypt.DecryptEncoded(CT);
            if (crypt.LastMethodSuccess != true)
            {
                //  Failed.  The resultant authenticated tag did not equal the expected authentication tag.
                // Console.WriteLine(crypt.LastErrorText);
            }
        }
        public static string DecryptRijndael(string _key, string _string)
        {
            Chilkat.Crypt2 _encrypt = new Chilkat.Crypt2();

            bool isUnlocked = _encrypt.UnlockComponent("SCOTTGCrypt_FdXsYk2WWPjN");

            //  AES is also known as Rijndael.
            _encrypt.CryptAlgorithm = "aes";

            //  CipherMode may be "ecb" or "cbc"
            _encrypt.CipherMode = "cbc";

            //  KeyLength may be 128, 192, 256
            _encrypt.KeyLength = 256;

            //  The padding scheme determines the contents of the bytes
            //  that are added to pad the result to a multiple of the
            //  encryption algorithm's block size.  AES has a block
            //  size of 16 bytes, so encrypted output is always
            //  a multiple of 16.
            _encrypt.PaddingScheme = 0;

            //  EncodingMode specifies the encoding of the output for
            //  encryption, and the input for decryption.
            //  It may be "hex", "url", "base64", or "quoted-printable".
            _encrypt.EncodingMode = "hex";

            //  An initialization vector is required if using CBC mode.
            //  ECB mode does not use an IV.
            //  The length of the IV is equal to the algorithm's block size.
            //  It is NOT equal to the length of the key.
            string ivHex;
            ivHex = "000102030405060708090A0B0C0D0E0F";
            _encrypt.SetEncodedIV(ivHex,"hex");

            //  The secret key must equal the size of the key.  For
            //  256-bit encryption, the binary secret key is 32 bytes.
            //  For 128-bit encryption, the binary secret key is 16 bytes.
            string keyHex;
            keyHex = _key;
            _encrypt.SetEncodedKey(keyHex,"hex");

            //  Now decrypt:
            return _encrypt.DecryptStringENC(_string);
        }
Ejemplo n.º 28
0
        static string HttpGet(string url)
        {
            bool           success = false;
            HttpWebRequest req     = WebRequest.Create(url) as HttpWebRequest;

            string Token = String.Format("{0:yyyy-MM-dd HH:mm:ss}", new DateTime(2010, 02, 02, 21, 15, 0));

            //SIGN
            Chilkat.PrivateKey privkey1 = new Chilkat.PrivateKey();
            privkey1.LoadPem(mykey);
            Chilkat.Rsa rsa1 = new Chilkat.Rsa();
            success           = rsa1.UnlockComponent("HAFSJORSA_K36nxU3n1Yui");
            success           = rsa1.ImportPrivateKey(privkey1.GetXml());
            rsa1.EncodingMode = "base64";
            rsa1.Charset      = "ANSI";
            rsa1.LittleEndian = false;
            rsa1.OaepPadding  = false;
            string hexSig = rsa1.SignStringENC(Token, "sha-1");


            //VERIFY
            Chilkat.Cert cert2 = new Chilkat.Cert();
            success = cert2.LoadFromBase64(mycert);
            Chilkat.PublicKey pubKey2 = null;
            pubKey2 = cert2.ExportPublicKey();
            Chilkat.Rsa rsa2 = new Chilkat.Rsa();
            success           = rsa2.ImportPublicKey(pubKey2.GetXml());
            rsa2.EncodingMode = "base64";
            rsa2.Charset      = "ANSI";
            rsa2.LittleEndian = false;
            rsa2.OaepPadding  = false;
            success           = rsa2.VerifyStringENC(Token, "sha-1", hexSig);

            req.Headers.Add("Token", Token);
            req.Headers.Add("Signature", hexSig);

            //ENCRYPT
            Chilkat.Cert cert3 = new Chilkat.Cert();
            success = cert3.LoadFromBase64(mycert);
            Chilkat.PublicKey pubKey3 = null;
            pubKey3 = cert3.ExportPublicKey();
            Chilkat.Rsa rsa3 = new Chilkat.Rsa();
            success           = rsa3.UnlockComponent("HAFSJORSA_K36nxU3n1Yui");
            rsa3.EncodingMode = "base64";
            rsa3.Charset      = "ANSI";
            rsa3.LittleEndian = true;
            rsa3.OaepPadding  = false;
            rsa3.ImportPublicKey(pubKey3.GetXml());
            bool usePrivateKey = false;

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] TokenArr = encoding.GetBytes(Token);
            //byte[] encryptedArr = rsa3.EncryptBytes(TokenArr, usePrivateKey);
            string encryptedstr = rsa3.EncryptBytesENC(TokenArr, usePrivateKey);

            //DECRYPT
            Chilkat.Rsa rsa4 = new Chilkat.Rsa();
            rsa4.EncodingMode = "base64";
            rsa4.Charset      = "ANSI";
            rsa4.LittleEndian = true;
            rsa4.OaepPadding  = false;
            rsa4.ImportPrivateKey(privkey1.GetXml());
            usePrivateKey = true;
            //encryptedStr = "XJ65xTR/xvD2N9xBKyKPqPijqTAyJuVtOlbaFUIboJaEPHH9pv+Lhrd5o6MSwKF6TeXs6hVsKnj8jVeYFYoEDgJS95GqaaUomWBhEZYchOp/6dn3ZxCeQoljAWLt6m4C829R9b5JYatYar9YV0d+QV+jVWE4U0rlNrkTqtA02Qw4ztN4/oehgCISrBnc81N1MYNwG9vrTHSVM6tSUWjWxMRubpOBvqKqOxyA9fpJNHgUyzio2X1cp12K++1GEUWNWyYVhTiBr/QM3mUN67mHcn0vvWZvmPhYlIaVn9DqIvVdMbHRbLwrCczFgY4PdHrhcH9yDTlkkAbKUatgDQiI4w==";
            //encryptedStr = "6KQbxh+x5SGIzD89zEwj+/IVVCBocemCXWl1mr+mk9wxRMydCfmMSUHDOafnqiJ6GAJapKbLTHOc9d1OyWTwsp5BQBT5VM20hb9r+AkDrHwkgL06ifizP0gTEO17cyO95jwlRXOfkQKb3cERLBEtOAnRep4bKMSsPLyxRRBX5VT4d19yxRor2V9js0CEFONinxl7qRxjckwvQk53+qpxeQ8jOx+pmrQukX7nWkMajWi+ZFndyfLL3LfRBYZKN2R0vdrnSMKdkxUEUUJybsv4QCMWshNpQznPSantq2dKNe07eB5mX4fRufy4mY4qjqBlf8+XFKdD+J37C6r3THL6pw==";
            //string decryptedStr = rsa4.DecryptStringENC(encryptedStr, usePrivateKey);



            Chilkat.Crypt2 crypt = new Chilkat.Crypt2();
            success              = crypt.UnlockComponent("HAFSJOCrypt_0xo09cJWVQAw");
            crypt.EncodingMode   = "base64";
            crypt.CryptAlgorithm = "none";
            req.Headers.Add("authorization", "Basic " + crypt.EncryptStringENC("Mogens:Hafsjold"));

            string result = null;

            using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(resp.GetResponseStream());
                result = reader.ReadToEnd();
            }
            return(result);
        }
Ejemplo n.º 29
0
        // URLs to help understand this topic:
        // https://developers.google.com/identity/protocols/OAuth2InstalledApp
        //
        private bool oauth2_google(string scope)
        {
            // Generates state and PKCE values.
            string state         = m_prng.GenRandom(32, base64Url);
            string code_verifier = m_prng.GenRandom(32, base64Url);

            Chilkat.Crypt2 crypt = new Chilkat.Crypt2();
            crypt.EncodingMode  = base64Url;
            crypt.HashAlgorithm = "SHA256";
            string       code_challenge        = crypt.HashStringENC(code_verifier);
            const string code_challenge_method = "S256";

            //Create a Chilkat socket for listening.  Begin listening asynchronously.
            Chilkat.Socket listenSocket = new Chilkat.Socket();
            int            backlog      = 5;
            int            listenPort   = 0;

            // Passing a listenPort = 0 causes BindAndListen to find a random unused port.
            // The chosen port will be available via the ListenPort property.
            if (!listenSocket.BindAndListen(listenPort, backlog))
            {
                fgAppendToErrorLog(listenSocket.LastErrorText);
                popupError("Failed to BindAndListen");
                return(false);
            }

            // Get the chosen listen port
            // This ListenPort property is available starting in Chilkat v9.5.0.59
            listenPort = listenSocket.ListenPort;

            // Creates a redirect URI using an available port on the loopback address.
            string redirect_uri = "http://127.0.0.1:" + listenPort.ToString() + "/";

            //Wait a max of 5 minutes.  The OnTaskCompleted event is called when an incoming connection
            //arrives, or when the listen failed.
            listenSocket.OnTaskCompleted += listenSocket_OnTaskCompleted;
            Chilkat.Task task = listenSocket.AcceptNextConnectionAsync(5 * 60000);
            if (task == null)
            {
                MessageBox.Show("Failed to start socket accept...");
                return(false);
            }

            // Add some information that will be needed by the TaskCompleted event..
            Chilkat.JsonObject taskData = new Chilkat.JsonObject();
            taskData.AppendString("code_verifier", code_verifier);
            taskData.AppendString("redirect_uri", redirect_uri);
            task.UserData = taskData.Emit();

            // Start the task.
            task.Run();

            // Creates the OAuth 2.0 authorization request.
            Chilkat.StringBuilder sbAuthRequest = new Chilkat.StringBuilder();
            sbAuthRequest.Append(authorizationEndpoint);
            sbAuthRequest.Append("?response_type=code&scope=");
            sbAuthRequest.Append(m_encoder.EncodeString(scope, "utf-8", "url"));
            sbAuthRequest.Append("&redirect_uri=");
            sbAuthRequest.Append(m_encoder.EncodeString(redirect_uri, "utf-8", "url"));
            sbAuthRequest.Append("&client_id=");
            sbAuthRequest.Append(googleAppClientId);
            sbAuthRequest.Append("&state=");
            sbAuthRequest.Append(state);
            sbAuthRequest.Append("&code_challenge=");
            sbAuthRequest.Append(code_challenge);
            sbAuthRequest.Append("&code_challenge_method=");
            sbAuthRequest.Append(code_challenge_method);

            // Here is a shorter way of building the URL in C#
            //string authorizationRequest = string.Format("{0}?response_type=code&scope={6}&redirect_uri={1}&client_id={2}&state={3}&code_challenge={4}&code_challenge_method={5}",
            //    authorizationEndpoint,  // 0
            //    System.Uri.EscapeDataString(redirect_uri), // 1
            //    googleAppClientId, // 2
            //    state, // 3
            //    code_challenge, // 4
            //    code_challenge_method, // 5
            //    System.Uri.EscapeDataString(scope)); // 6

            // Get authorization from Google account owner...
            webBrowser1.Navigate(sbAuthRequest.GetAsString());

            return(true);
        }
Ejemplo n.º 30
0
        public static void CreateValue(string passwordPhrase)
        {
            Random random      = new Random();
            int    num_letters = 5;

            char[] letters = "abcdefghijklmnopqrstuvwxyz1234567890".ToCharArray();
            string word    = "";

            for (int j = 1; j <= num_letters; j++)
            {
                int letter_num = random.Next(0, letters.Length - 1);
                word += letters[letter_num];
            }
            string phraseForHash = passwordPhrase + word;

            //DES - блоковий
            DES    DESalg   = DES.Create();
            string FileName = "des.txt";

            EncryptTextToFile(phraseForHash, FileName, DESalg.Key, DESalg.IV);
            FileStream   fStream      = File.Open(FileName, FileMode.OpenOrCreate);
            StreamReader streamReader = new StreamReader(fStream);

            string desKey = streamReader.ReadLine();

            fStream.Close();
            streamReader.Close();
            //CFB - зворотній зв'язок
            byte[] plainBytes = Encoding.UTF8.GetBytes(desKey);
            byte[] savedKey   = new byte[16];
            byte[] savedIV    = new byte[16];
            byte[] cipherBytes;
            using (RijndaelManaged Aes128 = new RijndaelManaged())
            {
                Aes128.BlockSize    = 128;
                Aes128.KeySize      = 128;
                Aes128.Mode         = CipherMode.CFB;
                Aes128.FeedbackSize = 8;
                Aes128.Padding      = PaddingMode.None;
                Aes128.GenerateKey();
                Aes128.GenerateIV();
                Aes128.Key.CopyTo(savedKey, 0);
                Aes128.IV.CopyTo(savedIV, 0);

                using (var encryptor = Aes128.CreateEncryptor())
                    using (var msEncrypt = new MemoryStream())
                        using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                            using (var bw = new BinaryWriter(csEncrypt, Encoding.UTF8))
                            {
                                bw.Write(plainBytes);
                                bw.Close();

                                cipherBytes = msEncrypt.ToArray();
                            }
            }
            string cfbKey = cipherBytes.ToString();

            //MD2
            Chilkat.Crypt2 crypt = new Chilkat.Crypt2();
            crypt.HashAlgorithm = "md2";
            string       hashFinal = crypt.HashStringENC(cfbKey);
            FileStream   fStreamF  = File.Open("hash.txt", FileMode.OpenOrCreate);
            StreamWriter sWriter   = new StreamWriter(fStreamF);

            sWriter.WriteLine(hashFinal);
            sWriter.Close();
            fStreamF.Close();
        }