public string HashContent(string content) { var crypt = new Chilkat.Crypt2 { HashAlgorithm = "sha256" }; var hash = crypt.HashStringENC(content); return(hash); }
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); }
/// <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)); }
// 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); }
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); } }
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(); }