public void TestSHA1() { byte[] data = new byte[256]; byte[] result; var shaM = new SHA1Managed(); result = shaM.ComputeHash(data); }
public static bool CompareCode(string regcode) { if (regcode == null || regcode == "") { return false; } try { string toolcode = GetDiskVolumeSerialNumber() + GetCpuSerialNumber(); string pubkey = "<RSAKeyValue><Modulus>xe3teTUwLgmbiwFJwWEQnshhKxgcasglGsfNVFTk0hdqKc9i7wb+gG7HOdPZLh65QyBcFfzdlrawwVkiPEL5kNTX1q3JW5J49mTVZqWd3w49reaLd8StHRYJdyGAL4ZovBhSTThETi+zYvgQ5SvCGkM6/xXOz+lkMaEgeFcjQQs=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"; string prikey = "<RSAKeyValue><Modulus>xe3teTUwLgmbiwFJwWEQnshhKxgcasglGsfNVFTk0hdqKc9i7wb+gG7HOdPZLh65QyBcFfzdlrawwVkiPEL5kNTX1q3JW5J49mTVZqWd3w49reaLd8StHRYJdyGAL4ZovBhSTThETi+zYvgQ5SvCGkM6/xXOz+lkMaEgeFcjQQs=</Modulus><Exponent>AQAB</Exponent><P>5flMAd7IrUTx92yomBdJBPDzp1Kclpaw4uXB1Ht+YXqwLW/9icI6mcv7d2O0kuVLSWj8DPZJol9V8AtvHkC3oQ==</P><Q>3FRA9UWcFrVPvGR5bewcL7YqkCMZlybV/t6nCH+gyMfbEvgk+p04F+j8WiHDykWj+BahjScjwyF5SGADbrfJKw==</Q><DP>b4WOU1XbERNfF3JM67xW/5ttPNX185zN2Ko8bbMZXWImr1IgrD5RNqXRo1rphVbGRKoxmIOSv7flr8uLrisKIQ==</DP><DQ>otSZlSq2qomgvgg7PaOLSS+F0TQ/i1emO0/tffhkqT4ah7BgE97xP6puJWZivjAteAGxrxHH+kPY0EY1AzRMNQ==</DQ><InverseQ>Sxyz0fEf5m7GrzAngLDRP/i+QDikJFfM6qPyr3Ub6Y5RRsFbeOWY1tX3jmV31zv4cgJ6donH7W2dSBPi67sSsw==</InverseQ><D>nVqofsIgSZltxTcC8fA/DFz1kxMaFHKFvSK3RKIxQC1JQ3ASkUEYN/baAElB0f6u/oTNcNWVPOqE31IDe7ErQelVc4D26RgFd5V7dSsF3nVz00s4mq1qUBnCBLPIrdb0rcQZ8FUQTsd96qW8Foave4tm8vspbM65iVUBBVdSYYE=</D></RSAKeyValue>"; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(pubkey); RSAPKCS1SignatureDeformatter f = new RSAPKCS1SignatureDeformatter(rsa); f.SetHashAlgorithm("SHA1"); SHA1Managed sha = new SHA1Managed(); byte[] name = sha.ComputeHash(ASCIIEncoding.ASCII.GetBytes(toolcode)); byte[] key = Convert.FromBase64String(regcode); return f.VerifySignature(name, key); } } catch { return false; } }
/// /// 图片解密 /// /// 源文件 /// 保存文件 /// 密钥 public static byte[] DecryptFile2(byte[] data, string keyStr) { byte[] inputByteArray; //通过des解密 DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByteArray = data; byte[] keyByteArray = Encoding.Default.GetBytes(keyStr); //定义哈希变量 SHA1 ha = new SHA1Managed(); //计算指定字节组指定区域哈希值 byte[] hb = ha.ComputeHash(keyByteArray); //加密密钥数组 byte[] sKey = new byte[8]; //加密变量 byte[] sIV = new byte[8]; for (int i = 0; i < 8; i++) sKey[i] = hb[i]; for (int i = 8; i < 16; i++) sIV[i - 8] = hb[i]; //获取加密密钥 des.Key = sKey; //加密变量 des.IV = sIV; MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); inputByteArray = ms.ToArray(); cs.Close(); ms.Close(); return inputByteArray; }
/// <summary> /// 加密字符串 /// </summary> /// <param name="inputStr">输入字符串</param> /// <param name="keyStr">密码,可以为“”</param> /// <returns>输出加密后字符串</returns> public string EncryptString(string inputStr, string keyStr) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); if (keyStr == "") keyStr = key; byte[] inputByteArray = Encoding.Default.GetBytes(inputStr); byte[] keyByteArray = Encoding.Default.GetBytes(keyStr); SHA1 ha = new SHA1Managed(); byte[] hb = ha.ComputeHash(keyByteArray); sKey = new byte[8]; sIV = new byte[8]; for (int i = 0; i < 8; i++) sKey[i] = hb[i]; for (int i = 8; i < 16; i++) sIV[i - 8] = hb[i]; des.Key = sKey; des.IV = sIV; MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } cs.Close(); ms.Close(); return ret.ToString(); }
public static string EncodePassword(string value) { string encodedpasswordstring = ""; byte[] encodedpassword; byte[] sha1hash; System.Security.Cryptography.SHA1Managed hash = new System.Security.Cryptography.SHA1Managed(); // get the byte representation of the password encodedpassword = Encoding.ASCII.GetBytes(value); // Compute the SHA1 hash of the password. sha1hash = hash.ComputeHash(encodedpassword); // String builder to create the final Hex encoded hash string StringBuilder hashedkey = new StringBuilder(sha1hash.Length); // Convert to Hex encoded string foreach (byte b in sha1hash) { // This generates the hex encoded string in lower case. Use "X2" to get hash string in upper-case. hashedkey.Append(b.ToString("x2")); } encodedpasswordstring = hashedkey.ToString(); // Final Hex encoded SHA1 hash string return(encodedpasswordstring); }
public void AddFile(DeduplicatorState state, FileInfo sourceFile, string destinationPath) { if (state.DestinationToFileHash.ContainsKey(destinationPath)) { // File has already been added. return; } // Read the source file. var memory = new MemoryStream(); using (var stream = new BufferedStream(new FileStream(sourceFile.FullName, FileMode.Open, FileAccess.Read, FileShare.None), 1200000)) { stream.CopyTo(memory); } // Hash the memory stream. var sha1 = new SHA1Managed(); memory.Seek(0, SeekOrigin.Begin); var hashBytes = sha1.ComputeHash(memory); var hashString = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant(); memory.Seek(0, SeekOrigin.Begin); // Add to the file hash -> source map if not already present. if (!state.FileHashToSource.ContainsKey(hashString)) { state.FileHashToSource.Add(hashString, memory); } else { memory.Dispose(); } state.DestinationToFileHash.Add(destinationPath, hashString); }
private String CreateWsseHeader() { // HTTPリクエスト毎に生成するセキュリティ・トークン(ランダム文字列) byte[] b_nonce = new byte[8]; Random rand = new Random(); rand.NextBytes( b_nonce ); // nonce 生成時の日 string created = DateTime.Now.ToUniversalTime().ToString( "o" ); byte[] b_created = Encoding.UTF8.GetBytes( created ); byte[] b_password = Encoding.UTF8.GetBytes( Password ); SHA1Managed sh1 = new SHA1Managed(); sh1.Initialize(); // Join byte[] origin = new byte[b_nonce.Length + b_created.Length + b_password.Length]; Array.Copy( b_nonce, 0, origin, 0, b_nonce.Length ); Array.Copy( b_created, 0, origin, b_nonce.Length, b_created.Length ); Array.Copy( b_password, 0, origin, b_nonce.Length + b_created.Length, b_password.Length ); // Create Hash Value byte[] passwordDigest = sh1.ComputeHash( origin ); string header = String.Format( "UsernameToken Username=\"{0}\", PasswordDigest=\"{1}\", Nonce=\"{2}\", Created=\"{3}\"", Username, Convert.ToBase64String( passwordDigest ), Convert.ToBase64String( b_nonce ), created ); return header; }
public static TapeRecord ReadRecord(Stream file) { ReadAndVerifySignature(file, ReadableHeaderStart, "Start"); var dataLength = ReadReadableInt64(file); ReadAndVerifySignature(file, ReadableHeaderEnd, "Header-End"); var data = new byte[dataLength]; file.Read(data, 0, (int) dataLength); ReadAndVerifySignature(file, ReadableFooterStart, "Footer-Start"); ReadReadableInt64(file); //length verified var recVersion = ReadReadableInt64(file); var hash = ReadReadableHash(file); using (var managed = new SHA1Managed()) { var computed = managed.ComputeHash(data); if (!computed.SequenceEqual(hash)) throw new InvalidOperationException("Hash corrupted"); } ReadAndVerifySignature(file, ReadableFooterEnd, "End"); return new TapeRecord(recVersion, data); }
public int CreateServerKeyExchangeSign(SecurityParameters sparams, byte[] params_buffer, int params_offset, int params_length, byte[] sign_buffer, int sign_offset) { byte[] hash; using (SHA1Managed sha1 = new SHA1Managed ()) { sha1.Initialize (); sha1.TransformBlock (sparams.ClientRandom, 0, sparams.ClientRandom.Length, sparams.ClientRandom, 0); sha1.TransformBlock (sparams.ServerRandom, 0, sparams.ServerRandom.Length, sparams.ServerRandom, 0); sha1.TransformBlock (params_buffer, params_offset, params_length, params_buffer, params_offset); sha1.TransformFinalBlock (Utility.EmptyByteArray, 0, 0); hash = sha1.Hash; } // 署名 byte[] sign = _ecdsa.SignHash (hash); // DER形式に変換 // TODO: 400bit以上の署名サイズに対応させる byte der_len = (byte)(sign.Length + 6); byte int_len = (byte)(sign.Length >> 1); sign_buffer[sign_offset + 0] = 0x30; sign_buffer[sign_offset + 1] = (byte)(der_len - 2); sign_buffer[sign_offset + 2] = 0x02; sign_buffer[sign_offset + 3] = int_len; Buffer.BlockCopy (sign, 0, sign_buffer, sign_offset + 4, int_len); sign_offset += int_len + 4; sign_buffer[sign_offset + 0] = 0x02; sign_buffer[sign_offset + 1] = int_len; Buffer.BlockCopy (sign, int_len, sign_buffer, sign_offset + 2, int_len); return der_len; }
public static AESKeyData GenerateKeyDataFromNonces(byte[] serverNonce, byte[] newNonce) { using (SHA1 hash = new SHA1Managed()) { var nonces = new byte[48]; newNonce.CopyTo(nonces, 0); serverNonce.CopyTo(nonces, 32); byte[] hash1 = hash.ComputeHash(nonces); serverNonce.CopyTo(nonces, 0); newNonce.CopyTo(nonces, 16); byte[] hash2 = hash.ComputeHash(nonces); nonces = new byte[64]; newNonce.CopyTo(nonces, 0); newNonce.CopyTo(nonces, 32); byte[] hash3 = hash.ComputeHash(nonces); using (var keyBuffer = new MemoryStream(32)) using (var ivBuffer = new MemoryStream(32)) { keyBuffer.Write(hash1, 0, hash1.Length); keyBuffer.Write(hash2, 0, 12); ivBuffer.Write(hash2, 12, 8); ivBuffer.Write(hash3, 0, hash3.Length); ivBuffer.Write(newNonce, 0, 4); return new AESKeyData(keyBuffer.ToArray(), ivBuffer.ToArray()); } } }
public static string GetHash(byte[] bytes) { using (var sha1 = new SHA1Managed()) { return string.Join("", sha1.ComputeHash(bytes).Select(b => b.ToString("x2"))); } }
/// <summary> /// Performs an SHA1 hash of an input byte array /// </summary> public static byte[] SHAHash( byte[] input ) { using ( var sha = new SHA1Managed() ) { return sha.ComputeHash( input ); } }
public string GenerateSHA1Hash(string str) { SHA1Managed sha1 = new SHA1Managed(); var hash = sha1.ComputeHash(StringToAscii(str)); string hex = BitConverter.ToString(hash); return hex.Replace("-", "").ToLower(); }
public byte[] CreateSha1(byte[] value) { var sha1 = new SHA1Managed(); sha1.ComputeHash(value); return sha1.Hash; }
private static string GetSha1(string value) { var data = Encoding.ASCII.GetBytes(value); var hashData = new SHA1Managed().ComputeHash(data); return hashData.Aggregate(string.Empty, (current, b) => current + b.ToString("X2")); }
static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("You need to specify a filename as a single argument"); } else { string file = args[0]; if (File.Exists(file) == false) { Console.WriteLine("Argument is not a valid filename"); } else { FileStream fs = new FileStream(@file, FileMode.Open); using (SHA1Managed sha1 = new SHA1Managed()) { byte[] hash = sha1.ComputeHash(fs); StringBuilder sb = new StringBuilder(hash.Length); foreach (byte b in hash) { sb.AppendFormat("{0:X2}", b); } Console.WriteLine(sb.ToString()); } } } }
public override string Transform(string key) { SHA1Managed sh = new SHA1Managed(); byte[] data = sh.ComputeHash(Encoding.Unicode.GetBytes(key)); return Convert.ToBase64String(data, Base64FormattingOptions.None); }
internal static string CalculateSHA1(string text) { SHA1Managed s = new SHA1Managed(); UTF8Encoding enc = new UTF8Encoding(); s.ComputeHash(enc.GetBytes(text.ToCharArray())); return BitConverter.ToString(s.Hash).Replace("-", ""); }
}/* private string Hash(byte[] buffer) { SHA1Managed sha1 = new SHA1Managed(); byte[] hashBytes = sha1.ComputeHash(buffer); return BufferToString(hashBytes); } private string Hash(FileStream stream) { SHA1Managed sha1 = new SHA1Managed(); byte[] hashBytes = sha1.ComputeHash(stream); return BufferToString(hashBytes); } // TODO: refactor, this is a copy/paste from ObjectForScripting private string Hash(FileInfo fileInfo) { SHA1Managed sha1 = new SHA1Managed(); FileStream inFile = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); return Hash(inFile); }*/ private string FileHash(byte[] buffer) { MemoryStream ms = new MemoryStream(buffer,false); SHA1Managed sha1 = new SHA1Managed(); return string.Concat(from b in sha1.ComputeHash(ms) select b.ToString("X2")); }
public string GenerateSha1Hash(string str) { SHA1Managed sha1 = new SHA1Managed(); var hash = sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str)); string hex = BitConverter.ToString(hash); return hex.Replace("-", "").ToLower(); }
private string HashValues(string Value1, string Value2, string HashingAlgorithm) { string sHashingAlgorithm = ""; if (String.IsNullOrEmpty(HashingAlgorithm)) sHashingAlgorithm = "SHA-1"; else sHashingAlgorithm = HashingAlgorithm; byte[] arrByte; if (sHashingAlgorithm == "SHA-1") { SHA1Managed hash = new SHA1Managed(); arrByte = hash.ComputeHash(ASCIIEncoding.ASCII.GetBytes(Value1 + Value2)); } else { SHA256Managed hash = new SHA256Managed(); arrByte = hash.ComputeHash(ASCIIEncoding.ASCII.GetBytes(Value1 + Value2)); } string s = ""; for (int i = 0; i < arrByte.Length; i++) { s += arrByte[i].ToString("x2"); } return s; }
public bool CompareStringToHash(string s, string hash) { var hashData = Convert.FromBase64String(hash); // First, pluck the four-byte salt off of the end of the hash var saltData = new byte[SaltSize]; Array.Copy(hashData, hashData.Length - saltData.Length, saltData, 0, saltData.Length); var passwordData = Encoding.UTF8.GetBytes(s); // Append the salt to the end of the original var saltedPasswordData = new byte[passwordData.Length + saltData.Length]; Array.Copy(passwordData, 0, saltedPasswordData, 0, passwordData.Length); Array.Copy(saltData, 0, saltedPasswordData, passwordData.Length, saltData.Length); // Create a new SHA-1 instance and compute the hash var sha = new SHA1Managed(); var newHashData = sha.ComputeHash(saltedPasswordData); // Add salt bytes onto end of the original hash for storage var newHashSaltData = new byte[newHashData.Length + saltData.Length]; Array.Copy(newHashData, 0, newHashSaltData, 0, newHashData.Length); Array.Copy(saltData, 0, newHashSaltData, newHashData.Length, saltData.Length); // Compare and return return (Convert.ToBase64String(hashData).Equals(Convert.ToBase64String(newHashSaltData))); }
/// <summary> /// Computes hash for password /// </summary> /// <param name="password">Password to encrypt</param> /// <returns>Encrypted password</returns> public static string ComputeHash(string password) { SHA1Managed sha = new SHA1Managed(); byte[] data = Encoding.Unicode.GetBytes(password); string hash = Convert.ToBase64String(sha.ComputeHash(data)); return hash; }
public static SeekableCryptoStream CreateUltraSecureStream(string pswd, int seglen, Stream btr) { SHA1 mt = new SHA1Managed(); byte[] hash = mt.ComputeHash(Encoding.UTF8.GetBytes(pswd)); List<char> tlist = new List<char>(pswd.ToCharArray()); tlist.Reverse(); string reversed = new string(tlist.ToArray()); //Create stream 0 Aes rdale = new AesManaged(); Rfc2898DeriveBytes derivitive = new Rfc2898DeriveBytes(reversed + pswd + hash[5].ToString(), hash); rdale.Key = derivitive.GetBytes(32); derivitive = new Rfc2898DeriveBytes(hash, Encoding.Unicode.GetBytes(pswd), 16); rdale.IV = derivitive.GetBytes(16); SeekableCryptoStream mstr = new SeekableCryptoStream(new SegmentReader(btr, rdale, seglen)); //Create stream 1 Aes secondale = new AesManaged(); derivitive = new Rfc2898DeriveBytes(pswd + reversed + hash[2].ToString(), Encoding.BigEndianUnicode.GetBytes(pswd)); secondale.Key = derivitive.GetBytes(32); derivitive = new Rfc2898DeriveBytes(hash, Encoding.Unicode.GetBytes(pswd), 16); secondale.IV = derivitive.GetBytes(16); //No clue why this has to be less than 16384, but it does.... Console.WriteLine("WARNING: Insecure test algorithm. Uncomment line below to secure it"); //TODO: DOESN't work with 2 for some reason.... mstr = new SeekableCryptoStream(new SegmentReader(mstr, rdale, seglen)); return mstr; }
public static Hash FromFile(string path) { SHA1 sha = new SHA1Managed(); byte[] arr = FileUtils.GetAllBytes(path); byte[] result = sha.ComputeHash(arr); return new Hash(result); }
static void GenKey(string baseName, out byte[] desKey, out byte[] desIV) { byte[] secretBytes = { 6, 29, 66, 6, 2, 68, 4, 7, 70 }; byte[] baseNameBytes = new ASCIIEncoding().GetBytes(baseName); byte[] hashBytes = new byte[secretBytes.Length + baseNameBytes.Length]; // copy secret byte to start of hash array for (int i = 0; i < secretBytes.Length; i++) { hashBytes[i] = secretBytes[i]; } // copy filename byte to end of hash array for (int i = 0; i < baseNameBytes.Length; i++) { hashBytes[i + secretBytes.Length] = baseNameBytes[i]; } SHA1Managed sha = new SHA1Managed(); // run the sha1 hash byte[] hashResult = sha.ComputeHash(hashBytes); desKey = new byte[8]; desIV = new byte[8]; for (int i = 0; i < 8; i++) { desKey[i] = hashResult[i]; desIV[i] = hashResult[8 + i]; } }
public bool EncryptFile(string filePath, string savePath, string keyStr) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); if (keyStr == "") keyStr = key; FileStream fs = File.OpenRead(filePath); byte[] inputByteArray = new byte[fs.Length]; fs.Read(inputByteArray, 0, (int)fs.Length); fs.Close(); byte[] keyByteArray = Encoding.Default.GetBytes(keyStr); SHA1 ha = new SHA1Managed(); byte[] hb = ha.ComputeHash(keyByteArray); sKey = new byte[8]; sIV = new byte[8]; for (int i = 0; i < 8; i++) sKey[i] = hb[i]; for (int i = 8; i < 16; i++) sIV[i - 8] = hb[i]; des.Key = sKey; des.IV = sIV; MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); fs = File.OpenWrite(savePath); foreach (byte b in ms.ToArray()) { fs.WriteByte(b); } fs.Close(); cs.Close(); ms.Close(); return true; }
public static string SHA1(string stringToHash) { System.Security.Cryptography.SHA1Managed sha1Obj = new System.Security.Cryptography.SHA1Managed(); byte[] bytesToHash = System.Text.Encoding.UTF8.GetBytes(stringToHash); bytesToHash = sha1Obj.ComputeHash(bytesToHash); return(BitConverter.ToString(bytesToHash).Replace("-", "").ToUpper()); }
public virtual string GenerateId(string handle) { var sha = new SHA1Managed(); var handleBytes = Encoding.UTF8.GetBytes(handle); var hashBytes = sha.ComputeHash(handleBytes); return BitConverter.ToString(hashBytes, 0, 9).Replace("-", ""); }
/// <summary> /// Empaqquete un DIscoInfo /// </summary> /// <param name="info">DicoInfo</param> /// <returns>Ampaquetage</returns> public static string DiscoInfoToVersion(DiscoInfo info) { StringBuilder builder = new StringBuilder(256); DiscoIdentity[] identities = info.GetIdentities(); string[] ids = new string[identities.Length]; for (int i = 0; i < identities.Length; i++) { ids[i] = string.Format("{0}/{1}", identities[i].Category, identities[i].Type); } Array.Sort(ids); foreach (string id in ids) { builder.AppendFormat("{0}<", id); } DiscoFeature[] features = info.GetFeatures(); string[] feas = new string[features.Length]; for (int i = 0; i < features.Length; i++) { feas[i] = features[i].Var; } Array.Sort(feas); foreach (string fea in feas) { builder.AppendFormat("{0}<", fea); } SHA1Managed sha1 = new SHA1Managed(); byte[] hash = sha1.ComputeHash(Encoding.Unicode.GetBytes(builder.ToString())); return Convert.ToBase64String(hash); }
/// <summary> /// SHA1非对称加密.用于密码加密,使用SHA1Managed类产生长度为160位哈希值. /// </summary> /// <param name="text">传入一个任意长字符串.</param> /// <returns>返回长度为28字节的字符串.</returns> public static string GetSHA1(string text) { byte[] byteSHA1 = System.Text.Encoding.UTF8.GetBytes(text); var sha1 = new SHA1Managed(); byte[] result = sha1.ComputeHash(byteSHA1); return Convert.ToBase64String(result); }
public WardenRandom(byte[] seed) { Data1 = new byte[0x14]; Data2 = new byte[0x14]; Data3 = new byte[0x14]; int length1 = (int)seed.Length >> 1; int length2 = seed.Length - length1; byte[] seed1 = new byte[length1]; byte[] seed2 = new byte[length2]; for (int i = 0; i < length1; i++) seed1[i] = seed[i]; for (int i = 0; i < length2; i++) seed2[i] = seed[i + length1]; SHA1 sha = new SHA1Managed(); Data2 = sha.ComputeHash(seed1); Data3 = sha.ComputeHash(seed2); sha.Initialize(); sha.TransformBlock(Data2, 0, Data2.Length, Data2, 0); sha.TransformBlock(Data1, 0, Data1.Length, Data1, 0); sha.TransformFinalBlock(Data3, 0, Data3.Length); Data1 = sha.Hash; sha.Initialize(); }
// Seeds PRNG with first 32 bits of hashed input from tf_randomSeed textbox private void glitchSpeak_Click(object sender, RoutedEventArgs e) { HashAlgorithm hasher = new System.Security.Cryptography.SHA1Managed(); var bytes = hasher.ComputeHash(Encoding.Unicode.GetBytes(tf_randomSeed.Text)); var hash = string.Join("", bytes.Select(x => x.ToString("x2")).ToArray()); rand = new Random(Convert.ToInt32(hash.Substring(0, 8), 16)); }
//password hashing private string GetHash() { using (var hash = new System.Security.Cryptography.SHA1Managed()) { var hashbytes = System.Text.Encoding.UTF8.GetBytes(Password); return(Convert.ToBase64String(hash.ComputeHash(hashbytes))); } }
public static string computeSHA1Hash(string val) { if (val.Equals("")) { return(""); } byte[] data = System.Text.Encoding.UTF8.GetBytes(val); System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1Managed(); byte[] res = sha.ComputeHash(data); return(System.BitConverter.ToString(res).Replace("-", "").ToUpper()); }
public static void Check(out bool isValid, out bool expired, out int siteQty) { siteQty = 0; isValid = false; expired = true; HiContext current = HiContext.Current; XmlDocument xmlDocument = HiCache.Get("FileCache_CommercialLicenser") as XmlDocument; SiteSettings masterSettings = SettingsManager.GetMasterSettings(true); if (xmlDocument == null) { string text = (current.Context != null) ? current.Context.Request.MapPath("~/config/Certificates.cer") : System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "config\\Certificates.cer"); if (!System.IO.File.Exists(text)) { return; } xmlDocument = new XmlDocument(); xmlDocument.LoadXml(System.IO.File.ReadAllText(text)); HiCache.Max("FileCache_CommercialLicenser", xmlDocument, new CacheDependency(text)); } XmlNode xmlNode = xmlDocument.DocumentElement.SelectSingleNode("//Host"); XmlNode xmlNode2 = xmlDocument.DocumentElement.SelectSingleNode("//LicenseDate"); XmlNode xmlNode3 = xmlDocument.DocumentElement.SelectSingleNode("//Expires"); XmlNode xmlNode4 = xmlDocument.DocumentElement.SelectSingleNode("//SiteQty"); XmlNode xmlNode5 = xmlDocument.DocumentElement.SelectSingleNode("//Signature"); //if (string.Compare(xmlNode.InnerText, masterSettings.SiteUrl, true, System.Globalization.CultureInfo.InvariantCulture) == 0) //{ //} string s = string.Format(System.Globalization.CultureInfo.InvariantCulture, "Host={0}&Expires={1}&SiteQty={2}&LicenseDate={3}", new object[] { masterSettings.SiteUrl, xmlNode3.InnerText, xmlNode4.InnerText, xmlNode2.InnerText }); using (System.Security.Cryptography.RSACryptoServiceProvider rSACryptoServiceProvider = new System.Security.Cryptography.RSACryptoServiceProvider()) { rSACryptoServiceProvider.FromXmlString(LicenseHelper.GetPublicKey()); System.Security.Cryptography.RSAPKCS1SignatureDeformatter rSAPKCS1SignatureDeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(rSACryptoServiceProvider); rSAPKCS1SignatureDeformatter.SetHashAlgorithm("SHA1"); byte[] rgbSignature = System.Convert.FromBase64String(xmlNode5.InnerText); byte[] rgbHash = new System.Security.Cryptography.SHA1Managed().ComputeHash(System.Text.Encoding.UTF8.GetBytes(s)); isValid = rSAPKCS1SignatureDeformatter.VerifySignature(rgbHash, rgbSignature); isValid = true; } expired = (System.DateTime.Now > System.DateTime.Parse(xmlNode3.InnerText)); if (isValid && !expired) { int.TryParse(xmlNode4.InnerText, out siteQty); } }
public static string Hash(string strToEncrypt) { System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding(); byte[] bytes = ue.GetBytes(strToEncrypt); // encrypt bytes var sha1 = new System.Security.Cryptography.SHA1Managed(); byte[] hashBytes = sha1.ComputeHash(bytes); var sHash = System.Convert.ToBase64String(hashBytes); return(sHash); }
public static string SHA1file(byte[] buffer) { try { System.Security.Cryptography.SHA1Managed Sha1 = new System.Security.Cryptography.SHA1Managed(); byte[] retVal = Sha1.ComputeHash(buffer); return(System.Convert.ToBase64String(retVal)); } catch (Exception ex) { throw new Exception("SHA1file() fail, error:" + ex.Message); } }
public static string SHA1(string input) { System.Security.Cryptography.SHA1Managed sha1 = new System.Security.Cryptography.SHA1Managed(); byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input)); sha1.Dispose(); StringBuilder sb = new StringBuilder(hash.Length * 2); foreach (byte b in hash) // can be "x2" if you want lowercase { sb.Append(b.ToString("x2")); } return(sb.ToString()); }
private ResmgrNative() { //初始化本地URL #if UNITY_ANDROID && !UNITY_EDITOR localurl = Application.streamingAssetsPath; //Android 比较特别 #else localurl = "file://" + Application.streamingAssetsPath; //此url 在 windows 及 WP IOS 可以使用 #endif cacheurl = System.IO.Path.Combine(Application.persistentDataPath, "vercache"); sha1 = new System.Security.Cryptography.SHA1Managed(); taskState = new TaskState(); }
public string Encrypt(string password) { var sha1 = new System.Security.Cryptography.SHA1Managed(); var plaintextBytes = Encoding.UTF8.GetBytes(password); var hashBytes = sha1.ComputeHash(plaintextBytes); var sb = new StringBuilder(); foreach (var hashByte in hashBytes) { sb.AppendFormat("{0:x2}", hashByte); } return(sb.ToString().ToUpper()); }
public static string SHA1file(string file) { try { FileStream fs = new FileStream(file, FileMode.Open); System.Security.Cryptography.SHA1Managed Sha1 = new System.Security.Cryptography.SHA1Managed(); byte[] retVal = Sha1.ComputeHash(fs); fs.Close(); return(System.Convert.ToBase64String(retVal)); } catch (Exception ex) { throw new Exception("SHA1file() fail, error:" + ex.Message); } }
/// <summary> /// 获取字符串的Hash字符 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string ToHashText(this string str) { if (String.IsNullOrEmpty(str)) { return(String.Empty); } using (var sha1 = new System.Security.Cryptography.SHA1Managed()) { byte[] textData = System.Text.Encoding.UTF8.GetBytes(str); byte[] hash = sha1.ComputeHash(textData); return(BitConverter.ToString(hash).Replace("-", String.Empty)); } }
private string HashFiles(IEnumerable <VstsFile> files) { StringBuilder builder = new StringBuilder(); foreach (var f in files.OrderBy(f => f.Path)) { builder.Append(f.Blob.Id); builder.Append(f.Path); } var bytes = Encoding.UTF8.GetBytes(builder.ToString()); var hasher = new System.Security.Cryptography.SHA1Managed(); var hash = hasher.ComputeHash(bytes); //really we want to encode as base36 return(System.BitConverter.ToString(hash).Replace("-", "").ToLower()); }
public byte[] GetPublicKeyToken() { if (public_key == null || public_key_token != null) { return(public_key_token); } HashAlgorithm ha = new System.Security.Cryptography.SHA1Managed(); byte[] hash = ha.ComputeHash(public_key); // we need the last 8 bytes in reverse order public_key_token = new byte[8]; Buffer.BlockCopy(hash, hash.Length - 8, public_key_token, 0, 8); Array.Reverse(public_key_token, 0, 8); return(public_key_token); }
internal static string getSha1Hash(string text) { if (String.IsNullOrEmpty(text)) { return(String.Empty); } using (var sha1 = new System.Security.Cryptography.SHA1Managed()) { byte[] textData = Encoding.UTF8.GetBytes(text); byte[] hash = sha1.ComputeHash(textData); return(BitConverter.ToString(hash).Replace("-", String.Empty)); } }
public static string GetSHA1Hash(string str) { Encoder enc = System.Text.Encoding.Unicode.GetEncoder(); byte[] unicodeText = new byte[str.Length * 2]; enc.GetBytes(str.ToCharArray(), 0, str.Length, unicodeText, 0, true); System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1Managed(); byte[] result = sha.ComputeHash(unicodeText); StringBuilder sb = new StringBuilder(); for (int i = 0; i < result.Length; i++) { sb.Append(result[i].ToString()); } return(sb.ToString()); }
private unsafe static void SHATransform(uint *expandedBuffer, uint *state, byte *block) { uint num = *state; uint num2 = state[1]; uint num3 = state[2]; uint num4 = state[3]; uint num5 = state[4]; Utils.DWORDFromBigEndian(expandedBuffer, 16, block); SHA1Managed.SHAExpand(expandedBuffer); int i; for (i = 0; i < 20; i += 5) { num5 += (num << 5 | num >> 27) + (num4 ^ (num2 & (num3 ^ num4))) + expandedBuffer[i] + 1518500249U; num2 = (num2 << 30 | num2 >> 2); num4 += (num5 << 5 | num5 >> 27) + (num3 ^ (num & (num2 ^ num3))) + expandedBuffer[i + 1] + 1518500249U; num = (num << 30 | num >> 2); num3 += (num4 << 5 | num4 >> 27) + (num2 ^ (num5 & (num ^ num2))) + expandedBuffer[i + 2] + 1518500249U; num5 = (num5 << 30 | num5 >> 2); num2 += (num3 << 5 | num3 >> 27) + (num ^ (num4 & (num5 ^ num))) + expandedBuffer[i + 3] + 1518500249U; num4 = (num4 << 30 | num4 >> 2); num += (num2 << 5 | num2 >> 27) + (num5 ^ (num3 & (num4 ^ num5))) + expandedBuffer[i + 4] + 1518500249U; num3 = (num3 << 30 | num3 >> 2); } while (i < 40) { num5 += (num << 5 | num >> 27) + (num2 ^ num3 ^ num4) + expandedBuffer[i] + 1859775393U; num2 = (num2 << 30 | num2 >> 2); num4 += (num5 << 5 | num5 >> 27) + (num ^ num2 ^ num3) + expandedBuffer[i + 1] + 1859775393U; num = (num << 30 | num >> 2); num3 += (num4 << 5 | num4 >> 27) + (num5 ^ num ^ num2) + expandedBuffer[i + 2] + 1859775393U; num5 = (num5 << 30 | num5 >> 2); num2 += (num3 << 5 | num3 >> 27) + (num4 ^ num5 ^ num) + expandedBuffer[i + 3] + 1859775393U; num4 = (num4 << 30 | num4 >> 2); num += (num2 << 5 | num2 >> 27) + (num3 ^ num4 ^ num5) + expandedBuffer[i + 4] + 1859775393U; num3 = (num3 << 30 | num3 >> 2); i += 5; } while (i < 60) { num5 += (num << 5 | num >> 27) + ((num2 & num3) | (num4 & (num2 | num3))) + expandedBuffer[i] + 2400959708U; num2 = (num2 << 30 | num2 >> 2); num4 += (num5 << 5 | num5 >> 27) + ((num & num2) | (num3 & (num | num2))) + expandedBuffer[i + 1] + 2400959708U; num = (num << 30 | num >> 2); num3 += (num4 << 5 | num4 >> 27) + ((num5 & num) | (num2 & (num5 | num))) + expandedBuffer[i + 2] + 2400959708U; num5 = (num5 << 30 | num5 >> 2); num2 += (num3 << 5 | num3 >> 27) + ((num4 & num5) | (num & (num4 | num5))) + expandedBuffer[i + 3] + 2400959708U; num4 = (num4 << 30 | num4 >> 2); num += (num2 << 5 | num2 >> 27) + ((num3 & num4) | (num5 & (num3 | num4))) + expandedBuffer[i + 4] + 2400959708U; num3 = (num3 << 30 | num3 >> 2); i += 5; } while (i < 80) { num5 += (num << 5 | num >> 27) + (num2 ^ num3 ^ num4) + expandedBuffer[i] + 3395469782U; num2 = (num2 << 30 | num2 >> 2); num4 += (num5 << 5 | num5 >> 27) + (num ^ num2 ^ num3) + expandedBuffer[i + 1] + 3395469782U; num = (num << 30 | num >> 2); num3 += (num4 << 5 | num4 >> 27) + (num5 ^ num ^ num2) + expandedBuffer[i + 2] + 3395469782U; num5 = (num5 << 30 | num5 >> 2); num2 += (num3 << 5 | num3 >> 27) + (num4 ^ num5 ^ num) + expandedBuffer[i + 3] + 3395469782U; num4 = (num4 << 30 | num4 >> 2); num += (num2 << 5 | num2 >> 27) + (num3 ^ num4 ^ num5) + expandedBuffer[i + 4] + 3395469782U; num3 = (num3 << 30 | num3 >> 2); i += 5; } *state += num; state[1] += num2; state[2] += num3; state[3] += num4; state[4] += num5; }
public static string GetHashSHA1(Stream data) { System.Security.Cryptography.SHA1Managed sha = new System.Security.Cryptography.SHA1Managed(); byte[] result = sha.ComputeHash(data); return(Convert.ToBase64String(result)); }
// Получить код хеш устройства С: public static byte[] HashHardvare() { System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1Managed(); return(sha.ComputeHash(HardwareKey())); }
/// <summary> /// Gets SHA1 hash of a byte array /// </summary> /// <param name="buffer">Byte array</param> /// <returns>SHA1 hash as string</returns> public static string SHA1(byte[] buffer) { SHA1 sha1 = new SHA1CryptoServiceProvider(); return(BitConverter.ToString(sha1.ComputeHash(buffer)).Replace("-", "")); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token) { if (!request.Headers.Contains("Signature") && !request.Headers.Contains("SignatureCertChainUrl")) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)); } var signatureCertChainUrl = request.Headers.GetValues("SignatureCertChainUrl").First().Replace("/../", "/"); if (string.IsNullOrWhiteSpace(signatureCertChainUrl)) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)); } var certUrl = new Uri(signatureCertChainUrl); if (!((certUrl.Port == 443 && certUrl.IsDefaultPort) && certUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase) && certUrl.Host.Equals("s3.amazonaws.com", StringComparison.OrdinalIgnoreCase) && certUrl.AbsolutePath.StartsWith("/echo.api/"))) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)); } // download the certificate using (var web = new System.Net.WebClient()) { var certificate = web.DownloadData(certUrl); var cert = new X509Certificate2(certificate); var expiryDate = DateTime.MinValue; var effectiveDate = DateTime.MinValue; if (DateTime.TryParse(cert.GetExpirationDateString(), out expiryDate) && expiryDate < DateTime.UtcNow && DateTime.TryParse(cert.GetEffectiveDateString(), out effectiveDate) && effectiveDate < DateTime.UtcNow) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)); } if (!cert.Subject.Contains("CN=echo-api.amazon.com")) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)); } var signatureString = request.Headers.GetValues("Signature").First(); byte[] signature = Convert.FromBase64String(signatureString); using (var sha1 = new System.Security.Cryptography.SHA1Managed()) { var body = await request.Content.ReadAsStringAsync(); var data = sha1.ComputeHash(Encoding.UTF8.GetBytes(body)); var rsa = (RSACryptoServiceProvider)cert.PublicKey.Key; if (!rsa.VerifyHash(data, CryptoConfig.MapNameToOID("SHA1"), signature)) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)); } } } return(await base.SendAsync(request, token)); }
private string step_3(string filename) //Core validation { string[] SUPPORTED_TRANSFORMS = { "http://www.w3.org/TR/2001/REC-xml-c14n-20010315", "http://www.w3.org/2000/09/xmldsig#base64", }; string[] SUPPORTED_DIGEST_METHOD = { "http://www.w3.org/2001/04/xmlenc#sha512 ", "http://www.w3.org/2001/04/xmldsig-more#sha384", "http://www.w3.org/2001/04/xmlenc#sha256", "http://www.w3.org/2001/04/xmldsig-more#sha224", "http://www.w3.org/2000/09/xmldsig#sha1", }; XmlDocument xades = new XmlDocument(); xades.Load(filename); var namespaceId = new XmlNamespaceManager(xades.NameTable); namespaceId.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#"); namespaceId.AddNamespace("xades", "http://uri.etsi.org/01903/v1.3.2#"); //check ds:SignedInfo and ds:Manifest XmlNode signedInfoN = xades.SelectSingleNode(@"//ds:SignedInfo", namespaceId); XmlNodeList referenceElements = signedInfoN.SelectNodes(@"//ds:Reference", namespaceId); //Reference in SignedInfo foreach (XmlNode reference in referenceElements) { String ReferenceURI = reference.Attributes.GetNamedItem("URI").Value; ReferenceURI = ReferenceURI.Substring(1); XmlNode digestMethod = reference.SelectSingleNode("ds:DigestMethod", namespaceId); String digestMethodAlgorithm = digestMethod.Attributes.GetNamedItem("Algorithm").Value; string dsDigestValue = reference.SelectSingleNode("ds:DigestValue", namespaceId).InnerText; if (ReferenceURI.StartsWith("ManifestObject")) { //get Manifest XML and check DigestValue string manifestXML = xades.SelectSingleNode("//ds:Manifest[@Id='" + ReferenceURI + "']", namespaceId).OuterXml; MemoryStream sManifest = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(manifestXML)); XmlDsigC14NTransform t = new XmlDsigC14NTransform(); t.LoadInput(sManifest); HashAlgorithm hash = null; switch (digestMethodAlgorithm) { case "http://www.w3.org/2000/09/xmldsig#sha1": hash = new System.Security.Cryptography.SHA1Managed(); break; case "http://www.w3.org/2001/04/xmlenc#sha256": hash = new System.Security.Cryptography.SHA256Managed(); break; case "http://www.w3.org/2001/04/xmldsig-more#sha384": hash = new System.Security.Cryptography.SHA384Managed(); break; case "http://www.w3.org/2001/04/xmlenc#sha512": hash = new System.Security.Cryptography.SHA512Managed(); break; } if (hash == null) { return("nesprávny hashovací algoritmus " + digestMethodAlgorithm); } byte[] digest = t.GetDigestedOutput(hash); string result = Convert.ToBase64String(digest); Console.WriteLine("-"); Console.WriteLine("Overenie hodnoty podpisu"); Console.WriteLine(result); Console.WriteLine(dsDigestValue); Console.WriteLine("-"); if (!result.Equals(dsDigestValue)) { return("hodnoty DigestValue s výpočtom Manifest sa nezhodujú"); } } } //signed info kanonikalizovat XmlNode checkData = xades.SelectSingleNode(@"//ds:KeyInfo/ds:X509Data/ds:X509Certificate", namespaceId); if (checkData == null) { return("neobsahuje element ds:X509Data"); } byte[] signatureCertificate = Convert.FromBase64String(xades.SelectSingleNode(@"//ds:KeyInfo/ds:X509Data/ds:X509Certificate", namespaceId).InnerText); byte[] signature = Convert.FromBase64String(xades.SelectSingleNode(@"//ds:SignatureValue", namespaceId).InnerText); XmlNode signedInfoNnn = xades.SelectSingleNode(@"//ds:SignedInfo", namespaceId); string signedInfoTransformAlg = xades.SelectSingleNode(@"//ds:SignedInfo/ds:CanonicalizationMethod", namespaceId).Attributes.GetNamedItem("Algorithm").Value; string signedInfoSignatureAlg = xades.SelectSingleNode(@"//ds:SignedInfo/ds:SignatureMethod", namespaceId).Attributes.GetNamedItem("Algorithm").Value; XmlDsigC14NTransform t1 = new XmlDsigC14NTransform(false); XmlDocument pom = new XmlDocument(); pom.LoadXml(signedInfoNnn.OuterXml); t1.LoadInput(pom); byte[] data = ((MemoryStream)t1.GetOutput()).ToArray(); string errMsg = ""; bool res = this.verifySign(signatureCertificate, signature, data, signedInfoSignatureAlg, out errMsg); if (!res) { Console.WriteLine("Error " + errMsg); return(errMsg); } //check Id in ds:Signature XmlNode dsSignatureId = xades.SelectSingleNode("//ds:Signature", namespaceId).Attributes["Id"]; if (dsSignatureId == null) { return("ds:Signature nemá atribút Id"); } //check namespace in ds:Signature XmlNode dsSignatureXmlns = xades.SelectSingleNode("//ds:Signature", namespaceId).Attributes["xmlns:ds"]; if (dsSignatureXmlns == null) { return("ds:Signature nemá špecifikovaný namespace xmlns:ds"); } //check SignatureValue Id XmlNode dsSignatureValueId = xades.SelectSingleNode("//ds:SignatureValue", namespaceId).Attributes["Id"]; if (dsSignatureValueId == null) { return("ds:SignatureValue nemá atribút Id"); } //check reference in ds:SignedInfo XmlNode signedInfo = xades.SelectSingleNode("//ds:SignedInfo", namespaceId); XmlNodeList dsKeyInfoId = signedInfo.SelectNodes("//ds:Reference", namespaceId); if (dsKeyInfoId.Count < 1) { return("ds:SignedInfo neobsahuje ds:Reference"); } String KeyInfo = ""; String SignatureProperties = ""; String SignedProperties = ""; List <string> Manifest = new List <string>(); //get URI foreach (XmlNode ReferenceList in dsKeyInfoId) { if (ReferenceList.Attributes["Id"] == null) { continue; } else if (ReferenceList.Attributes["Id"] != null) { if (ReferenceList.Attributes["Type"].Value.Contains("Object")) { KeyInfo = ReferenceList.Attributes["URI"].Value; KeyInfo = KeyInfo.Substring(1); } else if (ReferenceList.Attributes["Type"].Value.Contains("SignatureProperties")) { SignatureProperties = ReferenceList.Attributes["URI"].Value; SignatureProperties = SignatureProperties.Substring(1); } else if (ReferenceList.Attributes["Type"].Value.Contains("SignedProperties")) { SignedProperties = ReferenceList.Attributes["URI"].Value; SignedProperties = SignedProperties.Substring(1); } else if (ReferenceList.Attributes["Type"].Value.Contains("Manifest")) { String tmp = ReferenceList.Attributes["URI"].Value; tmp = tmp.Substring(1); Manifest.Add(tmp); } } } //check if exist ds:KeyInfo, ds:SignatureProperties, xades:SignedProperties XmlNode ElementKeyInfo = xades.SelectSingleNode("//ds:KeyInfo", namespaceId); XmlNode ElementSignatureProperties = xades.SelectSingleNode("//ds:SignatureProperties", namespaceId); XmlNode ElementSignedProperties = xades.SelectSingleNode("//xades:SignedProperties", namespaceId); if (ElementKeyInfo.Attributes["Id"] == null) { return("ds:Keyinfo nemá atribút Id"); } if (!ElementKeyInfo.Attributes["Id"].Value.Equals(KeyInfo)) { return("ds:Keyinfo, nezhoduje sa Id s URI"); } if (ElementSignatureProperties.Attributes["Id"] == null) { return("ds:SignatureProperties nemá atribút Id"); } if (!ElementSignatureProperties.Attributes["Id"].Value.Equals(SignatureProperties)) { return("ds:SignatureProperties, nezhoduje sa Id s URI"); } if (ElementSignedProperties.Attributes["Id"] == null) { return("xades:SignedProperties nemá atribút Id"); } if (!ElementSignedProperties.Attributes["Id"].Value.Equals(SignedProperties)) { return("xades:SignedProperties, nezhoduje sa Id s URI"); } //check if exist ds:Manifest XmlNodeList ElementManifest = xades.SelectNodes("//ds:Manifest", namespaceId); bool flag = false; foreach (XmlNode OneManifest in ElementManifest) { foreach (String ManifestURI in Manifest) { if (OneManifest.Attributes["Id"] == null || !OneManifest.Attributes["Id"].Value.Equals(ManifestURI)) { flag = true; } } } if (!flag) { return("ds:Manifest nemá atribút Id alebo sa nezhoduje Id s URI"); } //check ds:KeyInfo Id if (ElementKeyInfo.Attributes["Id"] == null) { return("element ds:KeyInfo nemá atribút Id"); } //check ds:KeyInfo elements XmlNode X509Data = ElementKeyInfo.SelectSingleNode("//ds:X509Data", namespaceId); if (X509Data == null) { return("ds:KeyInfo neobsahuje element ds:X509Data"); } if (X509Data.ChildNodes.Count < 3) { return(" chýbajú podelementy pre ds:X509Data"); } //check ds:KeyInfo values XmlNodeList elemList = X509Data.ChildNodes; byte[] bytes; var cert = new X509Certificate2(); String IssuerSerialFirst = ""; String IssuerSerialSecond = ""; String SubjectName = ""; for (int i = 0; i < elemList.Count; i++) { switch (elemList[i].Name) { case "ds:X509Certificate": bytes = Convert.FromBase64String(elemList[i].InnerText); cert = new X509Certificate2(bytes); break; case "ds:X509IssuerSerial": if (elemList[i].HasChildNodes) { IssuerSerialFirst = elemList[i].FirstChild.InnerText; IssuerSerialSecond = elemList[i].LastChild.InnerText; } break; case "ds:X509SubjectName": SubjectName = elemList[i].InnerText; break; } } BigInteger hex = BigInteger.Parse(cert.SerialNumber, NumberStyles.AllowHexSpecifier); if (!cert.Subject.Equals(SubjectName)) { return("hodnota ds:X509SubjectName sa nezhoduje s príslušnou hodnotou v certifikáte"); } if (!cert.Issuer.Equals(IssuerSerialFirst)) { return("hodnota ds:X509IssuerName sa nezhoduje s príslušnou hodnotou v certifikáte"); } if (!hex.ToString().Equals(IssuerSerialSecond)) { return("hodnota ds:X509SerialNumber sa nezhoduje s príslušnou hodnotou v certifikáte"); } //check ds:SignatureProperties Id if (ElementSignatureProperties.Attributes["Id"] == null) { return("element ds:SignatureProperties nema atribut Id"); } //check ds:SignatureProperties numbers of elements XmlNodeList elemListSignatureProperties = ElementSignatureProperties.ChildNodes; if (elemListSignatureProperties.Count < 2) { return("ds:SignatureProperties neobsahuje dva elementy"); } //check ds:SignatureProperties elements for (int i = 0; i < elemListSignatureProperties.Count; i++) { if (elemListSignatureProperties[i].FirstChild.Name.Equals("xzep:SignatureVersion") || elemListSignatureProperties[i].FirstChild.Name.Equals("xzep:ProductInfos")) { String tmpTargetValue = elemListSignatureProperties[i].Attributes["Target"].Value; tmpTargetValue = tmpTargetValue.Substring(1); if (!tmpTargetValue.Equals(dsSignatureId.Value)) { return("atribút Target v elemente ds:SignatureProperty nie je nastavený na element ds:Signature"); } } } //check Manifest and Manifest references String ManifestReferenceUri = ""; String algorithmDigestMethod = ""; String algorithmTransforms = ""; String digestValue = ""; bool flag1 = false; for (int i = 0; i < ElementManifest.Count; i++) { //check ds:Manifest Id if (ElementManifest[i].Attributes["Id"] == null) { return("jeden z elementov ds:Manifest nemá atribút Id"); } //check number of reference, ds:Object XmlNodeList ManifestChildNodes = ElementManifest[i].ChildNodes; if (ManifestChildNodes.Count > 1 || ManifestChildNodes.Count < 1) { return("ds:Manifest neobsahuje práve jedenu referenciu"); } if (!ManifestChildNodes[0].Attributes["Type"].Value.Contains("Object")) { return("nezhoduje sa Type v ds:Manifest"); } //check value attribute Type if (ManifestChildNodes[0].Attributes["Type"].Value.Equals("http://www.w3.org/2000/09/xmldsig#Object")) { //check supported ds:Transforms and ds:DigestMethod XmlNodeList ReferenceElementsChild = ManifestChildNodes[0].ChildNodes; for (int l = 0; l < ReferenceElementsChild.Count; l++) { if (ReferenceElementsChild[l].Name.Equals("ds:Transforms")) { algorithmTransforms = ReferenceElementsChild[l].FirstChild.Attributes["Algorithm"].Value; if (!SUPPORTED_TRANSFORMS.Contains(algorithmTransforms)) { return("ds:Transforms neobsahuje podporovaný algoritmus pre daný element podľa profilu XAdES_ZEP"); } } if (ReferenceElementsChild[l].Name.Equals("ds:DigestMethod")) { algorithmDigestMethod = ReferenceElementsChild[l].Attributes["Algorithm"].Value; if (!SUPPORTED_DIGEST_METHOD.Contains(algorithmDigestMethod)) { return("ds:DigestMethod neobsahuje podporovaný algoritmus pre daný element podľa profilu XAdES_ZEP"); } } if (ReferenceElementsChild[l].Name.Equals("ds:DigestValue")) { digestValue = ReferenceElementsChild[l].InnerText; } } ManifestReferenceUri = ManifestChildNodes[0].Attributes["URI"].Value; ManifestReferenceUri = ManifestReferenceUri.Substring(1); //check values ds:Manifest and ds:Object XmlNodeList ObjectElement = xades.SelectNodes("//ds:Object", namespaceId); for (int j = 0; j < ObjectElement.Count; j++) { if (ObjectElement[j].Attributes["Id"] == null) { continue; } if (ObjectElement[j].Attributes["Id"].Value.Equals(ManifestReferenceUri)) { flag1 = true; XmlDsigC14NTransform t = new XmlDsigC14NTransform(); XmlDocument myDoc = new XmlDocument(); myDoc.LoadXml(ObjectElement[i].OuterXml); t.LoadInput(myDoc); Stream s = (Stream)t.GetOutput(typeof(Stream)); byte[] hash; string base64String = ""; switch (algorithmDigestMethod) { case "http://www.w3.org/2001/04/xmldsig#sha1": SHA1 sha1 = SHA1.Create(); hash = sha1.ComputeHash(s); base64String = Convert.ToBase64String(hash); break; case "http://www.w3.org/2001/04/xmlenc#sha256": SHA256 sha256 = SHA256.Create(); hash = sha256.ComputeHash(s); base64String = Convert.ToBase64String(hash); break; case "http://www.w3.org/2001/04/xmldsig-more#sha384": SHA384 sha384 = SHA384.Create(); hash = sha384.ComputeHash(s); base64String = Convert.ToBase64String(hash); break; case "http://www.w3.org/2001/04/xmlenc#sha512": SHA512 sha512 = SHA512.Create(); hash = sha512.ComputeHash(s); base64String = Convert.ToBase64String(hash); break; } Console.WriteLine("-"); Console.WriteLine("Overenie hodnoty ds:DigestValue"); Console.WriteLine("First " + base64String); Console.WriteLine("Second " + digestValue); Console.WriteLine("-"); } } if (!flag1) { return("odkaz z ds:Manifest na ds:Object sa nezhoduje"); } flag1 = false; } else { return("ds:Reference, hodnota atribútu Type sa neoverila voči profilu XADES_ZEP"); } } return("OK"); }