internal async void MakeAssertionResponse(COSE.KeyType kty, COSE.Algorithm alg, COSE.EllipticCurve crv = COSE.EllipticCurve.P256) { const string rp = "fido2.azurewebsites.net"; byte[] rpId = System.Text.Encoding.UTF8.GetBytes(rp); var rpIdHash = SHA256.Create().ComputeHash(rpId); var flags = AuthenticatorFlags.AT | AuthenticatorFlags.ED | AuthenticatorFlags.UP | AuthenticatorFlags.UV; const UInt16 signCount = 0xf1d0; var aaguid = new Guid("F1D0F1D0-F1D0-F1D0-F1D0-F1D0F1D0F1D0"); var credentialID = new byte[] { 0xf1, 0xd0, 0xf1, 0xd0, 0xf1, 0xd0, 0xf1, 0xd0, 0xf1, 0xd0, 0xf1, 0xd0, 0xf1, 0xd0, 0xf1, 0xd0, }; CredentialPublicKey cpk = null; ECDsaCng ecdsa = null; RSACng rsa = null; byte[] privateKeySeed, publicKey, expandedPrivateKey = null; switch (kty) { case COSE.KeyType.EC2: { ecdsa = MakeECDsa(alg, crv); var ecparams = ecdsa.ExportParameters(true); cpk = MakeCredentialPublicKey(kty, alg, crv, ecparams.Q.X, ecparams.Q.Y); break; } case COSE.KeyType.RSA: { rsa = new RSACng(); var rsaparams = rsa.ExportParameters(true); cpk = MakeCredentialPublicKey(kty, alg, rsaparams.Modulus, rsaparams.Exponent); break; } case COSE.KeyType.OKP: { MakeEdDSA(out privateKeySeed, out publicKey, out expandedPrivateKey); cpk = MakeCredentialPublicKey(kty, alg, COSE.EllipticCurve.Ed25519, publicKey); break; } throw new ArgumentOutOfRangeException(string.Format("Missing or unknown kty {0}", kty.ToString())); } var acd = new AttestedCredentialData(aaguid, credentialID, cpk); var extBytes = CBORObject.NewMap().Add("testing", true).EncodeToBytes(); var exts = new Extensions(extBytes); var ad = new AuthenticatorData(rpIdHash, flags, signCount, acd, exts); var authData = ad.ToByteArray(); var challenge = new byte[128]; var rng = RandomNumberGenerator.Create(); rng.GetBytes(challenge); var clientData = new { Type = "webauthn.get", Challenge = challenge, Origin = rp, }; var clientDataJson = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(clientData)); var sha = SHA256.Create(); var hashedClientDataJson = sha.ComputeHash(clientDataJson); byte[] data = new byte[authData.Length + hashedClientDataJson.Length]; Buffer.BlockCopy(authData, 0, data, 0, authData.Length); Buffer.BlockCopy(hashedClientDataJson, 0, data, authData.Length, hashedClientDataJson.Length); byte[] signature = null; switch (kty) { case COSE.KeyType.EC2: { signature = ecdsa.SignData(data, CryptoUtils.algMap[(int)alg]); break; } case COSE.KeyType.RSA: { RSASignaturePadding padding; switch (alg) // https://www.iana.org/assignments/cose/cose.xhtml#algorithms { case COSE.Algorithm.PS256: case COSE.Algorithm.PS384: case COSE.Algorithm.PS512: padding = RSASignaturePadding.Pss; break; case COSE.Algorithm.RS1: case COSE.Algorithm.RS256: case COSE.Algorithm.RS384: case COSE.Algorithm.RS512: padding = RSASignaturePadding.Pkcs1; break; default: throw new ArgumentOutOfRangeException(string.Format("Missing or unknown alg {0}", alg.ToString())); } signature = rsa.SignData(data, CryptoUtils.algMap[(int)alg], padding); break; } case COSE.KeyType.OKP: { signature = Chaos.NaCl.Ed25519.Sign(data, expandedPrivateKey); break; } throw new ArgumentOutOfRangeException(string.Format("Missing or unknown kty {0}", kty.ToString())); } if (kty == COSE.KeyType.EC2) { signature = EcDsaSigFromSig(signature, ecdsa.KeySize); } var userHandle = new byte[16]; rng.GetBytes(userHandle); var assertion = new AuthenticatorAssertionRawResponse.AssertionResponse() { AuthenticatorData = authData, Signature = signature, ClientDataJson = clientDataJson, UserHandle = userHandle, }; var lib = new Fido2(new Fido2Configuration() { ServerDomain = rp, ServerName = rp, Origin = rp, }); List <PublicKeyCredentialDescriptor> existingCredentials = new List <PublicKeyCredentialDescriptor>(); var cred = new PublicKeyCredentialDescriptor(); cred.Type = PublicKeyCredentialType.PublicKey; cred.Id = new byte[] { 0xf1, 0xd0 }; existingCredentials.Add(cred); var options = lib.GetAssertionOptions(existingCredentials, null, null); options.Challenge = challenge; var response = new AuthenticatorAssertionRawResponse() { Response = assertion, Type = PublicKeyCredentialType.PublicKey, Id = new byte[] { 0xf1, 0xd0 }, RawId = new byte[] { 0xf1, 0xd0 }, }; IsUserHandleOwnerOfCredentialIdAsync callback = (args) => { return(Task.FromResult(true)); }; var res = await lib.MakeAssertionAsync(response, options, cpk.GetBytes(), signCount - 1, callback); }
private void koduok() { _ = this.Invoke((Action) delegate { //paspaudziam"koduot" ir ieskom ka uzkoduot FolderBrowserDialog FBD = new FolderBrowserDialog(); if (FBD.ShowDialog() == DialogResult.OK) { //visi failai kataloge: string[] fileArray = Directory.GetFiles(FBD.SelectedPath); string password = "******"; //Array.ForEach(fileArray, Console.WriteLine); //for progress bar-------- int k = 0; //is viso rezultatu: var fileCount = fileArray.Count(); progressBar1.Minimum = 0; progressBar1.Maximum = fileCount; //isvalyti faila su md5 reiksmem System.IO.File.WriteAllText("md5.txt", string.Empty); //for every file in the fileArray do this: foreach (string file in fileArray) { ////if its a file for md5 values- skip if (Path.GetFileName(file) == "md5.txt") { continue; } byte[] bytesToBeEncrypted = File.ReadAllBytes(file); byte[] passwordBytes = Encoding.UTF8.GetBytes(password); // Hash the password with SHA256 passwordBytes = SHA256.Create().ComputeHash(passwordBytes); byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes); //string fileEncrypted = "myfile.txt"; File.WriteAllBytes(file, bytesEncrypted); //apskaiciuojam md5 hash reiksme string reiksme = CalculateMD5(file); //Console.WriteLine(reiksme); //isaugom md5 reiksme faile //File.AppendAllText("md5.txt", reiksme); File.AppendAllText("md5.txt", reiksme + Environment.NewLine); //Progress bar'o pildymas while (k <= fileCount) { progressBar1.Value = k; k++; } } } }); }
/// <summary> /// Initializes a new instance of the <see cref="Sha256Hash"/> class. /// </summary> public Sha256Hash() { this.Sha256 = SHA256.Create(); }
public void Framework_Dependent_AppHost_From_Global_Registry_Location_Succeeds() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return; } var fixture = sharedTestState.PortableAppFixture_Published .Copy(); // Since SDK doesn't support building framework dependent apphost yet, emulate that behavior // by creating the executable from apphost.exe var appExe = fixture.TestProject.AppExe; var appDllName = Path.GetFileName(fixture.TestProject.AppDll); string hostExeName = RuntimeInformationExtensions.GetExeFileNameForCurrentPlatform("apphost"); string builtAppHost = Path.Combine(sharedTestState.RepoDirectories.HostArtifacts, hostExeName); string appDir = Path.GetDirectoryName(appExe); string appDirHostExe = Path.Combine(appDir, hostExeName); // Make a copy of apphost first, replace hash and overwrite app.exe, rather than // overwrite app.exe and edit in place, because the file is opened as "write" for // the replacement -- the test fails with ETXTBSY (exit code: 26) in Linux when // executing a file opened in "write" mode. File.Copy(builtAppHost, appDirHostExe, true); using (var sha256 = SHA256.Create()) { // Replace the hash with the managed DLL name. var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes("foobar")); var hashStr = BitConverter.ToString(hash).Replace("-", "").ToLower(); AppHostExtensions.SearchAndReplace(appDirHostExe, Encoding.UTF8.GetBytes(hashStr), Encoding.UTF8.GetBytes(appDllName), true); } File.Copy(appDirHostExe, appExe, true); // Get the framework location that was built string builtDotnet = fixture.BuiltDotnet.BinPath; RegistryKey hkcu = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32); RegistryKey interfaceKey = hkcu.CreateSubKey(@"Software\Classes\Interface"); string testKeyName = "_DOTNET_Test" + System.Diagnostics.Process.GetCurrentProcess().Id.ToString(); RegistryKey testKey = interfaceKey.CreateSubKey(testKeyName); try { string architecture = fixture.CurrentRid.Split('-')[1]; RegistryKey dotnetLocationKey = testKey.CreateSubKey($@"Setup\InstalledVersions\{architecture}"); dotnetLocationKey.SetValue("InstallLocation", builtDotnet); // Verify running with the default working directory Command.Create(appExe) .CaptureStdErr() .CaptureStdOut() .EnvironmentVariable("_DOTNET_TEST_SDK_REGISTRY_PATH", testKey.Name) .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello World") .And.HaveStdOutContaining($"Framework Version:{sharedTestState.RepoDirectories.MicrosoftNETCoreAppVersion}"); // Verify running from within the working directory Command.Create(appExe) .WorkingDirectory(fixture.TestProject.OutputDirectory) .EnvironmentVariable("_DOTNET_TEST_SDK_REGISTRY_PATH", testKey.Name) .CaptureStdErr() .CaptureStdOut() .Execute() .Should().Pass() .And.HaveStdOutContaining("Hello World") .And.HaveStdOutContaining($"Framework Version:{sharedTestState.RepoDirectories.MicrosoftNETCoreAppVersion}"); } finally { interfaceKey.DeleteSubKeyTree(testKeyName); } }
public static byte[] GetHash(HashType type, byte[] input, int reportInterval, IProgress <long> progress) { HashAlgorithm hash = null; try { switch (type) { case HashType.MD5: hash = MD5.Create(); break; case HashType.SHA1: hash = SHA1.Create(); break; case HashType.SHA256: hash = SHA256.Create(); break; case HashType.SHA384: hash = SHA384.Create(); break; case HashType.SHA512: hash = SHA512.Create(); break; default: throw new InvalidOperationException("Invalid Hash Type"); } // No progress report if (reportInterval <= 0 || progress == null) { return(hash.ComputeHash(input)); } // With progress report int offset = 0; while (offset < input.Length) { if (offset + reportInterval < input.Length) { hash.TransformBlock(input, offset, reportInterval, input, offset); offset += reportInterval; } else // Last run { int bytesRead = input.Length - offset; hash.TransformFinalBlock(input, offset, bytesRead); offset += bytesRead; } progress.Report(offset); } return(hash.Hash); } finally { if (hash != null) { hash.Dispose(); } } }
private byte[] GetHash(string inputString) { HashAlgorithm algorithm = SHA256.Create(); return(algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString))); }
public byte[] GenerateMAVLinkPacket20(MAVLINK_MSG_ID messageType, object indata, bool sign = false, byte sysid = 255, byte compid = (byte)MAV_COMPONENT.MAV_COMP_ID_MISSIONPLANNER, int sequence = -1) { byte[] data; data = MavlinkUtil.StructureToByteArray(indata); MavlinkUtil.TrimePayload(ref data); int extra = 0; if (sign) { extra = MAVLINK_SIGNATURE_BLOCK_LEN; } byte[] packet = new byte[data.Length + MAVLINK_NUM_NON_PAYLOAD_BYTES + extra]; packet[0] = MAVLINK2_STX; packet[1] = (byte)data.Length; packet[2] = 0;//incompat signing if (sign) { packet[2] |= MAVLINK_IFLAG_SIGNED; } packet[3] = 0;//compat packet[4] = (byte)packetcount; if (sequence != -1) { packet[4] = (byte)sequence; } packetcount++; packet[5] = sysid; packet[6] = compid; packet[7] = (byte)((UInt32)messageType); packet[8] = (byte)((UInt32)messageType >> 8); packet[9] = (byte)((UInt32)messageType >> 16); int i = MAVLINK_NUM_HEADER_BYTES; foreach (byte b in data) { packet[i] = b; i++; } ushort checksum = MavlinkCRC.crc_calculate(packet, data.Length + MAVLINK_NUM_HEADER_BYTES); checksum = MavlinkCRC.crc_accumulate(MAVLINK_MESSAGE_INFOS.GetMessageInfo((uint)messageType).crc, checksum); byte ck_a = (byte)(checksum & 0xFF); ///< High byte byte ck_b = (byte)(checksum >> 8); ///< Low byte packet[i] = ck_a; i += 1; packet[i] = ck_b; i += 1; if (sign) { //https://docs.google.com/document/d/1ETle6qQRcaNWAmpG2wz0oOpFKSF_bcTmYMQvtTGI8ns/edit /* * 8 bits of link ID * 48 bits of timestamp * 48 bits of signature */ // signature = sha256_48(secret_key + header + payload + CRC + link-ID + timestamp) var timestamp = (UInt64)((DateTime.UtcNow - new DateTime(2015, 1, 1)).TotalMilliseconds * 100); if (timestamp == lasttimestamp) { timestamp++; } lasttimestamp = timestamp; var timebytes = BitConverter.GetBytes(timestamp); var sig = new byte[7]; // 13 includes the outgoing hash sig[0] = sendlinkid; Array.Copy(timebytes, 0, sig, 1, 6); // timestamp //Console.WriteLine("gen linkid {0}, time {1} {2} {3} {4} {5} {6} {7}", sig[0], sig[1], sig[2], sig[3], sig[4], sig[5], sig[6], timestamp); if (signingKey == null || signingKey.Length != 32) { signingKey = new byte[32]; } using (SHA256 signit = SHA256.Create()) { MemoryStream ms = new MemoryStream(); ms.Write(signingKey, 0, signingKey.Length); ms.Write(packet, 0, i); ms.Write(sig, 0, sig.Length); var ctx = signit.ComputeHash(ms.ToArray()); // trim to 48 Array.Resize(ref ctx, 6); foreach (byte b in sig) { packet[i] = b; i++; } foreach (byte b in ctx) { packet[i] = b; i++; } } } return(packet); }
public static string GetSHA256Hash(this string input) => GetHash(input, SHA256.Create());
public static string GetSHA256FileSystemSafeHash(this string input) => GetFileSystemSafeHash(input, SHA256.Create());
/// <summary> /// 验证 SHA384 值 /// </summary> /// <param name="input"> 未加密的字符串 </param> /// <param name="encoding"> 字符编码 </param> /// <returns></returns> public static bool VerifySHA384Value(string input, Encoding encoding) { return VerifyHashValue(SHA256.Create(), input, SHA384Encrypt(input, encoding), encoding); }
private static string ComputeHash(string data, string algorithm) { // Disable MD5 insecure warning. #pragma warning disable CA5351 using (HashAlgorithm hash = algorithm.StartsWith("SHA-256", StringComparison.OrdinalIgnoreCase) ? SHA256.Create() : (HashAlgorithm)MD5.Create()) #pragma warning restore CA5351 { Encoding enc = Encoding.UTF8; byte[] result = hash.ComputeHash(enc.GetBytes(data)); StringBuilder sb = new StringBuilder(result.Length * 2); foreach (byte b in result) { sb.Append(b.ToString("x2")); } return(sb.ToString()); } }
/// <summary> /// SHA256 加密 /// </summary> /// <param name="input"> 要加密的字符串 </param> /// <param name="encoding"> 字符编码 </param> /// <returns></returns> public static string SHA256Encrypt(string input, Encoding encoding) { return HashEncrypt(SHA256.Create(), input, encoding); }
public async static Task<DecryptionResult> DecryptFile(Windows.Storage.StorageFile inputFile, string password) { DecryptionResult decryptionResult = null; try { byte[] FileContentBytes = null; using (Stream stream = await inputFile.OpenStreamForReadAsync()) { using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); FileContentBytes = memoryStream.ToArray(); } } int ctr = 0; for (int i = 999; i >= 0; i--) { if (FileContentBytes[i] != 0) { ctr = i; break; } } int ctr2 = 1000; for (int i = 1999; i >= 1000; i--) { if (FileContentBytes[i] != 0) { ctr2 = i; break; } } int FileNameBytesLength = ctr + 1; int ExtensionBytesLength = ctr2 + 1 - 1000; byte[] passwordBytes = SHA256.Create().ComputeHash(System.Text.Encoding.ASCII.GetBytes(password)); byte[] SaltedHashedPassword = SHA256.Create().ComputeHash(System.Text.Encoding.ASCII.GetBytes(password + "CryptoApp")); byte[] FileNameBytes = new byte[FileNameBytesLength]; byte[] ExtensionBytes = new byte[ExtensionBytesLength]; byte[] StoredHashedPassword = new byte[32]; byte[] EncryptedBytes = new byte[FileContentBytes.Length - 2032]; System.Buffer.BlockCopy(FileContentBytes, 2000, StoredHashedPassword, 0, 32); bool ArePasswordsSame = true; for (int i = 0; i < 32; i++) { if (SaltedHashedPassword[i] != StoredHashedPassword[i]) { ArePasswordsSame = false; break; } } if (ArePasswordsSame == false) { decryptionResult = new DecryptionResult() { Result = false, Error = "Password", DecryptedString = null }; return decryptionResult; } System.Buffer.BlockCopy(FileContentBytes, 0, FileNameBytes, 0, FileNameBytesLength); System.Buffer.BlockCopy(FileContentBytes, 1000, ExtensionBytes, 0, ExtensionBytesLength); System.Buffer.BlockCopy(FileContentBytes, 2032, EncryptedBytes, 0, EncryptedBytes.Length); int Blocks128000Size = EncryptedBytes.Length / 128000; int LastBlockSize = EncryptedBytes.Length % 128000; ctr = 0; byte[] DecryptedBytes = new byte[EncryptedBytes.Length]; for (long i = 0; i < Blocks128000Size; i++) { byte[] input = new byte[128000]; System.Buffer.BlockCopy(EncryptedBytes, ctr, input, 0, 128000); byte[] result = DecryptionService.GetDecryptedByteArray(input, passwordBytes); System.Buffer.BlockCopy(result, 0, DecryptedBytes, ctr, 128000); ctr = ctr + 128000; } if (LastBlockSize > 0) { byte[] input = new byte[LastBlockSize]; System.Buffer.BlockCopy(EncryptedBytes, ctr, input, 0, LastBlockSize); byte[] result = DecryptionService.GetDecryptedByteArray(input, passwordBytes); System.Buffer.BlockCopy(result, 0, DecryptedBytes, ctr, LastBlockSize); } string CurrentDirectoryPath = System.IO.Path.GetDirectoryName(inputFile.Path); string CurrentFileName = System.Text.Encoding.ASCII.GetString(FileNameBytes) + "_1"; string CurrentFileExtension = System.Text.Encoding.ASCII.GetString(ExtensionBytes); string WritePath = System.IO.Path.Combine(CurrentDirectoryPath, CurrentFileName + CurrentFileExtension); decryptionResult = new DecryptionResult() { Result = true, Error = null, DecryptedString = null, DecryptedContents = DecryptedBytes, WritePath = WritePath }; } catch (Exception ex) { decryptionResult = new DecryptionResult() { Result = false, Error = ex.Message, DecryptedString = null }; } return decryptionResult; }
public DropboxContentHasher() : this(SHA256.Create(), SHA256.Create(), 0) { }
public static async Task UpdatePACFromGeosite() { string geositeUrl = GEOSITE_URL; string geositeSha256sumUrl = GEOSITE_SHA256SUM_URL; SHA256 mySHA256 = SHA256.Create(); var config = Program.MainController.GetCurrentConfiguration(); string group = config.geositeGroup; bool blacklist = config.geositeBlacklistMode; if (!string.IsNullOrWhiteSpace(config.geositeUrl)) { logger.Info("Found custom Geosite URL in config file"); geositeUrl = config.geositeUrl; } logger.Info($"Checking Geosite from {geositeUrl}"); // use System.Net.Http.HttpClient to download GeoSite db. // NASTY workaround: new HttpClient every update // because we can't change proxy on existing socketsHttpHandler instance httpClientHandler = new HttpClientHandler(); httpClient = new HttpClient(httpClientHandler); if (!string.IsNullOrWhiteSpace(config.userAgentString)) { httpClient.DefaultRequestHeaders.Add("User-Agent", config.userAgentString); } if (config.enabled) { httpClientHandler.Proxy = new WebProxy( config.isIPv6Enabled ? $"[{IPAddress.IPv6Loopback}]" : IPAddress.Loopback.ToString(), config.localPort); } try { // download checksum first var geositeSha256sum = await httpClient.GetStringAsync(geositeSha256sumUrl); geositeSha256sum = geositeSha256sum.Substring(0, 64).ToUpper(); logger.Info($"Got Sha256sum: {geositeSha256sum}"); // compare downloaded checksum with local geositeDB byte[] localDBHashBytes = mySHA256.ComputeHash(geositeDB); string localDBHash = BitConverter.ToString(localDBHashBytes).Replace("-", String.Empty); logger.Info($"Local Sha256sum: {localDBHash}"); // if already latest if (geositeSha256sum == localDBHash) { logger.Info("Local GeoSite DB is up to date."); return; } // not latest. download new DB var downloadedBytes = await httpClient.GetByteArrayAsync(geositeUrl); // verify sha256sum byte[] downloadedDBHashBytes = mySHA256.ComputeHash(downloadedBytes); string downloadedDBHash = BitConverter.ToString(downloadedDBHashBytes).Replace("-", String.Empty); logger.Info($"Actual Sha256sum: {downloadedDBHash}"); if (geositeSha256sum != downloadedDBHash) { logger.Info("Sha256sum Verification: FAILED. Downloaded GeoSite DB is corrupted. Aborting the update."); throw new Exception("Sha256sum mismatch"); } else { logger.Info("Sha256sum Verification: PASSED. Applying to local GeoSite DB."); } // write to geosite file using (FileStream geositeFileStream = File.Create(DATABASE_PATH)) await geositeFileStream.WriteAsync(downloadedBytes, 0, downloadedBytes.Length); // update stuff geositeDB = downloadedBytes; LoadGeositeList(); bool pacFileChanged = MergeAndWritePACFile(group, blacklist); UpdateCompleted?.Invoke(null, new GeositeResultEventArgs(pacFileChanged)); } catch (Exception ex) { Error?.Invoke(null, new ErrorEventArgs(ex)); } finally { if (httpClientHandler != null) { httpClientHandler.Dispose(); httpClientHandler = null; } if (httpClient != null) { httpClient.Dispose(); httpClient = null; } } }
private static byte[] GetHash(string str) { HashAlgorithm algorithm = SHA256.Create(); return(algorithm.ComputeHash(Encoding.UTF8.GetBytes(str))); }
/// <summary> /// Computes the sha 256 hash /// </summary> /// <param name="data"></param> /// <returns></returns> private byte[] ComputeSHA256(byte[] data) { var sha256 = SHA256.Create(); return(sha256.ComputeHash(data)); }
public static String Hashpassword(string password) { byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password); passwordBytes = SHA256.Create().ComputeHash(passwordBytes); return(Convert.ToBase64String(passwordBytes)); }
private Md5SingletonHelper() { this.md5 = MD5.Create(); this.sha1 = SHA1.Create(); this.sha256 = SHA256.Create(); }
/// <summary> /// Inserta un documento para generar una firma internally detached. /// </summary> /// <param name="sigDocument"></param> /// <param name="input"></param> /// <param name="mimeType"></param> private void SetContentInternallyDetached(SignatureDocument sigDocument, Stream input, string mimeType) { sigDocument.Document = new XmlDocument(); XmlElement rootElement = sigDocument.Document.CreateElement("DOCFIRMA"); sigDocument.Document.AppendChild(rootElement); string id = "CONTENT-" + Guid.NewGuid().ToString(); _refContent = new Reference { Uri = "#" + id, Id = "Reference-" + Guid.NewGuid().ToString(), Type = XadesSignedXml.XmlDsigObjectType }; _mimeType = mimeType; XmlElement contentElement = sigDocument.Document.CreateElement("CONTENT"); if (mimeType == "text/xml") { _encoding = "UTF-8"; XmlDocument doc = new XmlDocument { PreserveWhitespace = true }; doc.Load(input); contentElement.InnerXml = doc.DocumentElement.OuterXml; XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); _refContent.AddTransform(transform); } else { XmlDsigBase64Transform transform = new XmlDsigBase64Transform(); _refContent.AddTransform(transform); _encoding = transform.Algorithm; if (mimeType == "hash/sha256") { using (SHA256 sha2 = SHA256.Create()) { contentElement.InnerText = Convert.ToBase64String(sha2.ComputeHash(input)); } } else { using (MemoryStream ms = new MemoryStream()) { input.CopyTo(ms); contentElement.InnerText = Convert.ToBase64String(ms.ToArray()); } } } contentElement.SetAttribute("Id", id); contentElement.SetAttribute("MimeType", _mimeType); contentElement.SetAttribute("Encoding", _encoding); rootElement.AppendChild(contentElement); sigDocument.XadesSignature = new XadesSignedXml(sigDocument.Document); sigDocument.XadesSignature.AddReference(_refContent); }
internal static void AddMissingHeaders(HttpRequestMessage requestMessage, List <string> requiredHeaders) { var originalHeaders = requestMessage.Headers; var uri = requestMessage.RequestUri; if (IsRequiredHeaderMissing(Constants.DATE, originalHeaders, requiredHeaders)) { originalHeaders.Date = Convert.ToDateTime(ToRfc3339Format(DateTime.Now)); } if (IsRequiredHeaderMissing(Constants.HOST, originalHeaders, requiredHeaders)) { originalHeaders.Add(Constants.HOST, uri.Host); } // Add any of the missing content headers. This block should only be executed by PUT, POST and PATCH calls. // It won't be executed for ExcludeBodySigningStrategy type. if (requiredHeaders.Contains(Constants.CONTENT_LENGTH)) { HttpContentHeaders contentHeaders = requestMessage.Content.Headers; byte[] bodyBytes = ReadRequestBody(requestMessage).Result; if (IsRequiredHeaderMissing(Constants.CONTENT_TYPE, contentHeaders, requiredHeaders)) { contentHeaders.ContentType = new MediaTypeHeaderValue(Constants.JSON_CONTENT_TYPE); } if (IsRequiredHeaderMissing(Constants.CONTENT_LENGTH, contentHeaders, requiredHeaders)) { contentHeaders.ContentLength = bodyBytes.Length; } if (IsRequiredHeaderMissing(Constants.X_CONTENT_SHA256, contentHeaders, requiredHeaders)) { originalHeaders.Add(Constants.X_CONTENT_SHA256, Convert.ToBase64String(SHA256.Create().ComputeHash(bodyBytes))); } } }
/// <summary> /// 解密文件 /// </summary> /// <param name="inFile">待解密文件</param> /// <param name="outFile">解密后输出文件</param> /// <param name="password">解密密码</param> public static void DecryptFile(string inFile, string outFile, string password) { // 创建打开文件流 using (FileStream fin = File.OpenRead(inFile), fout = File.OpenWrite(outFile)) { int size = (int)fin.Length; byte[] bytes = new byte[BUFFER_SIZE]; int read = -1; int value = 0; int outValue = 0; byte[] IV = new byte[16]; fin.Read(IV, 0, 16); byte[] salt = new byte[16]; fin.Read(salt, 0, 16); SymmetricAlgorithm sma = DESFileClass.CreateRijndael(password, salt); sma.IV = IV; value = 32; long lSize = -1; // 创建散列对象, 校验文件 HashAlgorithm hasher = SHA256.Create(); using (CryptoStream cin = new CryptoStream(fin, sma.CreateDecryptor(), CryptoStreamMode.Read), chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write)) { // 读取文件长度 BinaryReader br = new BinaryReader(cin); lSize = br.ReadInt64(); ulong tag = br.ReadUInt64(); if (FC_TAG != tag) { throw new CryptoHelpException("文件被破坏"); } long numReads = lSize / BUFFER_SIZE; long slack = (long)lSize % BUFFER_SIZE; for (int i = 0; i < numReads; ++i) { read = cin.Read(bytes, 0, bytes.Length); fout.Write(bytes, 0, read); chash.Write(bytes, 0, read); value += read; outValue += read; } if (slack > 0) { read = cin.Read(bytes, 0, (int)slack); fout.Write(bytes, 0, read); chash.Write(bytes, 0, read); value += read; outValue += read; } chash.Flush(); chash.Close(); fout.Flush(); fout.Close(); byte[] curHash = hasher.Hash; // 获取比较和旧的散列对象 byte[] oldHash = new byte[hasher.HashSize / 8]; read = cin.Read(oldHash, 0, oldHash.Length); if ((oldHash.Length != read) || (!CheckByteArrays(oldHash, curHash))) { throw new CryptoHelpException("文件被破坏"); } } if (outValue != lSize) { throw new CryptoHelpException("文件大小不匹配"); } } }
public static byte[] GetHash(HashType type, Stream stream, long reportInterval, IProgress <long> progress) { HashAlgorithm hash = null; try { switch (type) { case HashType.MD5: hash = MD5.Create(); break; case HashType.SHA1: hash = SHA1.Create(); break; case HashType.SHA256: hash = SHA256.Create(); break; case HashType.SHA384: hash = SHA384.Create(); break; case HashType.SHA512: hash = SHA512.Create(); break; default: throw new InvalidOperationException("Invalid Hash Type"); } // No progress report if (reportInterval <= 0 || progress == null) { return(hash.ComputeHash(stream)); } // With progress report long nextReport = reportInterval; long offset = stream.Position; byte[] buffer = new byte[BufferSize]; int bytesRead; do { bytesRead = stream.Read(buffer, 0, buffer.Length); hash.TransformBlock(buffer, 0, bytesRead, buffer, 0); offset += bytesRead; if (nextReport <= offset) { progress.Report(offset); nextReport += reportInterval; } }while (0 < bytesRead); hash.TransformFinalBlock(buffer, 0, 0); return(hash.Hash); } finally { if (hash != null) { hash.Dispose(); } } }
public string DoSHA256(string input) { using (var sha256 = SHA256.Create()) return(ByteUtils.ByteToHexBitFiddle(sha256.ComputeHash(Encoding.UTF8.GetBytes(input)))); }
private void atkoduok() { _ = this.Invoke((Action) delegate { //atkoduoja katalogo failus- FolderBrowserDialog FBD = new FolderBrowserDialog(); if (FBD.ShowDialog() == DialogResult.OK) { //visi failai kataloge: string[] fileArray = Directory.GetFiles(FBD.SelectedPath); string password = "******"; // Array.ForEach(fileArray, Console.WriteLine); //for progress bar-------- int k = 0; //is viso rezultatu: var fileCount = fileArray.Count(); progressBar1.Minimum = 0; progressBar1.Maximum = fileCount; //for every file in the fileArray do this: foreach (string fileEncrypted in fileArray) { if (Path.GetFileName(fileEncrypted) == "md5.txt") { continue; } //apskaiciuojam md5 hash reiksme pries atkoduojant string reiksme = CalculateMD5(fileEncrypted); Console.WriteLine(reiksme); //if tokia reiksme neegzistuoja md5.txt - neleisti atkoduoti var lines = File.ReadAllLines("md5.txt"); if (!lines.Contains(reiksme)) { Console.WriteLine("neeigzistuoja toks md5"); break; } byte[] bytesToBeDecrypted = File.ReadAllBytes(fileEncrypted); byte[] passwordBytes = Encoding.UTF8.GetBytes(password); passwordBytes = SHA256.Create().ComputeHash(passwordBytes); byte[] bytesDecrypted = AES_Decrypt(bytesToBeDecrypted, passwordBytes); File.WriteAllBytes(fileEncrypted, bytesDecrypted); //Progress bar'o pildymas while (k <= fileCount) { progressBar1.Value = k; k++; } } } }); }
private async Task Restore(string password = "") { try { string contents; if (String.IsNullOrEmpty(password)) { contents = Encoding.UTF8.GetString(_fileData); } else { var sha256 = SHA256.Create(); var passwordBytes = Encoding.UTF8.GetBytes(password); var keyMaterial = sha256.ComputeHash(passwordBytes); var provider = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7); var key = provider.CreateSymmetricKey(keyMaterial); var raw = WinRTCrypto.CryptographicEngine.Decrypt(key, _fileData); contents = Encoding.UTF8.GetString(raw); _dialog.Dismiss(); } var backup = JsonConvert.DeserializeObject <Backup>(contents); if (backup.Authenticators == null) { Toast.MakeText(this, Resource.String.invalidFileError, ToastLength.Short).Show(); return; } var authsInserted = 0; var categoriesInserted = 0; foreach (var auth in backup.Authenticators.Where(auth => !_authSource.IsDuplicate(auth))) { auth.Validate(); await _connection.InsertAsync(auth); authsInserted++; } foreach (var category in backup.Categories.Where(category => !_categorySource.IsDuplicate(category))) { await _connection.InsertAsync(category); categoriesInserted++; } foreach (var binding in backup.AuthenticatorCategories.Where(binding => !_authSource.IsDuplicateCategoryBinding(binding))) { await _connection.InsertAsync(binding); } var message = String.Format(GetString(Resource.String.restoredFromBackup), authsInserted, categoriesInserted); Toast.MakeText(this, message, ToastLength.Long).Show(); Finish(); } catch (InvalidAuthenticatorException) { Toast.MakeText(this, Resource.String.invalidFileError, ToastLength.Short).Show(); } catch { _dialog.Error = GetString(Resource.String.restoreError); } }
/// <summary> /// Initializes a new instance of the <see cref="Sha256Hash"/> class. /// </summary> public Sha256Hash() : base() { this.Algorithm = SHA256.Create(); this.Name = HashAlgorithmName.SHA256.Name; }
internal string GenerateAssetManifest(Stream stream) { var assets = new AssetsManifestFileEntry[Assets.Length]; System.Threading.Tasks.Parallel.For(0, assets.Length, i => { var item = Assets[i]; var hash = item.GetMetadata("FileHash"); var url = item.GetMetadata("AssetUrl"); if (string.IsNullOrEmpty(hash)) { // Some files that are part of the service worker manifest may not have their hashes previously // calcualted. Calculate them at this time. using var sha = SHA256.Create(); using var file = File.OpenRead(item.ItemSpec); var bytes = sha.ComputeHash(file); hash = Convert.ToBase64String(bytes); } assets[i] = new AssetsManifestFileEntry { hash = "sha256-" + hash, url = url, }; }); var version = Version; if (string.IsNullOrEmpty(version)) { // If a version isn't specified (which is likely the most common case), construct a Version by combining // the file names + hashes of all the inputs. var combinedHash = string.Join( Environment.NewLine, assets.OrderBy(f => f.url, StringComparer.Ordinal).Select(f => f.hash)); using var sha = SHA256.Create(); var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(combinedHash)); version = Convert.ToBase64String(bytes).Substring(0, 8); } var data = new AssetsManifestFile { version = version, assets = assets, }; using var streamWriter = new StreamWriter(stream, Encoding.UTF8, bufferSize: 50, leaveOpen: true); streamWriter.Write("self.assetsManifest = "); streamWriter.Flush(); using var jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8, ownsStream: false, indent: true); new DataContractJsonSerializer(typeof(AssetsManifestFile)).WriteObject(jsonWriter, data); jsonWriter.Flush(); streamWriter.WriteLine(";"); return(version); }
/// <summary> /// Creates a PaswordHasher with a specified algorithm and custom options /// </summary> /// <param name="algorithm"></param> /// <param name="options"></param> public PasswordHasher(HashAlgorithm algorithm = null, PasswordHasherOptions options = null) { _hasher = algorithm != null ? new Hasher(algorithm) : new Hasher(SHA256.Create()); Options = PasswordHasherOptions.CreateMergedInstance(options); }
public ReversibleRenamer(string password) { cipher = new RijndaelManaged(); using (var sha = SHA256.Create()) cipher.Key = key = sha.ComputeHash(Encoding.UTF8.GetBytes(password)); }