private byte[] decrypt3DES(byte[] item1, string masterPwd, byte[] entrySalt, byte[] cipherT) { try { var sha1 = SHA1.Create("sha1"); var hp = sha1.ComputeHash(item1); Array.Resize(ref hp, 40); Array.Copy(entrySalt, 0, hp, 20, 20); var pes = entrySalt.Concat(Enumerable.Range(1, 20 - entrySalt.Length).Select(b => (byte)0).ToArray()).ToArray(); Array.Resize(ref pes, 40); Array.Copy(entrySalt, 0, pes, 20, 20); var chp = sha1.ComputeHash(hp); var hmac = HMACSHA1.Create(); hmac.Key = chp; var k1 = hmac.ComputeHash(pes); Array.Resize(ref pes, 20); var tk = hmac.ComputeHash(pes); Array.Resize(ref tk, 40); Array.Copy(entrySalt, 0, tk, 20, 20); var k2 = hmac.ComputeHash(tk); Array.Resize(ref k1, 40); Array.Copy(k2, 0, k1, 20, 20); var iv = k1.Skip(k1.Length - 8).ToArray(); var key = k1.Take(24).ToArray(); return(TripleDESHelper.DESCBCDecryptorByte(key, iv, cipherT).Take(24).ToArray()); } catch (Exception ex) { return(null); } }
/// <summary> /// Calculates the signature for the specified buffer. /// </summary> /// <param name="signedPayload">The payload to calculate the signature for.</param> /// <returns> /// The signature. /// </returns> protected override byte[] Sign(byte[] signedPayload) { using (var algorithm = HMACSHA1.Create()) { algorithm.Key = Encoding.ASCII.GetBytes(this.GetConsumerAndTokenSecretString()); return(algorithm.ComputeHash(signedPayload)); } }
private int FinalizeRemove(String filename, String passphrase) { try { core.InitializeKeys(passphrase); } catch { Console.Error.WriteLine("Invalid passphrase"); return(1); } StreamReader sr = new StreamReader(Path.Combine(core.ApplicationDataFolder, "identity")); String username = sr.ReadLine(); String email = sr.ReadLine(); sr.Close(); username.Trim(); email.Trim(); Connect(); ArrayList key = new ArrayList(File.ReadAllBytes(Path.Combine(core.ApplicationDataFolder, "answers.key"))); AESInfo info = new AESInfo(); info.key = (byte[])key.GetRange(0, Crypto.AESKeySize / 8).ToArray(Type.GetType("System.Byte")); info.IV = (byte[])key.GetRange(Crypto.AESKeySize / 8, Crypto.AESIVSize / 8).ToArray(Type.GetType("System.Byte")); Rijndael aes = Rijndael.Create(); String e_macpass = File.ReadAllText(filename); e_macpass = Crypto.StripMessage(e_macpass); byte[] macpass = Crypto.AESDecrypt(Convert.FromBase64String(e_macpass), aes.CreateDecryptor(info.key, info.IV)); HMAC hmac = HMACSHA1.Create(); hmac.Key = macpass; byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes("I want to remove my current public key")); try { if (server.USKeyRem_SendRemoveRequest(username, email, Convert.ToBase64String(hash))) { Console.WriteLine("Removal request successfully sent."); } } catch (Exception e) { Console.Error.WriteLine(e.Message); } File.Delete(Path.Combine(core.ApplicationDataFolder, "answers.key")); return(0); }
public int HOTP(UInt64 C, int digits = 6) { var hmac = HMACSHA1.Create(); hmac.Key = Key; hmac.ComputeHash(BitConverter.GetBytes(C)); return(Truncate(hmac.Hash, digits)); }
public void GenerateKey() { using (RandomNumberGenerator rng = new RNGCryptoServiceProvider()) { /* Keys SHOULD be of the length of the HMAC output to facilitate * interoperability.*/ Key = new byte[HMACSHA1.Create().HashSize / 8]; rng.GetBytes(Key); } }
public static byte[] ComputeHash(byte[] input, byte[] key, string algorithm) { if (input == null || input.Length == 0) { throw new ArgumentException(); } if (key == null || key.Length == 0) { throw new ArgumentException(); } System.Security.Cryptography.KeyedHashAlgorithm hash; switch (algorithm.ToUpperInvariant()) { case "MD5": case "HMACMD5": hash = HMACMD5.Create(); break; case "MD160": case "RIPEMD160": case "HMACRIPEMD160": hash = HMACRIPEMD160.Create(); break; case "SHA": case "SHA1": case "HMACSHA": case "HMACSHA1": hash = HMACSHA1.Create(); break; case "SHA256": case "HMACSHA256": hash = HMACSHA256.Create(); break; case "SHA384": case "HMACSHA384": hash = HMACSHA384.Create(); break; case "SHA512": case "HMACSHA512": hash = HMACSHA512.Create(); break; default: throw new NotSupportedException(); } hash.Key = key; byte[] result = hash.ComputeHash(input); hash.Clear(); return(result); }
/// <summary> /// Pass request method and URI parameters to get the Authorization header value /// </summary> /// <param name="method">Request Method</param> /// <param name="url">Request URI</param> /// <returns>Authorization header value</returns> public String getAuthorizationHeader(String method, String url) { /// Add the realm parameter to the header params this.headerParams.Add("realm", url); /// Start composing the base string from the method and request URI String baseString = method.ToUpper() + "&" + Uri.EscapeDataString(url) + "&"; /// Gather, encode, and sort the base string parameters SortedDictionary <String, String> encodedParams = new SortedDictionary <String, String>(); foreach (KeyValuePair <String, String> parameter in this.headerParams) { if (false == parameter.Key.Equals("realm")) { encodedParams.Add(Uri.EscapeDataString(parameter.Key), Uri.EscapeDataString(parameter.Value)); } } /// Expand the base string by the encoded parameter=value pairs List <String> paramStrings = new List <String>(); foreach (KeyValuePair <String, String> parameter in encodedParams) { paramStrings.Add(parameter.Key + "=" + parameter.Value); } String paramString = Uri.EscapeDataString(String.Join <String>("&", paramStrings)); baseString += paramString; /// Create the OAuth signature String signatureKey = Uri.EscapeDataString(this.appSecret) + "&" + Uri.EscapeDataString(this.accessSecret); HMAC hasher = HMACSHA1.Create(); hasher.Key = Encoding.UTF8.GetBytes(signatureKey); Byte[] rawSignature = hasher.ComputeHash(Encoding.UTF8.GetBytes(baseString)); String oAuthSignature = Convert.ToBase64String(rawSignature); /// Include the OAuth signature parameter in the header parameters array this.headerParams.Add("oauth_signature", oAuthSignature); /// Construct the header string List <String> headerParamStrings = new List <String>(); foreach (KeyValuePair <String, String> parameter in this.headerParams) { headerParamStrings.Add(parameter.Key + "=\"" + parameter.Value + "\""); } String authHeader = "OAuth " + String.Join <String>(", ", headerParamStrings); return(authHeader); }
//autentificacó a través del header public String getAuthorizationHeader(String method, String url) { //realm parameter al header this.headerParams.Add("realm", url); String baseString = method.ToUpper() + "&" + Uri.EscapeDataString(url) + "&"; //filtrar paràmetres del header SortedDictionary <String, String> encodedParams = new SortedDictionary <String, String>(); foreach (KeyValuePair <String, String> parameter in this.headerParams) { if (false == parameter.Key.Equals("realm")) { encodedParams.Add(Uri.EscapeDataString(parameter.Key), Uri.EscapeDataString(parameter.Value)); } } //Creació del paramStrings sumant la key i el value List <String> paramStrings = new List <String>(); foreach (KeyValuePair <String, String> parameter in encodedParams) { paramStrings.Add(parameter.Key + "=" + parameter.Value); } String paramString = Uri.EscapeDataString(String.Join <String>("&", paramStrings)); baseString += paramString; //OAuth signature String signatureKey = Uri.EscapeDataString(this.appSecret) + "&" + Uri.EscapeDataString(this.accessSecret); HMAC hasher = HMACSHA1.Create(); hasher.Key = Encoding.UTF8.GetBytes(signatureKey); Byte[] rawSignature = hasher.ComputeHash(Encoding.UTF8.GetBytes(baseString)); String oAuthSignature = Convert.ToBase64String(rawSignature); //Afegir la signatura al header this.headerParams.Add("oauth_signature", oAuthSignature); //Crear l'string del header List <String> headerParamStrings = new List <String>(); foreach (KeyValuePair <String, String> parameter in this.headerParams) { headerParamStrings.Add(parameter.Key + "=\"" + parameter.Value + "\""); } String authHeader = "OAuth " + String.Join <String>(", ", headerParamStrings); return(authHeader); }
private static byte[] GetHash([CanBeNull] string input, EHashType hash) { var inputBytes = Encoding.ASCII.GetBytes(input); switch (hash) { case EHashType.HMAC: return(HMAC.Create().ComputeHash(inputBytes)); #pragma warning disable RECS0030 // Suggests using the class declaring a static function when calling it case EHashType.HMACMD5: // DevSkim: ignore DS126858 return(HMACMD5.Create().ComputeHash(inputBytes)); // DevSkim: ignore DS126858 case EHashType.HMACSHA1: // DevSkim: ignore DS126858 return(HMACSHA1.Create().ComputeHash(inputBytes)); // DevSkim: ignore DS126858 case EHashType.HMACSHA256: return(HMACSHA256.Create().ComputeHash(inputBytes)); case EHashType.HMACSHA384: return(HMACSHA384.Create().ComputeHash(inputBytes)); case EHashType.HMACSHA512: return(HMACSHA512.Create().ComputeHash(inputBytes)); #pragma warning restore RECS0030 // Suggests using the class declaring a static function when calling it case EHashType.MD5: // DevSkim: ignore DS126858 #pragma warning disable SG0006 // Weak hashing function return(MD5.Create().ComputeHash(inputBytes)); // DevSkim: ignore DS126858 #pragma warning restore SG0006 // Weak hashing function case EHashType.SHA1: // DevSkim: ignore DS126858 #pragma warning disable SG0006 // Weak hashing function return(SHA1.Create().ComputeHash(inputBytes)); // DevSkim: ignore DS126858 #pragma warning restore SG0006 // Weak hashing function case EHashType.SHA256: return(SHA256.Create().ComputeHash(inputBytes)); case EHashType.SHA384: return(SHA384.Create().ComputeHash(inputBytes)); case EHashType.SHA512: return(SHA512.Create().ComputeHash(inputBytes)); default: return(inputBytes); } }
private string HashMac(string EncrypText) { HMAC hasher; Byte[] utf8EncodedString = Encoding.UTF8.GetBytes(EncrypText); hasher = HMACSHA1.Create(); hasher.Key = Encoding.UTF8.GetBytes(SecretKey); Byte[] hashResult = hasher.ComputeHash(utf8EncodedString); return(Convert.ToBase64String(hashResult)); }
/// <summary> /// 生成签名 /// </summary> /// <param name="method">请求方法 get/post </param> /// <param name="url_path">url_path</param> /// <param name="param">表单参数</param> /// <param name="secret">密钥</param> /// <returns>返回签名结果</returns> // static public string MakeSig(string method, string url_path, Dictionary <string, string> param, string secret) { string mk = MakeSource(method, url_path, param); //使用SHA1的HMAC HMAC hmac = HMACSHA1.Create(); hmac.Key = Encoding.UTF8.GetBytes(secret); byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(mk)); //转为base64编码 string my_sign = Convert.ToBase64String(hash); return(my_sign); }
private static byte[] GetHash(string Source, HashType hash) { byte[] inputBytes = Encoding.ASCII.GetBytes(Source); switch (hash) { case HashType.HMAC: return(HMAC.Create().ComputeHash(inputBytes)); case HashType.HMACMD5: return(HMACMD5.Create().ComputeHash(inputBytes)); case HashType.HMACSHA1: return(HMACSHA1.Create().ComputeHash(inputBytes)); case HashType.HMACSHA256: return(HMACSHA256.Create().ComputeHash(inputBytes)); case HashType.HMACSHA384: return(HMACSHA384.Create().ComputeHash(inputBytes)); case HashType.HMACSHA512: return(HMACSHA512.Create().ComputeHash(inputBytes)); /* * case HashType.MACTripleDES: * return MACTripleDES.Create().ComputeHash(inputBytes); */ case HashType.MD5: return(MD5.Create().ComputeHash(inputBytes)); /* * case HashType.RIPEMD160: * return RIPEMD160.Create().ComputeHash(inputBytes); */ case HashType.SHA1: return(SHA1.Create().ComputeHash(inputBytes)); case HashType.SHA256: return(SHA256.Create().ComputeHash(inputBytes)); case HashType.SHA384: return(SHA384.Create().ComputeHash(inputBytes)); case HashType.SHA512: return(SHA512.Create().ComputeHash(inputBytes)); default: return(inputBytes); } }
public virtual string Signature(HttpRequestMessage request, string secret) { using (var algorithm = HMACSHA1.Create()) { //设置散列加密算法的密钥 algorithm.Key = Encoding.UTF8.GetBytes(secret); //计算当前请求的签名数据 var data = Encoding.UTF8.GetBytes(Canonicalize(request)); //计算加密后的散列值(签名内容) return(System.Convert.ToBase64String(algorithm.ComputeHash(data))); } }
private static byte[] GetHash(string input, EHashType hash) { var inputBytes = Encoding.ASCII.GetBytes(input); switch (hash) { case EHashType.HMAC: return(HMAC.Create().ComputeHash(inputBytes)); case EHashType.HMACMD5: return(HMACMD5.Create().ComputeHash(inputBytes)); case EHashType.HMACSHA1: return(HMACSHA1.Create().ComputeHash(inputBytes)); case EHashType.HMACSHA256: return(HMACSHA256.Create().ComputeHash(inputBytes)); case EHashType.HMACSHA384: return(HMACSHA384.Create().ComputeHash(inputBytes)); case EHashType.HMACSHA512: return(HMACSHA512.Create().ComputeHash(inputBytes)); case EHashType.MACTripleDES: return(MACTripleDES.Create().ComputeHash(inputBytes)); case EHashType.MD5: return(MD5.Create().ComputeHash(inputBytes)); case EHashType.RIPEMD160: return(RIPEMD160.Create().ComputeHash(inputBytes)); case EHashType.SHA1: return(SHA1.Create().ComputeHash(inputBytes)); case EHashType.SHA256: return(SHA256.Create().ComputeHash(inputBytes)); case EHashType.SHA384: return(SHA384.Create().ComputeHash(inputBytes)); case EHashType.SHA512: return(SHA512.Create().ComputeHash(inputBytes)); default: return(inputBytes); } }
private String EncryptMACPass(String email, AESInfo aesInfo) { HMAC hmac = HMACSHA1.Create(); Rijndael aes = Rijndael.Create(); DatabaseConnection connection = new DatabaseConnection(); connection.setMACPass(email, Convert.ToBase64String(hmac.Key)); connection.close(); String result = Util.Wrap(Convert.ToBase64String(Crypto.AESEncrypt(hmac.Key, aes.CreateEncryptor(aesInfo.key, aesInfo.IV))), 64); return(result); }
private static string publicKey = string.Format("http://open.weather.com.cn/data/?areaid={0}&type={1}&date={2}&appid={3}", areaID, type, date, appID);//public_key为不包含key在内的完整URL其它部分(此处appid为完整appid) string GetKey() { //使用SHA1的HMAC HMAC hmac = HMACSHA1.Create(); var data = System.Text.Encoding.UTF8.GetBytes(publicKey); //密钥 var key = System.Text.Encoding.UTF8.GetBytes(privateKey); hmac.Key = key; //对数据进行签名 var signedData = hmac.ComputeHash(data); return(Convert.ToBase64String(signedData)); }
public void HashHMACSHA1() { byte[] plaintext = new byte[] { 0, 1, 2, 3 }; HashCryptographer cryptographer = new HashCryptographer(typeof(HMACSHA1), key); byte[] hash1 = cryptographer.ComputeHash(plaintext); Assert.IsFalse(CryptographyUtility.CompareBytes(plaintext, hash1)); KeyedHashAlgorithm hmacsha1 = HMACSHA1.Create(); hmacsha1.Key = key.DecryptedKey; byte[] hash2 = hmacsha1.ComputeHash(plaintext); Assert.IsTrue(CryptographyUtility.CompareBytes(hash1, hash2)); }
public static string Hash(string plain) { if (IsBlank(plain)) { return(string.Empty); } using (KeyedHashAlgorithm csp = HMACSHA1.Create()) { csp.Key = Key; byte[] data = System.Text.Encoding.Default.GetBytes(plain); byte[] hash = csp.ComputeHash(data); return(System.Convert.ToBase64String(hash)); } }
/// <summary> /// Sets up all security stuff for encrypting content and checking integrity. /// </summary> /// <param name="password">The password.</param> protected void SetupSecurityAlgorithms(string password) { lock (this) { if ((this.ZpaFeatureFlags & ZpaFeatureFlags.ElectronicCodebookEncryption) != 0 || (this.ZpaFeatureFlags & ZpaFeatureFlags.CipherBlockChainingEncryption) != 0) { // encryption this.SymmetricAlgorithm = Rijndael.Create(); this.SymmetricAlgorithm.Key = ZeroProofAuthorizationUtility.GeneratePasswordBasedSequence("Key" + password, this.Salt, 32); this.SymmetricAlgorithm.IV = ZeroProofAuthorizationUtility.GeneratePasswordBasedSequence("IV" + password, this.Salt, 16); this.SymmetricAlgorithm.Mode = (this.ZpaFeatureFlags & ZpaFeatureFlags.ElectronicCodebookEncryption) != 0 ? CipherMode.ECB : CipherMode.CBC; this._encryptor = this.SymmetricAlgorithm.CreateEncryptor(); this._decryptor = this.SymmetricAlgorithm.CreateDecryptor(); } // and integrity checking if ((this.ZpaFeatureFlags & ZpaFeatureFlags.Mac3DesCbcSigning) != 0) { this.KeyedHashAlgorithm = MACTripleDES.Create(); } if ((this.ZpaFeatureFlags & ZpaFeatureFlags.HmacSha1Signing) != 0) { this.KeyedHashAlgorithm = HMACSHA1.Create(); } if (this.KeyedHashAlgorithm != null) { this.KeyedHashAlgorithm.Key = ZeroProofAuthorizationUtility.GeneratePasswordBasedSequence("M3D" + password, this.Salt, 24); } // LOG: BinaryLogWriter binaryLogWriter = GenuineLoggingServices.BinaryLogWriter; if (binaryLogWriter != null && binaryLogWriter[LogCategory.Security] > 0) { binaryLogWriter.WriteEvent(LogCategory.Security, "SecuritySession_BaseZpaSession.SetupSecurityAlgorithms", LogMessageType.SecuritySessionKey, null, null, this.Remote, null, GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, this, this.Name, -1, 0, 0, 0, string.Format("Zero Proof Authorization Flags: {0} Encryption: {1} Data Integrity: {2}", Enum.Format(typeof(ZpaFeatureFlags), this.ZpaFeatureFlags, "g"), this.SymmetricAlgorithm == null ? "No" : this.SymmetricAlgorithm.GetType().ToString(), this.KeyedHashAlgorithm == null ? "No" : this.KeyedHashAlgorithm.GetType().ToString()), null, null, null, "Security Session security information is initialized."); } } }
private static byte[] GetHash(string input, EHashType hash) { byte[] inputBytes = Encoding.ASCII.GetBytes(input); switch (hash) { case EHashType.HMAC: return(HMAC.Create().ComputeHash(inputBytes)); case EHashType.HMACMD5: return(HMACMD5.Create().ComputeHash(inputBytes)); case EHashType.HMACSHA1: return(HMACSHA1.Create().ComputeHash(inputBytes)); case EHashType.HMACSHA256: return(HMACSHA256.Create().ComputeHash(inputBytes)); case EHashType.HMACSHA384: return(HMACSHA384.Create().ComputeHash(inputBytes)); case EHashType.HMACSHA512: return(HMACSHA512.Create().ComputeHash(inputBytes)); #pragma warning disable CS0618 // Type or member is obsolete case EHashType.MD5: #pragma warning restore CS0618 // Type or member is obsolete return(MD5.Create().ComputeHash(inputBytes)); #pragma warning disable CS0618 // Type or member is obsolete case EHashType.SHA1: #pragma warning restore CS0618 // Type or member is obsolete return(SHA1.Create().ComputeHash(inputBytes)); case EHashType.SHA256: return(SHA256.Create().ComputeHash(inputBytes)); case EHashType.SHA384: return(SHA384.Create().ComputeHash(inputBytes)); case EHashType.SHA512: return(SHA512.Create().ComputeHash(inputBytes)); default: return(inputBytes); } }
private bool SendQuery(String userID, String email, String message, String macValue) { DatabaseConnection connection = new DatabaseConnection(); String dbUserid = connection.getUserID(email); // connection.close(); if (userID == null) { ErrorLog_Write("Error - " + email + ": Email does not exist!"); Console.WriteLine("Error - " + email + ": Email does not exist!"); throw new Exception("Invalid user"); } if (userID != dbUserid) { ErrorLog_Write("Error - " + email + ": User id does not exist!"); Console.WriteLine("Error - " + email + ": User id does not exist!"); throw new Exception("Invalid user"); } // connection = new DatabaseConnection(); String dbMACPass = connection.getMACPass(email); // connection.close(); if (dbMACPass == null) { ErrorLog_Write("Error: MacPass does not exist!"); Console.WriteLine("Error: MacPass does not exist!"); throw new Exception("Invalid Mac Pass"); } HMAC hmac = HMACSHA1.Create(); hmac.Key = Convert.FromBase64String(dbMACPass); byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message)); if (Util.Compare(hash, Convert.FromBase64String(macValue))) { connection.removeMACPass(email); connection.close(); return(true); } connection.close(); ErrorLog_Write("Error - " + email + ": MAC value is tampered, public key is not set."); Console.WriteLine("Error - " + email + ": MAC value is tampered, public key is not set."); throw new Exception("MAC value is tampered, public key is not set"); }
private static byte[] GetHash(string input, eHashType hash) { byte[] inputBytes = Encoding.ASCII.GetBytes(input); switch (hash) { case eHashType.HMAC: return(HMAC.Create().ComputeHash(inputBytes)); case eHashType.HMACMD5: return(HMACMD5.Create().ComputeHash(inputBytes)); case eHashType.HMACSHA1: return(HMACSHA1.Create().ComputeHash(inputBytes)); case eHashType.HMACSHA256: return(HMACSHA256.Create().ComputeHash(inputBytes)); case eHashType.HMACSHA384: return(HMACSHA384.Create().ComputeHash(inputBytes)); case eHashType.HMACSHA512: return(HMACSHA512.Create().ComputeHash(inputBytes)); case eHashType.MD5: return(MD5.Create().ComputeHash(inputBytes)); case eHashType.SHA1: return(SHA1.Create().ComputeHash(inputBytes)); case eHashType.SHA256: return(SHA256.Create().ComputeHash(inputBytes)); case eHashType.SHA384: return(SHA384.Create().ComputeHash(inputBytes)); case eHashType.SHA512: return(SHA512.Create().ComputeHash(inputBytes)); default: return(inputBytes); } }
/// <summary> /// 生成签名 /// </summary> /// <param name="method">请求方法 get/post </param> /// <param name="url_path">url_path</param> /// <param name="param">表单参数</param> /// <param name="secret">密钥</param> /// <returns>返回签名结果</returns> // static public string MakeSig(string method, string url_path, Dictionary <string, string> param, string secret) { string mk = MakeSource(method, url_path, param); //HttpContext.Current.Response.Write("<br><br>============= MakeSig info ================<br>"); //HttpContext.Current.Response.Write("mk :" + mk + "<br>"); //HttpContext.Current.Response.Write("secret :" + secret + "<br>"); //使用SHA1的HMAC HMAC hmac = HMACSHA1.Create(); hmac.Key = Encoding.UTF8.GetBytes(secret); byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(mk)); //转为base64编码 string my_sign = Convert.ToBase64String(hash); //HttpContext.Current.Response.Write("my_sign :" + my_sign + "<br>"); return(my_sign); }
/// <summary>ハッシュ(キー付き)サービスプロバイダの生成</summary> /// <param name="ekha">ハッシュ(キー付き)サービスプロバイダの列挙型</param> /// <returns>ハッシュ(キー付き)サービスプロバイダ</returns> private static KeyedHashAlgorithm CreateKeyedHashAlgorithmServiceProvider(EnumKeyedHashAlgorithm ekha) { // ハッシュ(キー付き)サービスプロバイダ KeyedHashAlgorithm kha = null; if (ekha == EnumKeyedHashAlgorithm.Default) { // 既定の暗号化サービスプロバイダ kha = KeyedHashAlgorithm.Create(); // devps(1703) } else if (ekha == EnumKeyedHashAlgorithm.HMACSHA1) { // HMACSHA1サービスプロバイダ kha = HMACSHA1.Create(); // devps(1703) } else if (ekha == EnumKeyedHashAlgorithm.MACTripleDES) { // MACTripleDESサービスプロバイダ kha = MACTripleDES.Create(); // devps(1703) } return(kha); }
private static void VerifyIntegrity(FileData fileData) { BlobBuilder builder = new BlobBuilder(); if (fileData.ppkFileVersion != Version.V1) { builder.AddStringBlob(fileData.publicKeyAlgorithm.GetIdentifierString()); builder.AddStringBlob(fileData.privateKeyAlgorithm.GetIdentifierString()); builder.AddBlob(Encoding.GetEncoding(1252).GetBytes(fileData.comment)); builder.AddBlob(fileData.publicKeyBlob); builder.AddInt(fileData.privateKeyBlob.Data.Length); } builder.AddBytes(fileData.privateKeyBlob.Data); byte[] computedHash; SHA1 sha = SHA1.Create(); if (fileData.isHMAC) { HMAC hmac = HMACSHA1.Create(); if (fileData.passphrase != null) { using (PinnedArray <byte> hashData = new PinnedArray <byte>(cMACKeySalt.Length + fileData.passphrase.Length)) { Array.Copy(Encoding.UTF8.GetBytes(cMACKeySalt), hashData.Data, cMACKeySalt.Length); IntPtr passphrasePtr = Marshal.SecureStringToGlobalAllocUnicode(fileData.passphrase); for (int i = 0; i < fileData.passphrase.Length; i++) { int unicodeChar = Marshal.ReadInt16(passphrasePtr + i * 2); byte ansiChar = Util.UnicodeToAnsi(unicodeChar); hashData.Data[cMACKeySalt.Length + i] = ansiChar; Marshal.WriteByte(passphrasePtr, i * 2, 0); } Marshal.ZeroFreeGlobalAllocUnicode(passphrasePtr); hmac.Key = sha.ComputeHash(hashData.Data); } } else { hmac.Key = sha.ComputeHash(Encoding.UTF8.GetBytes(cMACKeySalt)); } computedHash = hmac.ComputeHash(builder.GetBlob()); hmac.Clear(); } else { computedHash = sha.ComputeHash(builder.GetBlob()); } sha.Clear(); builder.Clear(); try { int macLength = computedHash.Length; bool failed = false; if (fileData.privateMAC.Length == macLength) { for (int i = 0; i < macLength; i++) { if (fileData.privateMAC[i] != computedHash[i]) { failed = true; break; } } } else { failed = true; } if (failed) { // private key data should start with 3 bytes with value 0 if it was // properly decrypted or does not require decryption if ((fileData.privateKeyBlob.Data[0] == 0) && (fileData.privateKeyBlob.Data[1] == 0) && (fileData.privateKeyBlob.Data[2] == 0)) { // so if they bytes are there, passphrase decrypted properly and // something else is wrong with the file contents throw new PpkFormatterException(PpkFormatterException.PpkErrorType.FileCorrupt); } else { // if the bytes are not zeros, we assume that the data was not // properly decrypted because the passphrase was incorrect. throw new PpkFormatterException(PpkFormatterException.PpkErrorType.BadPassphrase); } } } catch { throw; } finally { Array.Clear(computedHash, 0, computedHash.Length); } }
// ReSharper disable AccessToStaticMemberViaDerivedType private void setHashAlgorithm() { switch (cbAlgo.SelectedIndex) { case 0: switch (cbOption.SelectedIndex) { case 0: _ha = SHA256.Create(); break; case 1: _ha = SHA256Cng.Create(); break; case 2: _ha = HMACSHA256.Create(); break; } break; case 1: switch (cbOption.SelectedIndex) { case 0: _ha = SHA512.Create(); break; case 1: _ha = SHA512Cng.Create(); break; case 2: _ha = HMACSHA512.Create(); break; } break; case 2: switch (cbOption.SelectedIndex) { case 0: _ha = SHA1.Create(); break; case 1: _ha = SHA1Cng.Create(); break; case 2: _ha = HMACSHA1.Create(); break; } break; case 3: switch (cbOption.SelectedIndex) { case 0: _ha = MD5.Create(); break; case 1: _ha = MD5Cng.Create(); break; case 2: _ha = HMACMD5.Create(); break; } break; case 4: //stays null for Modbus-CRC16 break; case 5: _ha = new Crc32(); break; } }
/// <summary> /// Pass request method and URI parameters to get the Authorization header value /// </summary> /// <param name="method">Request Method</param> /// <param name="url">Request URI</param> /// <returns>Authorization header value</returns> public String getAuthorizationHeader(String method, String url) { var URIparts = url.Split('?'); string baseURI = URIparts[0]; /// Add the realm parameter to the header params //string realm = new Uri(url).Host; string realm = baseURI; this.headerParams.Add("realm", realm); /// Start composing the base string from the method and request URI string baseString = method.ToUpper() + "&" + Uri.EscapeDataString(baseURI) + "&"; string[] requestParameters = URIparts.Count() > 1 ? URIparts[1].Split('&') : new string[] { }; foreach (var parameter in requestParameters) { var parts = parameter.Split('='); string key = parts[0]; string value = parts.Count() > 1 ? parts[1] : ""; headerParams.Add(key, value); } /// Gather, encode, and sort the base string parameters SortedDictionary <String, String> encodedParams = new SortedDictionary <String, String>(); foreach (var parameter in this.headerParams) { if (!parameter.Key.Equals("realm")) { encodedParams.Add(Uri.EscapeDataString(parameter.Key), Uri.EscapeDataString(parameter.Value)); } } /// Expand the base string by the encoded parameter=value pairs List <String> paramStrings = new List <String>(); foreach (KeyValuePair <String, String> parameter in encodedParams) { paramStrings.Add(parameter.Key + "=" + parameter.Value); } String paramString = Uri.EscapeDataString(String.Join <String>("&", paramStrings)); baseString += paramString; /// Create the OAuth signature String signatureKey = Uri.EscapeDataString(this.appSecret) + "&" + Uri.EscapeDataString(this.accessSecret); HMAC hasher = HMACSHA1.Create(); hasher.Key = Encoding.UTF8.GetBytes(signatureKey); Byte[] rawSignature = hasher.ComputeHash(Encoding.UTF8.GetBytes(baseString)); String oAuthSignature = Convert.ToBase64String(rawSignature); /// Include the OAuth signature parameter in the header parameters array this.headerParams.Add("oauth_signature", oAuthSignature); /// Construct the header string List <String> headerParamStrings = new List <String>(); foreach (KeyValuePair <String, String> parameter in this.headerParams) { headerParamStrings.Add(parameter.Key + "=\"" + parameter.Value + "\""); } String authHeader = "OAuth " + String.Join <String>(", ", headerParamStrings); return(authHeader); }
public void PrepareCryptoTransforms() { byte[] key_cache; HashAlgorithm hash_key = SHA1.Create(); // { MemoryStream ms_cache = new MemoryStream(); NetworkByteWriter nbw_cache = new NetworkByteWriter(ms_cache); nbw_cache.WriteMPInt(verify_k); nbw_cache.WriteBytes(verify_h); nbw_cache.WriteByte((byte)0x41); nbw_cache.WriteBytes(verify_h); key_cache = ms_cache.ToArray(); } byte[] IVc2s = hash_key.ComputeHash(key_cache); int j = key_cache.Length - verify_h.Length - 1; key_cache[j] = 0x42; byte[] IVs2c = hash_key.ComputeHash(key_cache); key_cache[j] = 0x43; byte[] Ec2s = hash_key.ComputeHash(key_cache); key_cache[j] = 0x44; byte[] Es2c = hash_key.ComputeHash(key_cache); key_cache[j] = 0x45; byte[] MACc2s = hash_key.ComputeHash(key_cache); key_cache[j] = 0x46; byte[] MACs2c = hash_key.ComputeHash(key_cache); { byte[] tmp = new byte[16]; Array.Copy(Ec2s, 0, tmp, 0, tmp.Length); Ec2s = tmp; } { byte[] tmp = new byte[16]; Array.Copy(IVc2s, 0, tmp, 0, tmp.Length); IVc2s = tmp; } { byte[] tmp = new byte[16]; Array.Copy(Es2c, 0, tmp, 0, tmp.Length); Es2c = tmp; } { byte[] tmp = new byte[16]; Array.Copy(IVs2c, 0, tmp, 0, tmp.Length); IVs2c = tmp; } RijndaelManaged rijndael = new RijndaelManaged(); rijndael.Mode = CipherMode.CBC; rijndael.Padding = PaddingMode.None; crypto_encryptor = rijndael.CreateEncryptor(Ec2s, IVc2s); crypto_decryptor = rijndael.CreateDecryptor(Es2c, IVs2c); crypto_mac_encryptor = HMACSHA1.Create(); ((HMAC)crypto_mac_encryptor).Key = MACc2s; }
private static KeyedHashAlgorithm CreateHashAlgorithm() { return(HMACSHA1.Create()); }
protected override void SetUp() { hash = HMACSHA1.Create(); (hash as KeyedHashAlgorithm).Key = new byte [8]; }