public CtVerifier(byte[] publicKey) { var key = DecodeSubjectPublicKeyInfo(publicKey); if (key == null) { throw new ArgumentException("Could not decode public key.", nameof(publicKey)); } _key = key; using (var sha = new SHA256Cng()) { LogId = sha.ComputeHash(publicKey); } }
private void btDecode_Click(object sender, RoutedEventArgs e) { Passphrase pass = new Passphrase(); pass.Owner = this; pass.ShowDialog(); byte[] iv = new byte[16]; byte[] publicAndPrivate = File.ReadAllBytes(@"C:\Users\Nastya\Desktop\Университет\ЗПиД\ЗПиД6\RSAЗакрытый.txt"); byte[] publicKey = File.ReadAllBytes(@"C:\Users\Nastya\Desktop\Университет\ЗПиД\ЗПиД6\RSAОткрытый.txt");//6 2 0 0 0 164 AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); SHA256 sha256 = new SHA256Cng(); byte[] entrophy = sha256.ComputeHash(Encoding.UTF8.GetBytes(pass.pbPass.Password)); if (rbDeSign.IsChecked == true) { Verify(publicKey, dataText); } else { /* byte[] temp = Encoding.UTF8.GetBytes(pass.pbPass.Password); * byte[] key = sha256.ComputeHash(temp); * temp = Decrypt(publicAndPrivate, aes, key, iv, CipherMode.CBC, PaddingMode.None);*/ byte[] privateKey = ProtectedData.Unprotect(publicAndPrivate, entrophy, DataProtectionScope.CurrentUser); byte[] data = File.ReadAllBytes((@"C:\Users\Nastya\Desktop\Университет\ЗПиД\ЗПиД6\RSAШифр.txt")); if (rbSignAndDecode.IsChecked == true) { Verify(publicKey, data); } byte[] text = new byte[data.Length - 128]; // Array.Copy(temp, privateKey, 596); byte[] AsymKey = new byte[128]; byte[] SymKey; for (int i = data.Length - 128, j = 0; i < data.Length; i++, j++) { AsymKey[j] = data[i]; } Array.Copy(data, text, data.Length - 128); using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keySize)) { rsa.ImportCspBlob(privateKey); SymKey = rsa.Decrypt(AsymKey, false); } byte[] DeText = Decrypt(text, aes, SymKey, iv, CipherMode.CBC, PaddingMode.None); string result = Encoding.UTF8.GetString(DeText); File.WriteAllText(@"C:\Users\Nastya\Desktop\Университет\ЗПиД\ЗПиД6\RSAРезультат.txt", result, Encoding.UTF8); MessageBox.Show("Выполнено!"); } }
public ActionResult Unlock(UnlockerModel model) { var algorithm = new SHA256Cng(); var unicoding = new UnicodeEncoding(); var hashed = unicoding.GetString(algorithm.ComputeHash(unicoding.GetBytes(model.Passphrase))); if (hashed == "嘃ᥐ倹⦦듑ꈳ囬쀺诫谾臭ᰠ屯") { FormsAuthentication.SetAuthCookie("Manager", false); var url = Handy.BaseUrl() + (model.ReturnUrl ?? Url.Action("Unlock")); return(Redirect(url)); } ModelState.AddModelError("AuthenticationFailed", "Wrong Passphrase"); return(View()); }
public string ResetPassword(string email, string newPassword) { var sha2 = new SHA256Cng(); var paramList = new List <SqlParameter> { new SqlParameter("@pass", Convert.ToBase64String(sha2.ComputeHash(Encoding.ASCII.GetBytes(newPassword)))), new SqlParameter("@email", email) }; var rowsAffected = ExecuteNonQuery("Update [User] Set [Password] = @pass WHERE Email = @email", paramList); if (rowsAffected == 1) { return(newPassword); } return(null); }
// Token: 0x060010B6 RID: 4278 RVA: 0x00062130 File Offset: 0x00060330 internal static ulong GetHash(byte[] bytes) { ulong result; using (SHA256Cng sha256Cng = new SHA256Cng()) { byte[] array = sha256Cng.ComputeHash(bytes); ulong num = 0UL; for (int i = 0; i < 8; i++) { num <<= 8; num |= (ulong)array[i]; } result = num; } return(result); }
public static byte[] ComputeSHA256(IList <string> parameters) { using (var ms = new MemoryStream()) { using (var bw = new BinaryWriter(ms)) { foreach (string parameter in parameters) { bw.Write(parameter); // also writes the length as a prefix; unambiguous } bw.Flush(); using (SHA256Cng sha256 = new SHA256Cng()) { byte[] retVal = sha256.ComputeHash(ms.GetBuffer(), 0, checked ((int)ms.Length)); return(retVal); } } } }
private void Button5_Click(object sender, EventArgs e) { // read file path from TextBox3.Text var FileStream = new FileStream(path: TextBox3.Text, mode: FileMode.Open, access: FileAccess.Read); RijndaelManaged AES = new RijndaelManaged(); SHA256Cng SHA256 = new SHA256Cng(); // read key from TextBox4.Text AES.Key = SHA256.ComputeHash(Encoding.ASCII.GetBytes(TextBox4.Text)); AES.Mode = CipherMode.ECB; // cryptostream starts here var cryptoStream = new CryptoStream(FileStream, AES.CreateDecryptor(), CryptoStreamMode.Read); // reading decrypted cryptostream and saves into video.mp4 VlcControl1.Play(cryptoStream); }
// Token: 0x060007AA RID: 1962 RVA: 0x0003A52C File Offset: 0x0003872C static Canary() { ITopologyConfigurationSession topologyConfigurationSession = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(true, ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromRootOrgScopeSet(), 78, ".cctor", "f:\\15.00.1497\\sources\\dev\\clients\\src\\owa\\bin\\core\\Canary.cs"); byte[] array = ADSystemConfigurationSession.GetRootOrgContainerIdForLocalForest().ObjectGuid.ToByteArray(); byte[] array2 = topologyConfigurationSession.GetDatabasesContainerId().ObjectGuid.ToByteArray(); Canary.adObjectIdsBinary = new byte[array.Length + array2.Length]; array.CopyTo(Canary.adObjectIdsBinary, 0); array2.CopyTo(Canary.adObjectIdsBinary, array.Length); if (ExTraceGlobals.UserContextTracer.IsTraceEnabled(TraceType.DebugTrace)) { using (SHA256Cng sha256Cng = new SHA256Cng()) { byte[] bytes = sha256Cng.ComputeHash(Canary.adObjectIdsBinary); ExTraceGlobals.UserContextTracer.TraceDebug <string, string>(2L, "{0}.Canary(): adObjectIdsBinaryHash={1}", "Owa.Core.Canary", Canary.GetHexString(bytes)); sha256Cng.Clear(); } } }
public static CtLogInfo FindByLogId(byte[] logId) { using (var sha = new SHA256Cng()) { foreach (var log in Logs) { var hash = sha.ComputeHash(log.Key); if (logId.Length != hash.Length) { continue; } if (hash.MemoryCompare(logId)) { return(log); } } } return(null); }
public static HashData ComputeHashes(string fileName) { try { using (FileStream stream = File.OpenRead(fileName)) { using (var bufferedStream = new BufferedStream(stream, 1024 * 32)) { string md5, sha1, sha256; byte[] checksum; using (var md5Cng = new MD5Cng()) { checksum = md5Cng.ComputeHash(bufferedStream); md5 = BitConverter.ToString(checksum).Replace("-", string.Empty); } stream.Seek(0, SeekOrigin.Begin); bufferedStream.Seek(0, SeekOrigin.Begin); using (var sha1Cng = new SHA1Cng()) { checksum = sha1Cng.ComputeHash(bufferedStream); sha1 = BitConverter.ToString(checksum).Replace("-", string.Empty); } stream.Seek(0, SeekOrigin.Begin); bufferedStream.Seek(0, SeekOrigin.Begin); using (var sha256Cng = new SHA256Cng()) { checksum = sha256Cng.ComputeHash(bufferedStream); sha256 = BitConverter.ToString(checksum).Replace("-", string.Empty); } return(new HashData(md5, sha1, sha256)); } } } catch (IOException) { } catch (UnauthorizedAccessException) { } return(null); }
// /// <summary> /// Method to verify password when user login. Entered password will be hashed using input from user plus the salt value /// The hashed password then will be compared with the value in database for validation. /// No longer being used! /// </summary> /// <param name="enteredPassword"></param> /// <param name="storedHash"></param> /// <param name="storedSalt"></param> /// <returns></returns> public static bool VerifyPassword(string enteredPassword, string storedHash, string storedSalt) { byte[] bytes = System.Text.Encoding.UTF8.GetBytes(enteredPassword + storedSalt); SHA256 sha = new SHA256Cng(); // Hash function byte[] hash = sha.ComputeHash(bytes); // Generate hash in bytes // Store the hash value as string with uppercase letters. StringBuilder hashPassword = new StringBuilder(); // To store the hash value foreach (byte b in hash) { hashPassword.Append(b.ToString("X2")); } String hashSaltPassword = hashPassword.ToString(); return(hashSaltPassword.Equals(storedHash)); }
private static byte[] Init() { ITopologyConfigurationSession topologyConfigurationSession = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(true, ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromRootOrgScopeSet(), 112, "Init", "f:\\15.00.1497\\sources\\dev\\clients\\src\\common\\CryptoMessage.cs"); byte[] array = ADSystemConfigurationSession.GetRootOrgContainerIdForLocalForest().ObjectGuid.ToByteArray(); byte[] array2 = topologyConfigurationSession.GetDatabasesContainerId().ObjectGuid.ToByteArray(); byte[] array3 = new byte[array.Length + array2.Length]; array.CopyTo(array3, 0); array2.CopyTo(array3, array.Length); if (ExTraceGlobals.CryptoTracer.IsTraceEnabled(TraceType.DebugTrace)) { using (SHA256Cng sha256Cng = new SHA256Cng()) { byte[] bytes = sha256Cng.ComputeHash(array3); ExTraceGlobals.CryptoTracer.TraceDebug <string, string, string>(0L, "{0}.{1}: adObjectIdsBinaryHash={2}", "Clients.Common.CryptoMessage", "CryptoMessage()", CryptoMessage.GetHexString(bytes)); sha256Cng.Clear(); } } return(array3); }
public static string ComputeSha256Hash(string fileName) { string sha256Hash = null; try { using (FileStream stream = File.OpenRead(fileName)) { using (var bufferedStream = new BufferedStream(stream, 1024 * 32)) { var sha = new SHA256Cng(); byte[] checksum = sha.ComputeHash(bufferedStream); sha256Hash = BitConverter.ToString(checksum).Replace("-", String.Empty); } } } catch (IOException) { } catch (UnauthorizedAccessException) { } return(sha256Hash); }
/// <summary> /// Gets the input string as a SHA256 Base64 encoded string. /// </summary> /// <param name="input">The input to hash.</param> /// <param name="isCaseSensitive">If set to <c>false</c> the function will produce the same value for any casing of input.</param> /// <returns>The hashed value.</returns> public static string GetHashedId(string input, bool isCaseSensitive = false) { // for nulls, return an empty string, else hash. if (input == null) { return(string.Empty); } using (SHA256 hasher = new SHA256Cng()) { string temp = input; if (isCaseSensitive == false) { temp = input.ToUpperInvariant(); } byte[] buffer = hasher.ComputeHash(Encoding.UTF8.GetBytes(temp)); return(new SoapBase64Binary(buffer).ToString()); } }
public static byte[] ComputeSHA256(IList <string> parameters) { byte[] result; using (MemoryStream memoryStream = new MemoryStream()) { using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream)) { foreach (string current in parameters) { binaryWriter.Write(current); } binaryWriter.Flush(); using (SHA256Cng sHA256Cng = new SHA256Cng()) { byte[] array = sHA256Cng.ComputeHash(memoryStream.GetBuffer(), 0, checked ((int)memoryStream.Length)); result = array; } } } return(result); }
// Token: 0x060007B8 RID: 1976 RVA: 0x0003A87C File Offset: 0x00038A7C private static byte[] ComputeHash(byte[] userContextIdBinary, byte[] timeStampBinary, string logonUniqueKey) { int num = 0; byte[] bytes = new UnicodeEncoding().GetBytes(logonUniqueKey); byte[] array = new byte[userContextIdBinary.Length + timeStampBinary.Length + bytes.Length + Canary.adObjectIdsBinary.Length]; userContextIdBinary.CopyTo(array, num); num += userContextIdBinary.Length; timeStampBinary.CopyTo(array, num); num += timeStampBinary.Length; bytes.CopyTo(array, num); num += bytes.Length; Canary.adObjectIdsBinary.CopyTo(array, num); byte[] result; using (SHA256Cng sha256Cng = new SHA256Cng()) { result = sha256Cng.ComputeHash(array); sha256Cng.Clear(); } return(result); }
private static string DecryptAES(string encrypted) { if (string.IsNullOrEmpty(encrypted)) { Logging.LogNullError(nameof(encrypted)); return(null); } try { byte[] key; using (SHA256Cng sha256 = new SHA256Cng()) { key = sha256.ComputeHash(EncryptionKey); } byte[] decryptedData = Convert.FromBase64String(encrypted); decryptedData = SteamKit2.CryptoHelper.SymmetricDecrypt(decryptedData, key); return(Encoding.UTF8.GetString(decryptedData)); } catch (Exception e) { Logging.LogGenericException(e); return(null); } }
private static string EncryptAES(string decrypted) { if (string.IsNullOrEmpty(decrypted)) { ASF.ArchiLogger.LogNullError(nameof(decrypted)); return(null); } try { byte[] key; using (SHA256Cng sha256 = new SHA256Cng()) { key = sha256.ComputeHash(EncryptionKey); } byte[] encryptedData = Encoding.UTF8.GetBytes(decrypted); encryptedData = SteamKit2.CryptoHelper.SymmetricEncrypt(encryptedData, key); return(Convert.ToBase64String(encryptedData)); } catch (Exception e) { ASF.ArchiLogger.LogGenericException(e); return(null); } }
private void Button5_Click(object sender, EventArgs e) { // read file path from TextBox3.Text var FileStream = new FileStream(path: TextBox3.Text, mode: FileMode.Open, access: FileAccess.Read); var streamWrapper = new SeekableStreamWrapper(() => { FileStream.Seek(0, SeekOrigin.Begin); RijndaelManaged AES = new RijndaelManaged(); SHA256Cng SHA256 = new SHA256Cng(); // read key from TextBox4.Text AES.Key = SHA256.ComputeHash(Encoding.ASCII.GetBytes(TextBox4.Text)); AES.Mode = CipherMode.ECB; return(new CryptoStream(FileStream, AES.CreateDecryptor(), CryptoStreamMode.Read, true)); }); videoView1.MediaPlayer = new MediaPlayer(_libVLC) { Media = new Media(_libVLC, new StreamMediaInput(streamWrapper)) }; videoView1.MediaPlayer.Play(); }
public static byte[] GenSHA256StrmHash(Stream Data) { var SHA = new SHA256Cng(); return(SHA.ComputeHash(Data)); }
public string WOL(int resourceId, bool alwaysWake = false) { string returnMessage = string.Empty; var settings = new RDPSettings(); bool deviceIsOnline = DeviceOnline(resourceId); if (deviceIsOnline && alwaysWake == false) { Log.Information("Device found to be online. Will not wake up."); return("Device is online and ready for RDP. Please run the downloaded file called Default.rdp"); } var peerList = GetDevicePeers(resourceId); if (peerList.Count == 0) { Log.Information("Device not online and no peers found."); return("Device does not show online and no peers found. You can try running the Default.rdp file but the device probably can't be turned on."); } var MACList = GetDeviceMACs(resourceId); if (MACList.Count == 0) { Log.Information("MAC Address for device not found. This is required for WOL"); return("Device does not show online and no MAC address was found. You can try running the Default.rdp file but the device probably can't be turned on."); } string macs = String.Join(",", MACList.ToArray()); Dictionary <string, object> scriptInformation = null; var SqlParams = new Dictionary <string, object>() { { "@ScriptName", settings.CMScriptName } }; using (var _sql = new SQL()) { var results = _sql.Invoke(GetScriptQuery, SqlParams); foreach (var result in results) { scriptInformation = result; } } if (scriptInformation == null) { Log.Information("Could not find WOL script"); return("Device does not show online and no script was found to turn it on. You can try running the Default.rdp file but the device probably can't be turned on."); } string scriptParameters = $"<ScriptParameters><ScriptParameter ParameterGroupGuid=\"\" ParameterGroupName=\"PG_\" ParameterName=\"Macs\" ParameterDataType=\"System.String\" ParameterVisibility=\"0\" ParameterType=\"0\" ParameterValue=\"{macs}\"/></ScriptParameters>"; string shaHash = ""; byte[] bytes = Encoding.Unicode.GetBytes(scriptParameters); using (SHA256 sHA = new SHA256Cng()) { byte[] a = sHA.ComputeHash(bytes); StringBuilder stringBuilder = new StringBuilder(); byte[] a2 = a; foreach (byte b in a2) { stringBuilder.Append(b.ToString("x2")); } shaHash = stringBuilder.ToString(); } string scriptXML = string.Format(CultureInfo.InvariantCulture, "<ScriptContent ScriptGuid='{0}'><ScriptVersion>{1}</ScriptVersion><ScriptType>{2}</ScriptType><ScriptHash ScriptHashAlg='SHA256'>{3}</ScriptHash>{4}<ParameterGroupHash ParameterHashAlg='SHA256'>{5}</ParameterGroupHash></ScriptContent>", scriptInformation["ScriptGuid"].ToString(), scriptInformation["ScriptVersion"].ToString(), scriptInformation["ScriptType"].ToString(), scriptInformation["ScriptHash"].ToString(), scriptParameters, shaHash); var scriptXMLBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(scriptXML)); var wmiUtility = new WMIUtility(); var wmiDictionary = new Dictionary <string, object>(); wmiDictionary.Add("Param", scriptXMLBase64); uint scriptType = 135; wmiDictionary.Add("Type", scriptType); List <uint> uintResourceIds = new List <uint>(); foreach (var r in peerList) { uintResourceIds.Add(Convert.ToUInt32(r)); } wmiDictionary.Add("TargetResourceIDs", uintResourceIds.ToArray()); Log.Information("Attempting to run script on these resourceIds {uintResourceIds}", uintResourceIds); var i = wmiUtility.InvokeClassMethod("SMS_ClientOperation", "InitiateClientOperationEx", wmiDictionary); Log.Information("Successfully sent request to start script"); return("Device does not show online so we are attempting to turn it on. You can run the Default.rdp file that was downloaded in 2-3 minutes to log into your computer. Thank you."); }
private string GetImageHash(byte[] image) { var sha256 = new SHA256Cng(); return(Encoding.Default.GetString(sha256.ComputeHash(image))); }
public void Sha256Cng() { _sha256Cng.ComputeHash(_inputBytes); }
private void CompressFunct() { var CompressionIO = new byte[104857600]; var blocksPerChunk = CompressionIO.Length / bs + (CompressionIO.Length % bs > 0 ? 1 : 0); var sourceFs = new LocalFileSystem(inFolderPath); var destFs = new LocalFileSystem(outFolderPath); foreach (var file in sourceFs.EnumerateEntries().Where(item => item.Type == DirectoryEntryType.File)) { Out.Log($"{file.FullPath}\r\n"); var outFileName = $"{file.Name}.nsz"; using (var outputFileBase = FolderTools.CreateAndOpen(file, destFs, outFileName)) using (var outputFile = new FilePositionStorage(outputFileBase)) using (var inputFileBase = sourceFs.OpenFile(file.FullPath, OpenMode.Read)) using (var inputFile = new FilePositionStorage(inputFileBase)) { amountOfBlocks = (int)Math.Ceiling((decimal)inputFile.GetSize() / bs); sizeOfSize = (int)Math.Ceiling(Math.Log(bs, 2) / 8); var perBlockHeaderSize = sizeOfSize + 1; var headerSize = 0x15 + perBlockHeaderSize * amountOfBlocks; outputFile.Seek(headerSize); var nsZipMagic = new byte[] { 0x6e, 0x73, 0x5a, 0x69, 0x70 }; var nsZipMagicRandomKey = new byte[5]; secureRNG.GetBytes(nsZipMagicRandomKey); Util.XorArrays(nsZipMagic, nsZipMagicRandomKey); var chunkIndex = 0; nsZipHeader = new byte[headerSize]; Array.Copy(nsZipMagic, 0x00, nsZipHeader, 0x00, 0x05); Array.Copy(nsZipMagicRandomKey, 0x00, nsZipHeader, 0x05, 0x05); nsZipHeader[0x0A] = 0x00; //Version nsZipHeader[0x0B] = 0x01; //Type nsZipHeader[0x0C] = (byte)(bs >> 32); nsZipHeader[0x0D] = (byte)(bs >> 24); nsZipHeader[0x0E] = (byte)(bs >> 16); nsZipHeader[0x0F] = (byte)(bs >> 8); nsZipHeader[0x10] = (byte)bs; nsZipHeader[0x11] = (byte)(amountOfBlocks >> 24); nsZipHeader[0x12] = (byte)(amountOfBlocks >> 16); nsZipHeader[0x13] = (byte)(amountOfBlocks >> 8); nsZipHeader[0x14] = (byte)amountOfBlocks; sha256Compressed = new SHA256Cng(); long maxPos = inputFile.GetSize(); int blocksLeft; int blocksInThisChunk; do { var outputLen = new int[blocksPerChunk]; //Filled with 0 inputFile.Read(CompressionIO); blocksLeft = amountOfBlocks - chunkIndex * blocksPerChunk; blocksInThisChunk = Math.Min(blocksPerChunk, blocksLeft); var opt = new ParallelOptions() { MaxDegreeOfParallelism = this.MaxDegreeOfParallelism }; //for(int index = 0; index < blocksInThisChunk; ++index) Parallel.For(0, blocksInThisChunk, opt, index => { var currentBlockID = chunkIndex * blocksPerChunk + index; var startPosRelative = index * bs; //Don't directly cast bytesLeft to int or sectors over 2 GB will overflow into negative size long startPos = (long)currentBlockID * (long)bs; long bytesLeft = maxPos - startPos; var blockSize = bs < bytesLeft ? bs : (int)bytesLeft; Out.Print($"Block: {currentBlockID + 1}/{amountOfBlocks} ({opt.MaxDegreeOfParallelism})\r\n"); CompressionAlgorithm compressionAlgorithm; outputLen[index] = CompressBlock(ref CompressionIO, startPosRelative, blockSize, out compressionAlgorithm); //Out.Log($"inputLen[{currentBlockID}]: {blockSize}\r\n"); //Out.Log($"outputLen[{currentBlockID}]: {outputLen[index]} bytesLeft={bytesLeft}\r\n"); var offset = currentBlockID * (sizeOfSize + 1); switch (compressionAlgorithm) { case CompressionAlgorithm.None: nsZipHeader[0x15 + offset] = 0x00; break; case CompressionAlgorithm.Zstandard: nsZipHeader[0x15 + offset] = 0x01; break; case CompressionAlgorithm.LZMA: nsZipHeader[0x15 + offset] = 0x02; break; default: throw new ArgumentOutOfRangeException(); } for (var j = 0; j < sizeOfSize; ++j) { nsZipHeader[0x16 + offset + j] = (byte)(outputLen[index] >> ((sizeOfSize - j - 1) * 8)); } }); for (int index = 0; index < blocksInThisChunk; ++index) { var startPos = index * bs; sha256Compressed.TransformBlock(CompressionIO, startPos, outputLen[index], null, 0); var dataToWrite = CompressionIO.AsSpan().Slice(startPos, outputLen[index]); outputFile.Write(dataToWrite); } ++chunkIndex; } while (blocksLeft - blocksInThisChunk > 0); outputFile.Write(nsZipHeader, 0); sha256Header = new SHA256Cng(); sha256Header.ComputeHash(nsZipHeader); var sha256Hash = new byte[0x20]; Array.Copy(sha256Header.Hash, sha256Hash, 0x20); sha256Compressed.TransformFinalBlock(new byte[0], 0, 0); Util.XorArrays(sha256Hash, sha256Compressed.Hash); //Console.WriteLine(sha256Header.Hash.ToHexString()); //Console.WriteLine(sha256Compressed.Hash.ToHexString()); outputFile.Seek(0, SeekOrigin.End); outputFile.Write(sha256Hash.AsSpan().Slice(0, 0x10)); } } }
/// <summary> /// Generates a 256-bit hash for the given data and returns the generated results as a Base-64 string. /// </summary> /// <param name="Data">The data to be hashed. Takes a string.</param> /// <returns>Hash value formatted as a Base-64 string.</returns> public static string Compute256Base64(string Data) { return(Convert.ToBase64String(SHA256.ComputeHash(System.Text.Encoding.Default.GetBytes(Data)))); }
/// <summary> /// Check that the Quote is correct /// </summary> /// <param name="m3Received">Message 3 from client</param> /// <param name="m3QuoteStr">Message 3 quote string</param> /// <param name="sigmaSequenceCheck">Service Provider Sequence (State) Check</param> /// <param name="currentGaStr">Message 3 ECC Ga String</param> /// <returns>Boolean whether the provided quote was valid</returns> private bool CheckQuoteOk(M3RequestMessage m3Received, String m3QuoteStr, String currentGaStr) { log.Debug("CheckQuoteOk(.) started."); if (m3Received == null || m3QuoteStr == null || currentGaStr == null) { HttpResponseException e = new HttpResponseException(System.Net.HttpStatusCode.InternalServerError); options.LogThrownException(e); throw e; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // The Quote should match a pre-provisioned enclave measurement, and the quote signature should be valid. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Ensure quote is within defined range bool qSizeLimits = (m3Received.reqM3Body.quote.Length > MsgFieldLimits.UINT32_MINIMUM_QUOTE_SIZE && m3Received.reqM3Body.quote.Length < MsgFieldLimits.UINT32_PRACTICAL_SIZE_LIMIT); if (!qSizeLimits) { log.Debug("Quote size is invalid: " + m3Received.reqM3Body.quote.Length + ". Expected range: " + MsgFieldLimits.UINT32_MINIMUM_QUOTE_SIZE + " to " + MsgFieldLimits.UINT32_PRACTICAL_SIZE_LIMIT); HttpResponseException e = new HttpResponseException(System.Net.HttpStatusCode.BadRequest); options.LogThrownException(e); throw e; } // Look at the enclave measurement stored in Constants.QuoteInfo from the settings file. // Assume the measurement is stored as a base 16 encoded string, but verify the input. bool qMeasurementMatch = false; bool qMeasurementRequired = false; string mrEncString = m3QuoteStr.Substring((int)Constants.QuoteInfo.mrEncOffset * 2, Constants.QuoteInfo.mrEncSize * 2); // MR Enclave String from Quote log.DebugFormat("m3 quote measurement: {0}", mrEncString); log.DebugFormat("recorded quote measurement: {0}", sigmaSequenceCheck.enclaveType.MRENCLAVE); // Check the stored quote string from user input by attempting to convert to byte array form. if (!String.IsNullOrEmpty(sigmaSequenceCheck.enclaveType.MRENCLAVE)) { qMeasurementRequired = true; byte[] mrEnclaveTestBa = bMessage.BlobStrToBa(sigmaSequenceCheck.enclaveType.MRENCLAVE); // Convert the MRenclave byte array back to string form to ensure uniform base16 Encoding from user input sigmaSequenceCheck.enclaveType.MRENCLAVE = bMessage.BaToBlobStr(mrEnclaveTestBa); qMeasurementMatch = String.Equals(mrEncString, sigmaSequenceCheck.enclaveType.MRENCLAVE, StringComparison.Ordinal); log.DebugFormat("converted quote measurement: {0}", sigmaSequenceCheck.enclaveType.MRENCLAVE); log.DebugFormat("quote compare result: {0}", qMeasurementMatch); } // Derive the "VK" key using VK = AES-CMAC(KDK, 0x01||’VK’||0x00||0x80 ||0x00) byte[] VK = bMessage.KeyLabelToKey(Constants.VK, sigmaSequenceCheck.currentKDK); // Compute a SHA-256 hash of (ga||gb||VK). string currentGbStr = bMessage.BaToBlobStr(sigmaSequenceCheck.currentGb); string vKstring = bMessage.BaToBlobStr(VK); string gabvkStr = currentGaStr + currentGbStr + vKstring; byte[] gabvkBa = bMessage.BlobStrToBa(gabvkStr); byte[] gabvkHashBa = null; // Klocwork issues related to qRptSha... // Klocwork thinks tha this object is dereferenced before null check. However, if it is // null, then an exception is thrown below, outside of our try-catch-finally block, and // all other paths go through the try-catch-finally, where it gets properly disposed. // It appears that klocwork somehow became confused in this code flow. using (SHA256Cng qRptSha = new SHA256Cng()) { if (qRptSha == null) { HttpResponseException e = new HttpResponseException(System.Net.HttpStatusCode.InternalServerError); options.LogThrownException(e); throw e; } try { gabvkHashBa = qRptSha.ComputeHash(gabvkBa); string gabvkHashString = bMessage.BaToBlobStr(gabvkHashBa); // Retrieve the non-zero (first 32) Bytes of the "REPORTDATA" field from the quote string rptDataString = m3QuoteStr.Substring((int)Constants.QuoteInfo.reportDataOffset * 2, Constants.QuoteInfo.reportDataSize * 2); bool qHashMatch = false; log.DebugFormat("m3 (ga||gb||VK) hash: {0}", rptDataString); log.DebugFormat("computed (ga||gb||VK) hash: {0}", gabvkHashString); qHashMatch = String.Equals(rptDataString, gabvkHashString, StringComparison.Ordinal); log.DebugFormat("hash compare result: {0}", qHashMatch); // Evaluate the quote check conditions if (qSizeLimits && qHashMatch && (qMeasurementMatch || !qMeasurementRequired)) { log.Debug("CheckQuoteOk(.) returning true."); return(true); } log.Debug("!!! Quote Check Failure !!!"); PrintQuote(m3QuoteStr); } catch (Exception e) { options.LogCaughtErrorException(e); log.Debug("Error checking Quote. " + e.Message); HttpResponseException newException = new HttpResponseException(System.Net.HttpStatusCode.InternalServerError); options.LogThrownException(newException); throw newException; } } log.Debug("CheckQuoteOk(.) returning false."); return(false); }
/// <summary> /// Computes the SHA256 hash of a given segment in a buffer. /// </summary> /// <param Name="buffer">The buffer over which to compute the hash.</param> /// <param Name="offset">The offset at which to begin computing the hash.</param> /// <param Name="count">The number of bytes in the buffer to include in the hash.</param> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <returns>The binary hash (32 bytes) of the buffer segment.</returns> public static byte[] ComputeHash(byte[] buffer, int offset, int count) { using (SHA256 sha256 = new SHA256Cng()) { return(sha256.ComputeHash(buffer, offset, count)); } }
public static byte[] GenSHA256Hash(byte[] Data) { var SHA = new SHA256Cng(); return(SHA.ComputeHash(Data)); }
private void btDecode_Click(object sender, RoutedEventArgs e) { Passphrase pass = new Passphrase(); pass.Owner = this; pass.ShowDialog(); byte[] decrypted; using (FileStream fileStream = File.OpenRead(file)) { decrypted = new byte[fileStream.Length]; fileStream.Read(decrypted, 0, decrypted.Length); } SymmetricAlgorithm sa; CipherMode mode; PaddingMode padding = PaddingMode.None; byte[] keyT = Encoding.UTF8.GetBytes(pass.pbPass.Password); SHA256 sha256 = new SHA256Cng(); keyT = sha256.ComputeHash(keyT); int n = 0; if (rbDeAES.IsChecked == true) { sa = AesCryptoServiceProvider.Create(); n = 32; } else { sa = TripleDESCryptoServiceProvider.Create(); n = 24; } byte[] key = new byte[n]; Array.Copy(keyT, key, n); byte[] iv = new byte[8]; if (n == 24) { iv = new byte[8]; } else { iv = new byte[16]; } if (rbEnCBC.IsChecked == true) { mode = CipherMode.CBC; } else { if (rbEnCFB.IsEnabled) { mode = CipherMode.CFB; } else { mode = CipherMode.CTS; } } byte[] entrophy = sha256.ComputeHash(Encoding.UTF8.GetBytes(pass.pbPass.Password)); //File.ReadAllBytes(@"D:\OSU\ЗПиД\ЗПиД6\Энтропия.txt");//113 183 // SHA256 sha256 = new SHA256Cng(); // entrophy = sha256.ComputeHash(entrophy); using (FileStream fstream = File.OpenRead(@"D:\OSU\ЗПиД\ЗПиД6\Пароль.txt")) { byte[] keyTemp = new byte[fstream.Length]; fstream.Read(keyTemp, 0, keyTemp.Length); key = ProtectedData.Unprotect(keyTemp, entrophy, DataProtectionScope.CurrentUser); // keyT = Decrypt(temp, sa, key, iv, mode, padding); } //Array.Copy(keyT, key, n); byte[] decr = Decrypt(decrypted, sa, key, iv, mode, padding); string result = Encoding.UTF8.GetString(decr); File.WriteAllText(@"C:\Users\Nastya\Desktop\Университет\ЗПиД\ЗПиД6\Результат.txt", result, Encoding.UTF8); MessageBox.Show("Выполнено!"); tbDeOpenDialog.Text = ""; }
private void Encode_Click(object sender, RoutedEventArgs e) { Passphrase pass = new Passphrase(); pass.Owner = this; pass.ShowDialog(); SymmetricAlgorithm sa; byte[] iv = new byte[8]; CipherMode mode; PaddingMode padding = PaddingMode.Zeros; int n = 0; if (rbEnAES.IsChecked == true) { sa = AesCryptoServiceProvider.Create(); n = 32; } else { sa = TripleDESCryptoServiceProvider.Create(); n = 24; } if (n == 32) { iv = new byte[16]; } byte[] key = new byte[n]; if (rbEnCBC.IsChecked == true) { mode = CipherMode.CBC; } else { if (rbEnCFB.IsChecked == true) { mode = CipherMode.CFB; } else { mode = CipherMode.CTS; } } byte[] entrophy = new byte[32]; /* RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); * rng.GetBytes(entrophy);*/ SHA256 sha256 = new SHA256Cng(); entrophy = sha256.ComputeHash(Encoding.UTF8.GetBytes(pass.pbPass.Password));//114 174 3 byte[] salt = Encoding.UTF8.GetBytes("saltsaltsalt"); // File.WriteAllBytes(@"D:\OSU\ЗПиД\ЗПиД6\Энтропия.txt", entrophy); if (rbGeneration.IsChecked == true) { Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(pass.pbPass.Password, salt, 10000); key = pbkdf2.GetBytes(n); } else { Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(pbKeyPhrase.Password, salt, 10000); key = pbkdf2.GetBytes(n); } byte[] encrypted = Encrypt(dataText, sa, key, iv, mode, padding); using ( FileStream fs = new FileStream(@"D:\OSU\ЗПиД\ЗПиД6\Шифр.txt", FileMode.Create)) { fs.Write(encrypted, 0, encrypted.Length); } byte[] keyTemp = Encoding.UTF8.GetBytes(pass.pbPass.Password); // SHA256 sha256 = new SHA256Managed(); keyTemp = sha256.ComputeHash(keyTemp); byte[] keyForkey = new byte[n]; Array.Copy(keyTemp, keyForkey, n); // byte[] en = Encrypt(key, sa, keyForkey, iv, mode, padding); byte[] en = ProtectedData.Protect(key, entrophy, DataProtectionScope.CurrentUser); using ( FileStream fs_key = new FileStream(@"D:\OSU\ЗПиД\ЗПиД6\Пароль.txt", FileMode.Create)) { fs_key.Write(en, 0, en.Length); } MessageBox.Show("Выполнено!"); tbEnOpenDialog.Text = ""; rbGeneration.IsChecked = true; pbKeyPhrase.Password = ""; rbGeneration_Checked(sender, e); }