public static string Hash(string input) { using (SHA1Managed sha1 = new SHA1Managed()) { var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input)); var sb = new StringBuilder(hash.Length * 2); foreach (byte b in hash) { // "x2" for lowercase sb.Append(b.ToString("X2")); } return sb.ToString(); } }
public static byte[] Get3DesSignatureInBytes(byte[] data, byte[] sharedSecret) { HashAlgorithm hash = new SHA1Managed(); byte[] hashedData = hash.ComputeHash(data); byte[] decryptedSignature = new byte[24]; for (int i = 0; i < hashedData.Length; i++) { decryptedSignature[i] = hashedData[i]; } for (int i = 20; i < decryptedSignature.Length; i++) { decryptedSignature[i] = (byte)0xFF; } TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); tdes.Key = sharedSecret; byte[] iv = new byte[8]; for (int i = 0; i < iv.Length; i++) { iv[i] = (byte)0x00; } tdes.IV = iv; tdes.Mode = CipherMode.CBC; ICryptoTransform transform = tdes.CreateEncryptor(); byte[] signature = new byte[24]; transform.TransformBlock(decryptedSignature, 0, decryptedSignature.Length, signature, 0); return signature; }
private static string SHA1Hash(string filePath) { using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) using (var hash = new SHA1Managed()) { var result = hash.ComputeHash(stream); return ByteArrayToHexString(result); } }
/// <summary> /// Получить SHA1 хеш потока файла. /// </summary> /// <param name="stream">Поток файла.</param> /// <returns>Хеш.</returns> public static string GetSHA1Hash(this FileStream stream) { var data = new byte[stream.Length]; stream.Read(data, 0, (int)stream.Length); SHA1Managed SHhash = new SHA1Managed(); var hash = SHhash.ComputeHash(data); var res = BitConverter.ToString(hash); return res.Replace("-", String.Empty); }
private static string HashPassword(string input) { var bytes = Encoding.UTF8.GetBytes(input); var output = new SHA1Managed().ComputeHash(bytes); var sb = new StringBuilder(); foreach (byte b in output) { sb.Append(b.ToString("X2")); } return sb.ToString(); }
public static string GetHash(string str) { //SHA-1 hashed with key // After that, a standard SHA hashing algorithm is applied and the output is base-64 encoded. // System uses SHA 1 hashing algorithm, as described in "Hartford Carrier Integration" document. System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); SHA1 sha = new SHA1Managed(); byte[] data = encoding.GetBytes(str); byte[] digest = sha.ComputeHash(data); string genHash = Convert.ToBase64String(digest); return genHash; }
public static string HashFromBytes(byte[] bytes) { using (SHA1Managed sha1 = new SHA1Managed()) { var hash = sha1.ComputeHash(bytes); StringBuilder sb = new StringBuilder(); foreach (byte b in bytes) { string hex = b.ToString("X2"); sb.Append(hex); } return sb.ToString(); } }
static string CalculateChecksum(Stream stream) { using (var bs = new BufferedStream(stream)) using (var sha1 = new SHA1Managed()) { var hash = sha1.ComputeHash(bs); var formatted = new StringBuilder(2*hash.Length); foreach (var b in hash) { formatted.AppendFormat("{0:X2}", b); } return formatted.ToString(); } }
public static string SHA1(string str) { Encoding enc = Encoding.GetEncoding("iso-8859-1"); using (SHA1Managed sha1 = new SHA1Managed()) { byte[] hash = sha1.ComputeHash(enc.GetBytes(str)); StringBuilder formatted = new StringBuilder(2 * hash.Length); foreach (byte b in hash) { formatted.AppendFormat("{0:X2}", b); } return formatted.ToString(); } }
public static byte[] GetDesSignatureInBytes(byte[] data, byte[] sharedSecret) { HashAlgorithm hash = new SHA1Managed(); byte[] hashedData = hash.ComputeHash(data); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); des.Key = sharedSecret; des.Mode = CipherMode.ECB; ICryptoTransform transform = des.CreateEncryptor(); byte[] signature = new byte[8]; transform.TransformBlock(hashedData, 0, signature.Length, signature, 0); return signature; }
public static string CalculateChecksum(string filename) { using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var bs = new BufferedStream(fs)) using (var sha1 = new SHA1Managed()) { var hash = sha1.ComputeHash(bs); var formatted = new StringBuilder(2 * hash.Length); foreach (var b in hash) { formatted.AppendFormat("{0:X2}", b); } return formatted.ToString(); } }
public HMACSHA1 (byte[] key, bool useManagedSha1) { m_hashName = "SHA1"; #if FEATURE_CRYPTO if (useManagedSha1) { #endif // FEATURE_CRYPTO m_hash1 = new SHA1Managed(); m_hash2 = new SHA1Managed(); #if FEATURE_CRYPTO } else { m_hash1 = new SHA1CryptoServiceProvider(); m_hash2 = new SHA1CryptoServiceProvider(); } #endif // FEATURE_CRYPTO HashSizeValue = 160; base.InitializeKey(key); }
void MakeIdenticon(string code) { byte[] data = Encoding.UTF8.GetBytes(code); //SHA1でハッシュ値取得 SHA1Managed sha1 = new SHA1Managed(); byte[] hash = sha1.ComputeHash(data); //リソース解放 sha1.Clear(); StringBuilder strbuilder = new StringBuilder(); foreach(byte b in hash){ strbuilder.Append(b.ToString("x2")); } string hash_str = strbuilder.ToString(); bool[,] pattern = CreatePattern(hash_str); MakeIdenticonPlane(pattern); }
public static string GetHash(string password) { byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(password); byte[] b2 = new SHA1Managed().ComputeHash(b); return Convert.ToBase64String(b2, 0, b2.Length); }
private bool Decrypt(string licence) { string[] splitLicense = licence.Split('-'); string plainText = (secret2 + splitLicense[0] + secret).ToUpper(); // Convert plain text into a byte array. byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); // Because we support multiple hashing algorithms, we must define // hash object as a common (abstract) base class. We will specify the // actual hashing algorithm class later during object creation. HashAlgorithm hash = new SHA1Managed(); // Compute hash value of our plain text with appended salt. byte[] hashBytes = hash.ComputeHash(plainTextBytes); char[] returnChar = Convert.ToBase64String(hashBytes).ToCharArray(); hashBytes = null; string returnString = ""; for (int i = 0; i < returnChar.Length; i++) { if (returnString.Length >= 8) { break; } if (((returnChar[i] >= 48) && (returnChar[i] <= 57)) || ((returnChar[i] >= 65) && (returnChar[i] <= 90)) || ((returnChar[i] >= 97) && (returnChar[i] <= 122))) { returnString += returnChar[i].ToString().ToUpper(); } } if (returnString.Length < 8) { //Pad the rest with 0 while (returnString.Length < 8) { returnString += "0"; } } try { licence = splitLicense[1] + splitLicense[2]; } catch { return (false); } if (licence == returnString) { return (true); } return (false); }
private static XmlElement GenerateXadesBesObject(XmlSignatureAppearance sap, String signatureId, String contentReferenceId, String signedPropertiesId, out XmlElement signedProperty) { HashAlgorithm md = new SHA1Managed(); X509Certificate cert = sap.GetCertificate(); XmlDocument doc = sap.GetXmlLocator().GetDocument(); XmlElement dsObject = doc.CreateElement("Object", SecurityConstants.XMLDSIG_URI); XmlElement QualifyingProperties = doc.CreateElement(SecurityConstants.XADES_QualifyingProperties, SecurityConstants.XADES_132_URI); QualifyingProperties.SetAttribute("Target", "#" + signatureId); XmlElement SignedProperties = doc.CreateElement(SecurityConstants.XADES_SignedProperties, SecurityConstants.XADES_132_URI); SignedProperties.SetAttribute("Id", signedPropertiesId); XmlElement SignedSignatureProperties = doc.CreateElement(SecurityConstants.XADES_SignedSignatureProperties, SecurityConstants.XADES_132_URI); XmlElement SigningTime = doc.CreateElement(SecurityConstants.XADES_SigningTime, SecurityConstants.XADES_132_URI); String result = sap.GetSignDate().ToString(SecurityConstants.SigningTimeFormat); SigningTime.AppendChild(doc.CreateTextNode(result)); SignedSignatureProperties.AppendChild(SigningTime); XmlElement SigningCertificate = doc.CreateElement(SecurityConstants.XADES_SigningCertificate, SecurityConstants.XADES_132_URI); XmlElement Cert = doc.CreateElement(SecurityConstants.XADES_Cert, SecurityConstants.XADES_132_URI); XmlElement CertDigest = doc.CreateElement(SecurityConstants.XADES_CertDigest, SecurityConstants.XADES_132_URI); XmlElement DigestMethod = doc.CreateElement(SecurityConstants.DigestMethod, SecurityConstants.XMLDSIG_URI); DigestMethod.SetAttribute(SecurityConstants.Algorithm, SecurityConstants.XMLDSIG_URI_SHA1); CertDigest.AppendChild(DigestMethod); XmlElement DigestValue = doc.CreateElement(SecurityConstants.DigestValue, SecurityConstants.XMLDSIG_URI); DigestValue.AppendChild(doc.CreateTextNode(Convert.ToBase64String(md.ComputeHash(cert.GetEncoded())))); CertDigest.AppendChild(DigestValue); Cert.AppendChild(CertDigest); XmlElement IssueSerial = doc.CreateElement(SecurityConstants.XADES_IssuerSerial, SecurityConstants.XADES_132_URI); XmlElement X509IssuerName = doc.CreateElement(SecurityConstants.X509IssuerName, SecurityConstants.XMLDSIG_URI); X509IssuerName.AppendChild(doc.CreateTextNode(GetX509IssuerName(cert))); IssueSerial.AppendChild(X509IssuerName); XmlElement X509SerialNumber = doc.CreateElement(SecurityConstants.X509SerialNumber, SecurityConstants.XMLDSIG_URI); X509SerialNumber.AppendChild(doc.CreateTextNode(GetX509SerialNumber(cert))); IssueSerial.AppendChild(X509SerialNumber); Cert.AppendChild(IssueSerial); SigningCertificate.AppendChild(Cert); SignedSignatureProperties.AppendChild(SigningCertificate); SignedProperties.AppendChild(SignedSignatureProperties); XmlElement SignedDataObjectProperties = doc.CreateElement(SecurityConstants.XADES_SignedDataObjectProperties, SecurityConstants.XADES_132_URI); XmlElement DataObjectFormat = doc.CreateElement(SecurityConstants.XADES_DataObjectFormat, SecurityConstants.XADES_132_URI); DataObjectFormat.SetAttribute(SecurityConstants.ObjectReference, "#" + contentReferenceId); String descr = sap.GetDescription(); if (descr != null) { XmlElement Description = doc.CreateElement(SecurityConstants.XADES_Description, SecurityConstants.XADES_132_URI); Description.AppendChild(doc.CreateTextNode(descr)); DataObjectFormat.AppendChild(Description); } XmlElement MimeType = doc.CreateElement(SecurityConstants.XADES_MimeType, SecurityConstants.XADES_132_URI); MimeType.AppendChild(doc.CreateTextNode(sap.GetMimeType())); DataObjectFormat.AppendChild(MimeType); String enc = sap.GetXmlLocator().GetEncoding(); if (enc != null) { XmlElement Encoding = doc.CreateElement(SecurityConstants.XADES_Encoding, SecurityConstants.XADES_132_URI); Encoding.AppendChild(doc.CreateTextNode(enc)); DataObjectFormat.AppendChild(Encoding); } SignedDataObjectProperties.AppendChild(DataObjectFormat); SignedProperties.AppendChild(SignedDataObjectProperties); QualifyingProperties.AppendChild(SignedProperties); dsObject.AppendChild(QualifyingProperties); signedProperty = SignedProperties; return(dsObject); }
public byte[] ToBytes(byte[] nonce, byte[] serverNonce, byte[] newNonce, byte[] encryptedAnswer) { this.newNonce = newNonce; AESKeyData key = AES.GenerateKeyDataFromNonces(serverNonce, newNonce); byte[] plaintextAnswer = AES.DecryptAES(key, encryptedAnswer); // logger.debug("plaintext answer: {0}", BitConverter.ToString(plaintextAnswer)); int g; BigInteger dhPrime; BigInteger ga; using (MemoryStream dhInnerData = new MemoryStream(plaintextAnswer)) { using (BinaryReader dhInnerDataReader = new BinaryReader(dhInnerData)) { byte[] hashsum = dhInnerDataReader.ReadBytes(20); uint code = dhInnerDataReader.ReadUInt32(); if (code != 0xb5890dba) { throw new InvalidOperationException($"invalid dh_inner_data code: {code}"); } // logger.debug("valid code"); byte[] nonceFromServer1 = dhInnerDataReader.ReadBytes(16); if (!nonceFromServer1.SequenceEqual(nonce)) { throw new InvalidOperationException("invalid nonce in encrypted answer"); } // logger.debug("valid nonce"); byte[] serverNonceFromServer1 = dhInnerDataReader.ReadBytes(16); if (!serverNonceFromServer1.SequenceEqual(serverNonce)) { throw new InvalidOperationException("invalid server nonce in encrypted answer"); } // logger.debug("valid server nonce"); g = dhInnerDataReader.ReadInt32(); dhPrime = new BigInteger(1, Serializers.Bytes.read(dhInnerDataReader)); ga = new BigInteger(1, Serializers.Bytes.read(dhInnerDataReader)); int serverTime = dhInnerDataReader.ReadInt32(); timeOffset = serverTime - (int)(Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds) / 1000); // logger.debug("g: {0}, dhprime: {1}, ga: {2}", g, dhPrime, ga); } } BigInteger b = new BigInteger(2048, new Random()); BigInteger gb = BigInteger.ValueOf(g).ModPow(b, dhPrime);// encrypt data generate public key _gab = ga.ModPow(b, dhPrime); // logger.debug("gab: {0}", gab); // prepare client dh inner data byte[] clientDHInnerDataBytes; using (MemoryStream clientDhInnerData = new MemoryStream()) { using (BinaryWriter clientDhInnerDataWriter = new BinaryWriter(clientDhInnerData)) { clientDhInnerDataWriter.Write(0x6643b654); // client_dh_inner_data clientDhInnerDataWriter.Write(nonce); clientDhInnerDataWriter.Write(serverNonce); clientDhInnerDataWriter.Write((long)0); // TODO: retry_id Serializers.Bytes.write(clientDhInnerDataWriter, gb.ToByteArrayUnsigned()); using (MemoryStream clientDhInnerDataWithHash = new MemoryStream()) { using (BinaryWriter clientDhInnerDataWithHashWriter = new BinaryWriter(clientDhInnerDataWithHash)) { using (SHA1 sha1 = new SHA1Managed()) { clientDhInnerDataWithHashWriter.Write(sha1.ComputeHash(clientDhInnerData.GetBuffer(), 0, (int)clientDhInnerData.Position)); clientDhInnerDataWithHashWriter.Write(clientDhInnerData.GetBuffer(), 0, (int)clientDhInnerData.Position); clientDHInnerDataBytes = clientDhInnerDataWithHash.ToArray(); } } } } } // logger.debug("client dh inner data papared len {0}: {1}", clientDHInnerDataBytes.Length, BitConverter.ToString(clientDHInnerDataBytes).Replace("-", "")); // encryption //TODO: uncomment encryption //byte[] clientDhInnerDataEncryptedBytes = clientDHInnerDataBytes; byte[] clientDhInnerDataEncryptedBytes = AES.EncryptAES(key, clientDHInnerDataBytes); // logger.debug("inner data encrypted {0}: {1}", clientDhInnerDataEncryptedBytes.Length, BitConverter.ToString(clientDhInnerDataEncryptedBytes).Replace("-", "")); // prepare set_client_dh_params byte[] setclientDhParamsBytes; using (MemoryStream setClientDhParams = new MemoryStream()) { using (BinaryWriter setClientDhParamsWriter = new BinaryWriter(setClientDhParams)) { setClientDhParamsWriter.Write(0xf5045f1f); setClientDhParamsWriter.Write(nonce); setClientDhParamsWriter.Write(serverNonce); Serializers.Bytes.write(setClientDhParamsWriter, clientDhInnerDataEncryptedBytes); setclientDhParamsBytes = setClientDhParams.ToArray(); } } // logger.debug("set client dh params prepared: {0}", BitConverter.ToString(setclientDhParamsBytes)); return(setclientDhParamsBytes); }
/// <summary> /// Generates a hash for the given plain text value and returns a /// base64-encoded result. Before the hash is computed, a random salt /// is generated and appended to the plain text. This salt is stored at /// the end of the hash value, so it can be used later for hash /// verification. /// </summary> /// <param name="plainText"> /// Plaintext value to be hashed. The function does not check whether /// this parameter is null. /// </param> /// <param name="hashAlgorithm"> /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1", /// "SHA256", "SHA384", and "SHA512" (if any other value is specified /// MD5 hashing algorithm will be used). This value is case-insensitive. /// </param> /// <param name="saltBytes"> /// Salt bytes. This parameter can be null, in which case a random salt /// value will be generated. /// </param> /// <returns> /// Hash value formatted as a base64-encoded string. /// </returns> public static string ComputeHash(string plainText, string hashAlgorithm, byte[] saltBytes) { // If salt is not specified, generate it on the fly. if (saltBytes == null) { // Define min and max salt sizes. int minSaltSize = 4; int maxSaltSize = 8; // Generate a random number for the size of the salt. Random random = new Random(); int saltSize = random.Next(minSaltSize, maxSaltSize); // Allocate a byte array, which will hold the salt. saltBytes = new byte[saltSize]; // Initialize a random number generator. RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); // Fill the salt with cryptographically strong byte values. rng.GetNonZeroBytes(saltBytes); } // Convert plain text into a byte array. byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); // Allocate array, which will hold plain text and salt. byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length]; // Copy plain text bytes into resulting array. for (int i = 0; i < plainTextBytes.Length; i++) { plainTextWithSaltBytes[i] = plainTextBytes[i]; } // Append salt bytes to the resulting array. for (int i = 0; i < saltBytes.Length; i++) { plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i]; } // Because we support multiple hashing algorithms, we must define // hash object as a common (abstract) base class. We will specify the // actual hashing algorithm class later during object creation. HashAlgorithm hash; // Make sure hashing algorithm name is specified. if (hashAlgorithm == null) { hashAlgorithm = ""; } // Initialize appropriate hashing algorithm class. switch (hashAlgorithm.ToUpper()) { case "SHA1": hash = new SHA1Managed(); break; case "SHA256": hash = new SHA256Managed(); break; case "SHA384": hash = new SHA384Managed(); break; case "SHA512": hash = new SHA512Managed(); break; default: hash = new MD5CryptoServiceProvider(); break; } // Compute hash value of our plain text with appended salt. byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes); // Create array which will hold hash and original salt bytes. byte[] hashWithSaltBytes = new byte[hashBytes.Length + saltBytes.Length]; // Copy hash bytes into resulting array. for (int i = 0; i < hashBytes.Length; i++) { hashWithSaltBytes[i] = hashBytes[i]; } // Append salt bytes to the result. for (int i = 0; i < saltBytes.Length; i++) { hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i]; } // Convert result into a base64-encoded string. string hashValue = Convert.ToBase64String(hashWithSaltBytes); // Return the result. return(hashValue); }
/// <summary> /// Solve the specified situation by using the session, storage, localFile and remoteId. /// If a folder is affected, simply update the local change time of the corresponding local folder. /// If it is a file and the changeToken is not equal to the saved, the new content is downloaded. /// </summary> /// <param name="localFile">Local file.</param> /// <param name="remoteId">Remote identifier.</param> /// <param name="localContent">Hint if the local content has been changed.</param> /// <param name="remoteContent">Information if the remote content has been changed.</param> public override void Solve( IFileSystemInfo localFile, IObjectId remoteId, ContentChangeType localContent = ContentChangeType.NONE, ContentChangeType remoteContent = ContentChangeType.NONE) { IMappedObject obj = this.Storage.GetObjectByRemoteId(remoteId.Id); if (remoteId is IFolder) { var remoteFolder = remoteId as IFolder; DateTime?lastModified = remoteFolder.LastModificationDate; obj.LastChangeToken = remoteFolder.ChangeToken; if (lastModified != null) { try { localFile.LastWriteTimeUtc = (DateTime)lastModified; } catch (IOException e) { Logger.Debug("Couldn't set the server side modification date", e); } obj.LastLocalWriteTimeUtc = localFile.LastWriteTimeUtc; } } else if (remoteId is IDocument) { byte[] lastChecksum = obj.LastChecksum; var remoteDocument = remoteId as IDocument; DateTime?lastModified = remoteDocument.LastModificationDate; if ((lastModified != null && lastModified != obj.LastRemoteWriteTimeUtc) || obj.LastChangeToken != remoteDocument.ChangeToken) { if (remoteContent != ContentChangeType.NONE) { if (obj.LastLocalWriteTimeUtc != localFile.LastWriteTimeUtc) { throw new ArgumentException("The local file has been changed since last write => aborting update"); } // Download changes var file = localFile as IFileInfo; var cacheFile = this.fsFactory.CreateDownloadCacheFileInfo(file); var transmissionEvent = new FileTransmissionEvent(FileTransmissionType.DOWNLOAD_MODIFIED_FILE, localFile.FullName, cacheFile.FullName); this.queue.AddEvent(transmissionEvent); this.transmissonManager.AddTransmission(transmissionEvent); using (SHA1 hashAlg = new SHA1Managed()) using (var filestream = cacheFile.Open(FileMode.Create, FileAccess.Write, FileShare.None)) using (IFileDownloader download = ContentTaskUtils.CreateDownloader()) { try { download.DownloadFile(remoteDocument, filestream, transmissionEvent, hashAlg); } catch (Exception ex) { transmissionEvent.ReportProgress(new TransmissionProgressEventArgs { FailedException = ex }); throw; } obj.ChecksumAlgorithmName = "SHA-1"; obj.LastChecksum = hashAlg.Hash; } var backupFile = this.fsFactory.CreateFileInfo(file.FullName + ".bak.sync"); Guid?uuid = file.Uuid; cacheFile.Replace(file, backupFile, true); try { file.Uuid = uuid; } catch (RestoreModificationDateException e) { Logger.Debug("Failed to restore modification date of original file", e); } try { backupFile.Uuid = null; } catch (RestoreModificationDateException e) { Logger.Debug("Failed to restore modification date of backup file", e); } byte[] checksumOfOldFile = null; using (var oldFileStream = backupFile.Open(FileMode.Open, FileAccess.Read, FileShare.None)) { checksumOfOldFile = SHA1Managed.Create().ComputeHash(oldFileStream); } if (!lastChecksum.SequenceEqual(checksumOfOldFile)) { var conflictFile = this.fsFactory.CreateConflictFileInfo(file); backupFile.MoveTo(conflictFile.FullName); OperationsLogger.Info(string.Format("Updated local content of \"{0}\" with content of remote document {1} and created conflict file {2}", file.FullName, remoteId.Id, conflictFile.FullName)); } else { backupFile.Delete(); OperationsLogger.Info(string.Format("Updated local content of \"{0}\" with content of remote document {1}", file.FullName, remoteId.Id)); } transmissionEvent.ReportProgress(new TransmissionProgressEventArgs { Completed = true }); } obj.LastRemoteWriteTimeUtc = remoteDocument.LastModificationDate; if (remoteDocument.LastModificationDate != null) { localFile.LastWriteTimeUtc = (DateTime)remoteDocument.LastModificationDate; } obj.LastLocalWriteTimeUtc = localFile.LastWriteTimeUtc; obj.LastContentSize = remoteDocument.ContentStreamLength ?? 0; } obj.LastChangeToken = remoteDocument.ChangeToken; obj.LastRemoteWriteTimeUtc = lastModified; } this.Storage.SaveMappedObject(obj); }
private void generateSHA1Hash() { SHA1 sha = new SHA1Managed(); String hashInput = m_transTimestamp + "." + m_transMerchantName + "." + m_transOrderID + "." + m_transAmount + "." + m_transCurrency + "." + m_transCard.CardNumber; String hashStage1 = hexEncode(sha.ComputeHash(Encoding.UTF8.GetBytes(hashInput))) + "." + m_normalPassword; String hashStage2 = hexEncode(sha.ComputeHash(Encoding.UTF8.GetBytes(hashStage1))); m_transSHA1Hash = hashStage2; }
public async Task <AuthKey> Generate(TelegramDC dc, int maxRetries) { ConnectedEvent += delegate {}; await ConnectAsync(dc, maxRetries); random.NextBytes(nonce); using (MemoryStream memoryStream = new MemoryStream()) { using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream)) { binaryWriter.Write(0x60469778); binaryWriter.Write(nonce); Send(memoryStream.ToArray()); } } completionSource = new TaskCompletionSource <byte[]>(); byte[] response = await completionSource.Task; BigInteger pq; List <byte[]> fingerprints = new List <byte[]>(); using (var memoryStream = new MemoryStream(response, false)) { using (var binaryReader = new BinaryReader(memoryStream)) { int responseCode = binaryReader.ReadInt32(); if (responseCode != 0x05162463) { logger.error("invalid response code: {0}", responseCode); return(null); } byte[] nonceFromServer = binaryReader.ReadBytes(16); if (!nonceFromServer.SequenceEqual(nonce)) { logger.debug("invalid nonce from server"); return(null); } serverNonce = binaryReader.ReadBytes(16); byte[] pqbytes = Serializers.Bytes.read(binaryReader); pq = new BigInteger(1, pqbytes); int vectorId = binaryReader.ReadInt32(); if (vectorId != 0x1cb5c415) { logger.debug("invalid fingerprints vector id: {0}", vectorId); return(null); } int fingerprintCount = binaryReader.ReadInt32(); for (int i = 0; i < fingerprintCount; i++) { byte[] fingerprint = binaryReader.ReadBytes(8); fingerprints.Add(fingerprint); } } } FactorizedPair pqPair = Factorizator.Factorize(pq); logger.debug("stage 1: ok"); random.NextBytes(newNonce); byte[] reqDhParamsBytes; using (MemoryStream pqInnerData = new MemoryStream(255)) { using (BinaryWriter pqInnerDataWriter = new BinaryWriter(pqInnerData)) { pqInnerDataWriter.Write(0x83c95aec); // pq_inner_data Serializers.Bytes.write(pqInnerDataWriter, pq.ToByteArrayUnsigned()); Serializers.Bytes.write(pqInnerDataWriter, pqPair.Min.ToByteArrayUnsigned()); Serializers.Bytes.write(pqInnerDataWriter, pqPair.Max.ToByteArrayUnsigned()); pqInnerDataWriter.Write(nonce); pqInnerDataWriter.Write(serverNonce); pqInnerDataWriter.Write(newNonce); logger.debug("pq_inner_data: {0}", BitConverter.ToString(pqInnerData.GetBuffer())); byte[] ciphertext = null; byte[] targetFingerprint = null; foreach (byte[] fingerprint in fingerprints) { ciphertext = RSA.Encrypt(BitConverter.ToString(fingerprint).Replace("-", string.Empty), pqInnerData.GetBuffer(), 0, (int)pqInnerData.Position); if (ciphertext != null) { targetFingerprint = fingerprint; break; } } if (ciphertext == null) { logger.error("not found valid key for fingerprints: {0}", String.Join(", ", fingerprints)); return(null); } using (MemoryStream reqDHParams = new MemoryStream(1024)) { using (BinaryWriter reqDHParamsWriter = new BinaryWriter(reqDHParams)) { reqDHParamsWriter.Write(0xd712e4be); // req_dh_params reqDHParamsWriter.Write(nonce); reqDHParamsWriter.Write(serverNonce); Serializers.Bytes.write(reqDHParamsWriter, pqPair.Min.ToByteArrayUnsigned()); Serializers.Bytes.write(reqDHParamsWriter, pqPair.Max.ToByteArrayUnsigned()); reqDHParamsWriter.Write(targetFingerprint); Serializers.Bytes.write(reqDHParamsWriter, ciphertext); logger.debug("sending req_dh_paras: {0}", BitConverter.ToString(reqDHParams.ToArray())); reqDhParamsBytes = reqDHParams.ToArray(); } } } } completionSource = new TaskCompletionSource <byte[]>(); Send(reqDhParamsBytes); response = await completionSource.Task; logger.debug("dh response: {0}", BitConverter.ToString(response)); byte[] encryptedAnswer; using (MemoryStream responseStream = new MemoryStream(response, false)) { using (BinaryReader responseReader = new BinaryReader(responseStream)) { uint responseCode = responseReader.ReadUInt32(); if (responseCode == 0x79cb045d) { // server_DH_params_fail logger.error("server_DH_params_fail: TODO"); return(null); } if (responseCode != 0xd0e8075c) { logger.error("invalid response code: {0}", responseCode); return(null); } byte[] nonceFromServer = responseReader.ReadBytes(16); if (!nonceFromServer.SequenceEqual(nonce)) { logger.debug("invalid nonce from server"); return(null); } byte[] serverNonceFromServer = responseReader.ReadBytes(16); if (!serverNonceFromServer.SequenceEqual(serverNonce)) { logger.error("invalid server nonce from server"); return(null); } encryptedAnswer = Serializers.Bytes.read(responseReader); } } logger.debug("encrypted answer: {0}", BitConverter.ToString(encryptedAnswer)); AESKeyData key = AES.GenerateKeyDataFromNonces(serverNonce, newNonce); byte[] plaintextAnswer = AES.DecryptAES(key, encryptedAnswer); logger.debug("plaintext answer: {0}", BitConverter.ToString(plaintextAnswer)); int g; BigInteger dhPrime; BigInteger ga; using (MemoryStream dhInnerData = new MemoryStream(plaintextAnswer)) { using (BinaryReader dhInnerDataReader = new BinaryReader(dhInnerData)) { byte[] hashsum = dhInnerDataReader.ReadBytes(20); uint code = dhInnerDataReader.ReadUInt32(); if (code != 0xb5890dba) { logger.error("invalid dh_inner_data code: {0}", code); return(null); } logger.debug("valid code"); byte[] nonceFromServer1 = dhInnerDataReader.ReadBytes(16); if (!nonceFromServer1.SequenceEqual(nonce)) { logger.error("invalid nonce in encrypted answer"); return(null); } logger.debug("valid nonce"); byte[] serverNonceFromServer1 = dhInnerDataReader.ReadBytes(16); if (!serverNonceFromServer1.SequenceEqual(serverNonce)) { logger.error("invalid server nonce in encrypted answer"); return(null); } logger.debug("valid server nonce"); g = dhInnerDataReader.ReadInt32(); dhPrime = new BigInteger(1, Serializers.Bytes.read(dhInnerDataReader)); ga = new BigInteger(1, Serializers.Bytes.read(dhInnerDataReader)); int serverTime = dhInnerDataReader.ReadInt32(); timeOffset = serverTime - (int)(Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds) / 1000); logger.debug("g: {0}, dhprime: {1}, ga: {2}", g, dhPrime, ga); } } BigInteger b = new BigInteger(2048, random); BigInteger gb = BigInteger.ValueOf(g).ModPow(b, dhPrime); BigInteger gab = ga.ModPow(b, dhPrime); logger.debug("gab: {0}", gab); // prepare client dh inner data byte[] clientDHInnerDataBytes; using (MemoryStream clientDhInnerData = new MemoryStream()) { using (BinaryWriter clientDhInnerDataWriter = new BinaryWriter(clientDhInnerData)) { clientDhInnerDataWriter.Write(0x6643b654); // client_dh_inner_data clientDhInnerDataWriter.Write(nonce); clientDhInnerDataWriter.Write(serverNonce); clientDhInnerDataWriter.Write((long)0); // TODO: retry_id Serializers.Bytes.write(clientDhInnerDataWriter, gb.ToByteArrayUnsigned()); using (MemoryStream clientDhInnerDataWithHash = new MemoryStream()) { using (BinaryWriter clientDhInnerDataWithHashWriter = new BinaryWriter(clientDhInnerDataWithHash)) { using (SHA1 sha1 = new SHA1Managed()) { clientDhInnerDataWithHashWriter.Write(sha1.ComputeHash(clientDhInnerData.GetBuffer(), 0, (int)clientDhInnerData.Position)); clientDhInnerDataWithHashWriter.Write(clientDhInnerData.GetBuffer(), 0, (int)clientDhInnerData.Position); clientDHInnerDataBytes = clientDhInnerDataWithHash.ToArray(); } } } } } logger.debug("client dh inner data papared len {0}: {1}", clientDHInnerDataBytes.Length, BitConverter.ToString(clientDHInnerDataBytes).Replace("-", "")); // encryption byte[] clientDhInnerDataEncryptedBytes = AES.EncryptAES(key, clientDHInnerDataBytes); logger.debug("inner data encrypted {0}: {1}", clientDhInnerDataEncryptedBytes.Length, BitConverter.ToString(clientDhInnerDataEncryptedBytes).Replace("-", "")); // prepare set_client_dh_params byte[] setclientDhParamsBytes; using (MemoryStream setClientDhParams = new MemoryStream()) { using (BinaryWriter setClientDhParamsWriter = new BinaryWriter(setClientDhParams)) { setClientDhParamsWriter.Write(0xf5045f1f); setClientDhParamsWriter.Write(nonce); setClientDhParamsWriter.Write(serverNonce); Serializers.Bytes.write(setClientDhParamsWriter, clientDhInnerDataEncryptedBytes); setclientDhParamsBytes = setClientDhParams.ToArray(); } } logger.debug("set client dh params prepared: {0}", BitConverter.ToString(setclientDhParamsBytes)); completionSource = new TaskCompletionSource <byte[]>(); Send(setclientDhParamsBytes); response = await completionSource.Task; using (MemoryStream responseStream = new MemoryStream(response)) { using (BinaryReader responseReader = new BinaryReader(responseStream)) { uint code = responseReader.ReadUInt32(); if (code == 0x3bcbf734) // dh_gen_ok { logger.debug("dh_gen_ok"); byte[] nonceFromServer = responseReader.ReadBytes(16); if (!nonceFromServer.SequenceEqual(nonce)) { logger.error("invalid nonce"); return(null); } byte[] serverNonceFromServer = responseReader.ReadBytes(16); if (!serverNonceFromServer.SequenceEqual(serverNonce)) { logger.error("invalid server nonce"); return(null); } byte[] newNonceHash1 = responseReader.ReadBytes(16); logger.debug("new nonce hash 1: {0}", BitConverter.ToString(newNonceHash1)); AuthKey authKey = new AuthKey(gab); byte[] newNonceHashCalculated = authKey.CalcNewNonceHash(newNonce, 1); if (!newNonceHash1.SequenceEqual(newNonceHashCalculated)) { logger.error("invalid new nonce hash"); return(null); } logger.info("generated new auth key: {0}", gab); logger.info("saving time offset: {0}", timeOffset); TelegramSession.Instance.TimeOffset = timeOffset; return(authKey); } else if (code == 0x46dc1fb9) // dh_gen_retry { logger.debug("dh_gen_retry"); return(null); } else if (code == 0xa69dae02) { // dh_gen_fail logger.debug("dh_gen_fail"); return(null); } else { logger.debug("dh_gen unknown: {0}", code); return(null); } } } }
protected override void CreateHasher() { _hasher = new SHA1Managed(); }
public bool Load(Stream stream) { _root = BencodingUtils.Decode(stream); if (_root == null) { return(false); } BDict dictRoot = (_root as BDict); if (dictRoot == null) { return(false); } if (dictRoot.ContainsKey("announce")) { Announce = (BString)dictRoot["announce"]; } if (dictRoot.ContainsKey("announce-list")) { BList announceList = (BList)dictRoot["announce-list"]; foreach (IBencodingType type in announceList) { if (type is BString) { AnnounceList.Add(type as BString); } else { BList list = type as BList; if (list == null) { continue; } BList listType = list; foreach (IBencodingType bencodingType in listType) { BString s = (BString)bencodingType; AnnounceList.Add(s); } } } } if (dictRoot.ContainsKey("comment")) { Comment = (BString)dictRoot["comment"]; } if (dictRoot.ContainsKey("created by")) { CreatedBy = (BString)dictRoot["created by"]; } if (dictRoot.ContainsKey("creation date")) { long ts = (BInt)dictRoot["creation date"]; CreationDate = new DateTime(1970, 1, 1).AddSeconds(ts); } if (dictRoot.ContainsKey("info")) { BDict infoDict = (BDict)dictRoot["info"]; using (SHA1Managed sha1 = new SHA1Managed()) { byte[] str = BencodingUtils.EncodeBytes(infoDict); Hash = sha1.ComputeHash(str); } if (infoDict.ContainsKey("files")) { //multi file mode BList fileList = (BList)infoDict["files"]; foreach (IBencodingType bencodingType in fileList) { BDict fileDict = (BDict)bencodingType; String filename = string.Empty; Int64 filesize = default(Int64); if (fileDict.ContainsKey("path")) { BList filenameList = (BList)fileDict["path"]; foreach (IBencodingType type in filenameList) { filename += (BString)type; filename += "\\"; } filename = filename.Trim('\\'); } if (fileDict.ContainsKey("length")) { filesize = (BInt)fileDict["length"]; } Files.Add(filename, filesize); } } if (infoDict.ContainsKey("name")) { Name = (BString)infoDict["name"]; if (Files.Count == 0 && infoDict.ContainsKey("length")) { Files.Add(Name, (BInt)infoDict["length"]); } } if (infoDict.ContainsKey("private")) { BInt isPrivate = (BInt)infoDict["private"]; Private = isPrivate != 0; } if (infoDict.ContainsKey("pieces")) { BString pieces = (BString)infoDict["pieces"]; for (int x = 0; x < pieces.ByteValue.Length; x += 20) { byte[] hash = pieces.ByteValue.GetBytes(x, 20); PieceHashes.Add(hash); } } if (infoDict.ContainsKey("piece length")) { PieceSize = (BInt)infoDict["piece length"]; } } return(true); }
public static void Sha1(this ReadOnlyByteSequence data, ByteSpan hash) { using var sha = new SHA1Managed(); sha.TransformFinalBlock(data, hash); }
public static string Hash(string userPassword) { return (BitConverter.ToString(SHA1Managed.Create().ComputeHash(Encoding.Default.GetBytes(userPassword))).Replace ("-", "")); }
public static async Task <MemoryStream> HitAsync(string url) { if (!Directory.Exists(AppCacheDirectory)) { Directory.CreateDirectory(AppCacheDirectory); } if (!Uri.TryCreate(url, UriKind.Absolute, out Uri uri)) { return(null); } var fileNameBuilder = new StringBuilder(); using (var sha1 = new SHA1Managed()) { var canonicalUrl = uri.ToString(); var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(canonicalUrl)); fileNameBuilder.Append(BitConverter.ToString(hash).Replace("-", "").ToLower()); if (Path.HasExtension(canonicalUrl)) { fileNameBuilder.Append(Path.GetExtension(canonicalUrl.Split('?')[0])); } } var fileName = fileNameBuilder.ToString(); var localFile = Path.Combine(AppCacheDirectory, fileName); var memoryStream = new MemoryStream(); FileStream fileStream = null; if (!_isWritingFile.ContainsKey(fileName) && File.Exists(localFile)) { await using (fileStream = new FileStream(localFile, FileMode.Open, FileAccess.Read)) { await fileStream.CopyToAsync(memoryStream); } memoryStream.Seek(0, SeekOrigin.Begin); return(memoryStream); } try { var responseStream = await _httpClient.GetStreamAsync(uri); if (responseStream == null) { return(null); } if (!_isWritingFile.ContainsKey(fileName)) { _isWritingFile[fileName] = true; fileStream = new FileStream(localFile, FileMode.Create, FileAccess.Write); } await using (responseStream) { var bytebuffer = new byte[1024]; int bytesRead; do { bytesRead = await responseStream.ReadAsync(bytebuffer, 0, 1024); if (fileStream != null) { await fileStream.WriteAsync(bytebuffer, 0, bytesRead); } await memoryStream.WriteAsync(bytebuffer, 0, bytesRead); } while (bytesRead > 0); if (fileStream != null) { await fileStream.FlushAsync(); fileStream.Dispose(); _isWritingFile.Remove(fileName); } } memoryStream.Seek(0, SeekOrigin.Begin); return(memoryStream); } catch (HttpRequestException) { return(null); } }
private string Sha1(string input) { byte[] hash = new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(input)); return(string.Concat(hash.Select(b => b.ToString("x2")))); }
/// <summary> /// Hash a string using SHA1 /// </summary> /// <param name="str">The string</param> /// <returns>The hex representation of the hash</returns> public static string Sha1(this string str) { if (str == null) { return null; } byte[] data = Encoding.UTF8.GetBytes(str); using (SHA1Managed sha = new SHA1Managed()) { byte[] hashBytes = sha.ComputeHash(data); return BitConverter.ToString(hashBytes).Replace("-", string.Empty).ToLowerInvariant(); } }
//=============================================================================== // Name: Function IALUGenerator_GenKey // Input: // ByRef Lic As ActiveLock3.ProductLicense - Product license // ByVal InstCode As String - Installation Code sent by the user // ByVal RegisteredLevel As String - Registration Level for the license. Default is "0" // Output: // String - Liberation key for the license // Purpose: Given the Installation Code, generates an Activelock license liberation key. // Remarks: None //=============================================================================== private string IALUGenerator_GenKey(ref ActiveLock3_6NET.ProductLicense Lic, string InstCode, [System.Runtime.InteropServices.OptionalAttribute, System.Runtime.InteropServices.DefaultParameterValueAttribute("0")] // ERROR: Optional parameters aren't supported in C# string RegisteredLevel) { // Take request code and decrypt it. string strReq = null; // 05.13.05 - ialkan Modified to merge DLLs into one strReq = modBase64.Base64_Decode(ref InstCode); // strReq now contains the {LockCode + vbLf + User} string string strLock = string.Empty; string strUser = string.Empty; GetLockAndUserFromInstallCode(strReq, ref strLock, ref strUser); Lic.Licensee = strUser; // registration date string strRegDate = null; // registered level Lic.RegisteredLevel = RegisteredLevel; strRegDate = Lic.RegisteredDate; string strEncrypted = null; // @todo Rethink this bit about encrypting the dates. // We need to keep in mind that the app does not have access to the private key, so and any decryption that requires private key // would not be possible. // Perhaps instead of encrypting, we could do MD5 hash of (regdate+lockcode)? //ActiveLockEventSink_ValidateValue strRegDate, strEncrypted // hash it //strEncrypted = ActiveLock3.MD5Hash(strEncrypted) strEncrypted = strRegDate; // get software codes ProductInfo ProdInfo = null; ProdInfo = IALUGenerator_RetrieveProduct(Lic.ProductName, Lic.ProductVer); Lic.ProductKey = ProdInfo.VCode; //@todo Check for "ProdInfo Is Nothing" and handle appropriately string strLic = null; strLic = Lic.ToString_Renamed() + Constants.vbLf + strLock; System.Diagnostics.Debug.WriteLine("strLic: " + Constants.vbCrLf + strLic); if (modALUGEN.strLeft(ProdInfo.VCode, 3) != "RSA") { // sign it string strSig = null; strSig = new string(Strings.Chr(0), 1024); // 05.13.05 - ialkan Modified to merge DLLs into one. Moved RSASign into a module strSig = modActiveLock.RSASign(ProdInfo.VCode, ProdInfo.GCode, strLic); // Create liberation key. This will be a base-64 encoded string of the whole license. string strLicKey = null; // 05.13.05 - ialkan Modified to merge DLLs into one strLicKey = modBase64.Base64_Encode(ref strSig); // update Lic with license key Lic.LicenseKey = strLicKey; // Print some info for debugging purposes System.Diagnostics.Debug.WriteLine("VCode: " + ProdInfo.VCode); System.Diagnostics.Debug.WriteLine("Lic: " + strLic); System.Diagnostics.Debug.WriteLine("Lic hash: " + modMD5.Hash(ref strLic)); System.Diagnostics.Debug.WriteLine("LicKey: " + strLicKey); System.Diagnostics.Debug.WriteLine("Sig: " + strSig); System.Diagnostics.Debug.WriteLine("Verify: " + modActiveLock.RSAVerify(ProdInfo.VCode, strLic, modBase64.Base64_Decode(ref strLicKey))); System.Diagnostics.Debug.WriteLine("===================================================="); } else { try { System.Security.Cryptography.RSACryptoServiceProvider rsaCSP = new System.Security.Cryptography.RSACryptoServiceProvider(); string strPublicBlob = null; string strPrivateBlob = null; strPublicBlob = ProdInfo.VCode; strPrivateBlob = ProdInfo.GCode; if (modALUGEN.strLeft(ProdInfo.GCode, 6) == "RSA512") { strPrivateBlob = modALUGEN.strRight(ProdInfo.GCode, Strings.Len(ProdInfo.GCode) - 6); } else { strPrivateBlob = modALUGEN.strRight(ProdInfo.GCode, Strings.Len(ProdInfo.GCode) - 7); } // import private key params into instance of RSACryptoServiceProvider rsaCSP.FromXmlString(strPrivateBlob); RSAParameters rsaPrivateParams = default(RSAParameters); //stores private key rsaPrivateParams = rsaCSP.ExportParameters(true); rsaCSP.ImportParameters(rsaPrivateParams); byte[] userData = Encoding.UTF8.GetBytes(strLic); AsymmetricSignatureFormatter asf = new RSAPKCS1SignatureFormatter(rsaCSP); HashAlgorithm algorithm = new SHA1Managed(); asf.SetHashAlgorithm(algorithm.ToString()); byte[] myhashedData = null; // a byte array to store hash value string myhashedDataString = null; myhashedData = algorithm.ComputeHash(userData); myhashedDataString = BitConverter.ToString(myhashedData).Replace("-", string.Empty); byte[] mysignature = null; // holds signatures mysignature = asf.CreateSignature(algorithm); string mySignatureBlock = null; mySignatureBlock = Convert.ToBase64String(mysignature); } catch (Exception ex) { modActiveLock.Set_Locale(modActiveLock.regionalSymbol); Err().Raise(AlugenGlobals.alugenErrCodeConstants.alugenProdInvalid, modTrial.ACTIVELOCKSTRING, ex.Message); } } // Serialize it into a formatted string string strLibKey = string.Empty; Lic.Save(ref strLibKey); return(strLibKey); }
public static byte[] GenerateHash(string value, string salt) { byte[] data = Encoding.ASCII.GetBytes(salt + value); data = SHA1Managed.Create().ComputeHash(data); return(data); }
protected string SHA1String(string input) { using (SHA1Managed sha1 = new SHA1Managed()) { var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input)); var 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().ToLower(); } }
public static string ComputeHash(string plainText, string hashAlgorithm, string salt) { byte[] saltBytes = Convert.FromBase64String(salt); // Convert plain text into a byte array. byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); // Allocate array, which will hold plain text and salt. byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length]; // Copy plain text bytes into resulting array. for (int i = 0; i < plainTextBytes.Length; i++) { plainTextWithSaltBytes[i] = plainTextBytes[i]; } // Append salt bytes to the resulting array. for (int i = 0; i < saltBytes.Length; i++) { plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i]; } // Because we support multiple hashing algorithms, we must define // hash object as a common (abstract) base class. We will specify the // actual hashing algorithm class later during object creation. HashAlgorithm hash; // Make sure hashing algorithm name is specified. if (hashAlgorithm == null) { hashAlgorithm = ""; } // Initialize appropriate hashing algorithm class. switch (hashAlgorithm.ToUpper()) { case "SHA1": hash = new SHA1Managed(); break; case "SHA256": hash = new SHA256Managed(); break; case "SHA384": hash = new SHA384Managed(); break; case "SHA512": hash = new SHA512Managed(); break; default: hash = new MD5CryptoServiceProvider(); break; } // Compute hash value of our plain text with appended salt. byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes); // Create array which will hold hash and original salt bytes. byte[] hashWithSaltBytes = new byte[hashBytes.Length + saltBytes.Length]; // Copy hash bytes into resulting array. for (int i = 0; i < hashBytes.Length; i++) { hashWithSaltBytes[i] = hashBytes[i]; } // Append salt bytes to the result. for (int i = 0; i < saltBytes.Length; i++) { hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i]; } // Convert result into a base64-encoded string. string hashValue = Convert.ToBase64String(hashWithSaltBytes); // Return the result. return(hashValue); }
public static void Start(ref BootParam param) { Console.WriteLine("Hello from ExpressOS-Managed"); ArchGlobals.Initialize(ref param); Globals.Initialize(ref param); SyscallProfiler.Initialize(); Misc.Initialize(); FileSystem.Initialize(); AESManaged.Initialize(); SHA1Managed.Initialize(); AndroidApplicationInfo appInfo = new AndroidApplicationInfo(); var appName = "me.haohui.expressos.browserbench"; appInfo.PackageName = appName; appInfo.uid = 1002; appInfo.flags = 0x8be45; appInfo.SourceDir = "/system/app/BrowserBench.apk"; appInfo.DataDir = "/data/data/" + appName; appInfo.Enabled = true; appInfo.TargetSdkVersion = 10; appInfo.Intent = appName + "/" + appName + ".BrowserActivity"; #if false var argv = new ASCIIString[] { new ASCIIString("/system/bin/simple-hello"), }; var envp = new ASCIIString[] { //new ASCIIString("LD_PRELOAD=/system/lib/libr2.so"), //new ASCIIString("HH_DEBUG=1"), }; #elif false var argv = new ASCIIString[] { new ASCIIString("/system/bin/bench-sqlite"), new ASCIIString("/data/data/com.valkyrie/1.db"), }; var envp = new ASCIIString[] { }; #elif false var argv = new ASCIIString[] { new ASCIIString("/system/bin/bench-bootanim"), }; var envp = new ASCIIString[] { new ASCIIString("CLASSPATH=/system/framework/am.jar"), new ASCIIString("PATH=/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin"), new ASCIIString("LD_LIBRARY_PATH=/vendor/lib:/system/lib"), new ASCIIString("ANDROID_BOOTLOGO=1"), new ASCIIString("ANDROID_ROOT=/system"), new ASCIIString("ANDROID_ASSETS=/system/app"), new ASCIIString("ANDROID_DATA=/data"), new ASCIIString("EXTERNAL_STORAGE=/mnt/sdcard"), new ASCIIString("ASEC_MOUNTPOINT=/mnt/asec"), new ASCIIString("LOOP_MOUNTPOINT=/mnt/obb"), new ASCIIString("BOOTCLASSPATH=/system/framework/core.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/android.policy.jar:/system/framework/services.jar:/system/framework/core-junit.jar"), // new ASCIIString("LD_PRELOAD=/system/lib/libr2.so"), }; #elif false var argv = new ASCIIString[] { new ASCIIString("/data/presenter"), }; var envp = new ASCIIString[] { new ASCIIString("CLASSPATH=/system/framework/am.jar"), new ASCIIString("PATH=/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin"), new ASCIIString("LD_LIBRARY_PATH=/vendor/lib:/system/lib"), new ASCIIString("ANDROID_BOOTLOGO=1"), new ASCIIString("ANDROID_ROOT=/system"), new ASCIIString("ANDROID_ASSETS=/system/app"), new ASCIIString("ANDROID_DATA=/data"), new ASCIIString("EXTERNAL_STORAGE=/mnt/sdcard"), new ASCIIString("ASEC_MOUNTPOINT=/mnt/asec"), new ASCIIString("LOOP_MOUNTPOINT=/mnt/obb"), new ASCIIString("BOOTCLASSPATH=/system/framework/core.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/android.policy.jar:/system/framework/services.jar:/system/framework/core-junit.jar"), new ASCIIString("SLIDES=/data/slides.zip"), }; #elif false var argv = new ASCIIString[] { new ASCIIString("/system/bin/bench-vbinder"), }; var envp = new ASCIIString[] { }; #elif false var argv = new ASCIIString[] { new ASCIIString("/system/xbin/wget"), new ASCIIString("http://128.174.236.238"), }; var envp = new ASCIIString[] { }; #elif false var argv = new ASCIIString[] { new ASCIIString("/system/bin/app_process"), new ASCIIString("/system/bin"), new ASCIIString("com.android.commands.am.Am"), new ASCIIString("start"), new ASCIIString("-a"), new ASCIIString("android.intent.action.MAIN"), new ASCIIString("-n"), new ASCIIString("com.valkyrie/com.valkyrie.HelloAndroidActivity"), }; var envp = new ASCIIString[] { new ASCIIString("CLASSPATH=/system/framework/am.jar"), new ASCIIString("PATH=/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin"), new ASCIIString("LD_LIBRARY_PATH=/vendor/lib:/system/lib"), new ASCIIString("ANDROID_BOOTLOGO=1"), new ASCIIString("ANDROID_ROOT=/system"), new ASCIIString("ANDROID_ASSETS=/system/app"), new ASCIIString("ANDROID_DATA=/data"), new ASCIIString("EXTERNAL_STORAGE=/mnt/sdcard"), new ASCIIString("ASEC_MOUNTPOINT=/mnt/asec"), new ASCIIString("LOOP_MOUNTPOINT=/mnt/obb"), new ASCIIString("BOOTCLASSPATH=/system/framework/core.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/android.policy.jar:/system/framework/services.jar:/system/framework/core-junit.jar"), /*new ASCIIString("HH_DEBUG=1"), */ }; #elif true var argv = new ASCIIString[] { new ASCIIString("/system/bin/app_process"), new ASCIIString("/system/bin"), new ASCIIString("android.app.ActivityThread"), }; var envp = new ASCIIString[] { new ASCIIString("CLASSPATH=/system/framework/am.jar"), new ASCIIString("PATH=/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin"), new ASCIIString("LD_LIBRARY_PATH=/vendor/lib:/system/lib"), new ASCIIString("ANDROID_BOOTLOGO=1"), new ASCIIString("ANDROID_ROOT=/system"), new ASCIIString("ANDROID_ASSETS=/system/app"), new ASCIIString("ANDROID_DATA=/data"), new ASCIIString("EXTERNAL_STORAGE=/mnt/sdcard"), new ASCIIString("ASEC_MOUNTPOINT=/mnt/asec"), new ASCIIString("LOOP_MOUNTPOINT=/mnt/obb"), new ASCIIString("BOOTCLASSPATH=/system/framework/core.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/android.policy.jar:/system/framework/services.jar:/system/framework/core-junit.jar"), new ASCIIString("HH_DEBUG=1"), /* new ASCIIString("LD_PRELOAD=/libr2.so"), */ }; #else var argv = new ASCIIString[] { new ASCIIString("/system/bin/app_process"), new ASCIIString("-Xgc:preverify"), new ASCIIString("-Xgc:postverify"), new ASCIIString("-Xgc:verifycardtable"), new ASCIIString("/system/bin"), new ASCIIString("android.os.GcTests"), }; var envp = new ASCIIString[] { new ASCIIString("CLASSPATH=/system/framework/frameworkcoretests.jar"), new ASCIIString("PATH=/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin"), new ASCIIString("LD_LIBRARY_PATH=/vendor/lib:/system/lib"), new ASCIIString("ANDROID_BOOTLOGO=1"), new ASCIIString("ANDROID_ROOT=/system"), new ASCIIString("ANDROID_ASSETS=/system/app"), new ASCIIString("ANDROID_DATA=/data"), new ASCIIString("EXTERNAL_STORAGE=/mnt/sdcard"), new ASCIIString("ASEC_MOUNTPOINT=/mnt/asec"), new ASCIIString("LOOP_MOUNTPOINT=/mnt/obb"), new ASCIIString("BOOTCLASSPATH=/system/framework/core.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/android.policy.jar:/system/framework/services.jar:/system/framework/core-junit.jar"), new ASCIIString("HH_DEBUG=1"), //new ASCIIString("LD_PRELOAD=/libr2.so"), }; #endif var proc = ExpressOS.Kernel.Exec.CreateProcess(argv[0], argv, envp, appInfo); if (proc == null) { Console.WriteLine("Cannot start init"); } Globals.SecurityManager.OnActiveProcessChanged(proc); Console.WriteLine("ExpressOS initialized"); Looper.ServerLoop(); }
static void Main(string[] args) { if (args.Length != 1) { throw new InvalidOperationException("Specify directory at the command line"); } var lines = new List <Line>(); var basePath = args[0]; if (!basePath.EndsWith("\\")) { basePath += "\\"; } foreach (string path in Directory.GetFiles(basePath, "*", SearchOption.AllDirectories)) { string hashString; long length; using (var stream = File.OpenRead(path)) { length = stream.Length; stream.Position = 0; using (var sha = new SHA1Managed()) { var hash = sha.ComputeHash(stream); hashString = BitConverter.ToString(hash).Replace("-", "").ToLower(); } } if (!path.StartsWith(basePath)) { throw new InvalidOperationException(); } lines.Add(new Line( path.Substring(basePath.Length), length, new FileInfo(path).LastWriteTime, hashString )); } lines.Sort((a, b) => String.Compare(a.Path, b.Path, StringComparison.InvariantCultureIgnoreCase)); using (var target = new StreamWriter("out.txt")) { target.WriteLine("Path\tLength\tTime\tHash"); foreach (var line in lines) { target.WriteLine( new StringBuilder() .Append(line.Path) .Append('\t') .Append(line.Length) .Append('\t') .Append(line.Time.ToString("yyyy-MM-dd hh:mm:ss")) .Append('\t') .Append(line.Hash) .ToString() ); } } }
/// <summary> /// Generates a hash for the given plain text value and returns a /// base64-encoded result. Before the hash is computed, a random salt /// is generated and appended to the plain text. This salt is stored at /// the end of the hash value, so it can be used later for hash /// verification. /// </summary> /// <param name="plainText"> /// Plaintext value to be hashed. /// </param> /// <param name="hashAlgorithm"> /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1", /// "SHA256", "SHA384", and "SHA512" (if any other value is specified /// MD5 hashing algorithm will be used). This value is case-insensitive. /// </param> /// <param name="saltBytes"> /// Optinoal salt bytes to apply to the hash. If not passed the /// raw encoding is used. /// </param> /// <returns> /// Hash value formatted as a base64-encoded string. /// </returns> public static string ComputeHash(string plainText, string hashAlgorithm, byte[] saltBytes, bool useBinHex = false) { if (string.IsNullOrEmpty(plainText)) { return(plainText); } // Convert plain text into a byte array. byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); byte[] plainTextWithSaltBytes; if (saltBytes != null) { // Allocate array, which will hold plain text and salt. plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length]; // Copy plain text bytes into resulting array. for (int i = 0; i < plainTextBytes.Length; i++) { plainTextWithSaltBytes[i] = plainTextBytes[i]; } // Append salt bytes to the resulting array. for (int i = 0; i < saltBytes.Length; i++) { plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i]; } } else { plainTextWithSaltBytes = plainTextBytes; } HashAlgorithm hash; // Make sure hashing algorithm name is specified. if (hashAlgorithm == null) { hashAlgorithm = ""; } // Initialize appropriate hashing algorithm class. switch (hashAlgorithm.ToUpper()) { case "SHA1": hash = new SHA1Managed(); break; case "SHA256": hash = new SHA256Managed(); break; case "SHA384": hash = new SHA384Managed(); break; case "SHA512": hash = new SHA512Managed(); break; default: // default to MD5 hash = new MD5CryptoServiceProvider(); break; } byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes); if (useBinHex) { return(BinaryToBinHex(hashBytes)); } return(Convert.ToBase64String(hashBytes)); }
protected void upload_button_Click(object sender, EventArgs e) { if (upload_element.HasFile) { string chosen_name = Path.GetFileName(upload_element.FileName); string extension = ""; bool found = false; bool isGB = false; string nameonly = ""; string ext = ""; if (chosen_name.Length > 3) { extension = chosen_name.Substring(chosen_name.Length - 4).ToUpper(); if (extension != ".NES" && extension != ".GBC" && extension != ".GBA" && extension != ".SMS" && (!extension.EndsWith(".GB"))) { unsuccessful(null); return; } else { if (extension.EndsWith(".GB")) { isGB = true; } } } else { unsuccessful(null); return; } upload_element.SaveAs(Server.MapPath("~/ROMS/") + chosen_name); if (!isGB) { nameonly = chosen_name.Remove(chosen_name.Length - 4); ext = extension.Substring(extension.Length - 3); } else { nameonly = chosen_name.Remove(chosen_name.Length - 3); ext = "GB"; extension = ".GB"; } nameonly = (Regex.Replace(nameonly, @"\s*?(?:\(.*?\)|\[.*?\]|\{.*?\})", String.Empty)).Trim(); // Remover todo o conteúdo entre (), [] ou {} string hashstring = ""; using (FileStream stream = File.OpenRead(Server.MapPath("~/ROMS/") + chosen_name)) { SHA1Managed sha = new SHA1Managed(); byte[] hash = sha.ComputeHash(stream); hashstring = BitConverter.ToString(hash).Replace("-", String.Empty); } if (findCandidates(nameonly, ext, hashstring, true).Count != 0) { System.Diagnostics.Debug.WriteLine("Existe um rom com este hash!" + nameonly + " " + ext); found = true; } else { System.Diagnostics.Debug.WriteLine("Não existe um rom com este hash!" + nameonly + " " + ext); } FileInfo saved_rom = new FileInfo(Server.MapPath("~/ROMS/") + chosen_name); if (saved_rom.Exists) { if (found) { saved_rom.Delete(); } else { FileInfo hashed_check = new FileInfo(Server.MapPath("~/ROMS/") + hashstring + extension); if (!hashed_check.Exists) { saved_rom.MoveTo(Server.MapPath("~/ROMS/") + hashstring + extension); } } } uploadSucceeded(nameonly, ext, hashstring, found); } }
/// <summary> /// Compares C# patterscan implementations. /// Uses a memory dump from main module of blender 2.64a 64bit as a target. /// </summary> /// <remarks>https://download.blender.org/release/Blender2.64/blender-2.64a-release-windows64.zip</remarks> internal static void Main(string[] args) { Console.Title = "Patternscan Benchmark"; Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine(@" ____ __ __ "); Console.WriteLine(@" / __ \____ _/ /_/ /____ _________ "); Console.WriteLine(@" / /_/ / __ `/ __/ __/ _ \/ ___/ __ \"); Console.WriteLine(@" / ____/ /_/ / /_/ /_/ __/ / / / / /"); Console.WriteLine(@"/_/ \__,_/\__/\__/\___/_/ /_/ /_/ "); Console.WriteLine(@" "); Console.WriteLine(" scan benchmark"); Console.WriteLine(" - C# version -"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Gray; PrintInfo(string.Format("{0} iterations | {1} patterns", ITERATIONS, TARGET_PATTERNS.Count)); Console.Write("To start press ENTER..."); Console.ReadLine(); Console.WriteLine(""); if (IntPtr.Size != 8) { throw new PlatformNotSupportedException("Supports x64 only"); } // get dump string memoryDumpPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + @"\memorydump.dat"; if (!File.Exists(memoryDumpPath)) { memoryDumpPath = Path.Combine(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "..", "..", ".."), "Memorydump") + @"\memorydump.dat"; if (!File.Exists(memoryDumpPath)) { throw new FileNotFoundException("Memory dump not found"); } } // read bytes and check hash byte[] moduleMemory = File.ReadAllBytes(memoryDumpPath); using (SHA1Managed sha1Managed = new SHA1Managed()) { byte[] hash = sha1Managed.ComputeHash(moduleMemory); string sha1 = string.Concat(hash.Select(b => b.ToString("x2"))); if (!sha1.Equals(TARGET_HASH, StringComparison.OrdinalIgnoreCase)) { throw new BadImageFormatException("Memory dump corrupted"); } } GC.KeepAlive(moduleMemory); // generate byte patterns and masks from string patterns List <MemoryPattern> memoryPatterns = new List <MemoryPattern>(); foreach (KeyValuePair <long, string> entry in TARGET_PATTERNS) { MemoryPattern memoryPattern = new MemoryPattern(entry.Key, entry.Value); memoryPatterns.Add(memoryPattern); } GC.KeepAlive(memoryPatterns); // bench all algorithms Stopwatch stopWatch = new Stopwatch(); foreach (KeyValuePair <string, PatternScanAlgorithm> patternScanAlgorithm in PATTERN_SCAN_ALGORITHMS) { GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true); PrintInfo(patternScanAlgorithm.Key + " - by " + patternScanAlgorithm.Value.Creator); long[] results = new long[ITERATIONS]; long lastRun = 0; bool algoSuccess = true; stopWatch.Restart(); string message = patternScanAlgorithm.Value.Init(in moduleMemory); for (int run = 0; run < ITERATIONS; run++) { if (!stopWatch.IsRunning) { stopWatch.Restart(); } foreach (MemoryPattern memoryPattern in memoryPatterns) { if (patternScanAlgorithm.Value.FindPattern(in moduleMemory, in memoryPattern.CbPattern, memoryPattern.SzMask) == memoryPattern.ExpectedAddress) { continue; } algoSuccess = false; break; } stopWatch.Stop(); if (!algoSuccess) { break; } results[run] = stopWatch.ElapsedMilliseconds; } if (!algoSuccess) { PrintError("failed..." + (message != "" ? " (" + message + ")" : "")); } else { PrintResults(results, message); } } Console.WriteLine(""); Console.WriteLine("finished..."); Console.ReadLine(); }
static string Hash(string input) { var hash = new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(input)); return(string.Concat(hash.Select(b => b.ToString("x2")))); }
/// <summary> /// Hash a string using SHA1 /// </summary> /// <param name="str">The string</param> /// <returns>The hex representation of the hash</returns> public static string Sha1(this string str) { if (str == null) { return null; } byte[] data = Encoding.UTF8.GetBytes(str); using (SHA1Managed sha = new SHA1Managed()) { byte[] hashBytes = sha.ComputeHash(data); return ToHex(hashBytes); } }
public static HashAlgorithm GetHashAlgorithm() { HashAlgorithm hashAlgo = new SHA1Managed(); return(hashAlgo); }
private void Process() { m_LVL_Received = true; m_ButtonMessage = "Check LVL"; m_ButtonEnabled = true; if (m_LVLCheck == null) return; int responseCode = m_LVLCheck.Get<int>("_arg0"); string message = m_LVLCheck.Get<string>("_arg1"); string signature = m_LVLCheck.Get<string>("_arg2"); m_LVLCheck = null; m_ResponseCode_Received = responseCode.ToString(); if (responseCode < 0 || string.IsNullOrEmpty(message) || string.IsNullOrEmpty(signature)) { m_PackageName_Received = "<Failed>"; return; } byte[] message_bytes = System.Text.Encoding.UTF8.GetBytes(message); byte[] signature_bytes = System.Convert.FromBase64String(signature); RSACryptoServiceProvider csp = new RSACryptoServiceProvider(); csp.ImportParameters(m_PublicKey); SHA1Managed sha1 = new SHA1Managed(); bool match = csp.VerifyHash(sha1.ComputeHash(message_bytes), CryptoConfig.MapNameToOID("SHA1"), signature_bytes); if (!match) { m_ResponseCode_Received = "<Failed>"; m_PackageName_Received = "<Invalid Signature>"; return; } int index = message.IndexOf(':'); string mainData, extraData; if (-1 == index) { mainData = message; extraData = ""; } else { mainData = message.Substring(0, index); extraData = index >= message.Length ? "" : message.Substring(index + 1); } string[] vars = mainData.Split('|'); // response | nonce | package | version | userid | timestamp if (vars[0].CompareTo(responseCode.ToString()) != 0) { m_ResponseCode_Received = "<Failed>"; m_PackageName_Received = "<Response Mismatch>"; return; } m_ResponseCode_Received = vars[0]; m_Nonce_Received = System.Convert.ToInt32(vars[1]); m_PackageName_Received = vars[2]; m_VersionCode_Received = System.Convert.ToInt32(vars[3]); m_UserID_Received = vars[4]; System.Int64 ticks = ConvertEpochSecondsToTicks(System.Convert.ToInt64(vars[5])); m_Timestamp_Received = new System.DateTime(ticks).ToLocalTime().ToString(); if (!string.IsNullOrEmpty(extraData)) { Dictionary<string, string> extrasDecoded = DecodeExtras(extraData); if (extrasDecoded.ContainsKey("GR")) { m_MaxRetry_Received = System.Convert.ToInt32(extrasDecoded["GR"]); } else { m_MaxRetry_Received = 0; } if (extrasDecoded.ContainsKey("VT")) { ticks = ConvertEpochSecondsToTicks(System.Convert.ToInt64(extrasDecoded["VT"])); m_LicenceValidityTimestamp_Received = new System.DateTime(ticks).ToLocalTime().ToString(); } else { m_LicenceValidityTimestamp_Received = null; } if (extrasDecoded.ContainsKey("GT")) { ticks = ConvertEpochSecondsToTicks(System.Convert.ToInt64(extrasDecoded["GT"])); m_GracePeriodTimestamp_Received = new System.DateTime(ticks).ToLocalTime().ToString(); } else { m_GracePeriodTimestamp_Received = null; } if (extrasDecoded.ContainsKey("UT")) { ticks = ConvertEpochSecondsToTicks(System.Convert.ToInt64(extrasDecoded["UT"])); m_UpdateTimestamp_Received = new System.DateTime(ticks).ToLocalTime().ToString(); } else { m_UpdateTimestamp_Received = null; } if (extrasDecoded.ContainsKey("FILE_URL1")) { m_FileURL1_Received = extrasDecoded["FILE_URL1"]; } else { m_FileURL1_Received = ""; } if (extrasDecoded.ContainsKey("FILE_URL2")) { m_FileURL2_Received = extrasDecoded["FILE_URL2"]; } else { m_FileURL2_Received = ""; } if (extrasDecoded.ContainsKey("FILE_NAME1")) { m_FileName1_Received = extrasDecoded["FILE_NAME1"]; } else { m_FileName1_Received = null; } if (extrasDecoded.ContainsKey("FILE_NAME2")) { m_FileName2_Received = extrasDecoded["FILE_NAME2"]; } else { m_FileName2_Received = null; } if (extrasDecoded.ContainsKey("FILE_SIZE1")) { m_FileSize1_Received = System.Convert.ToInt32(extrasDecoded["FILE_SIZE1"]); } else { m_FileSize1_Received = 0; } if (extrasDecoded.ContainsKey("FILE_SIZE2")) { m_FileSize2_Received = System.Convert.ToInt32(extrasDecoded["FILE_SIZE2"]); } else { m_FileSize2_Received = 0; } } }
/// <summary> /// Generates a BASE64-encoded SHA-1 hash from the specified input data. /// </summary> /// <param name="data">The input data to hash.</param> /// <returns>The hashed input data as a BASE64-encoded string.</returns> /// <exception cref="ArgumentNullException">The data parameter is /// null.</exception> string Hash(byte[] data) { data.ThrowIfNull("data"); using (var sha1 = new SHA1Managed()) { return Convert.ToBase64String(sha1.ComputeHash(data)); } }
/// <summary> /// /// </summary> /// <returns></returns> public ActionResult Index() { if (Request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase)) { return(Redirect("http://www.truefitsolutions.com/")); } if (Request.Files.Count <= 0 || Request.Files.Count > 1) { return(Redirect("http://www.truefitsolutions.com/")); } if (Request.Files[0] == null) { return(Redirect("http://www.truefitsolutions.com/")); } var file = Request.Files[0]; using (var hasher = new SHA1Managed()) using (var cryptoStream = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write)) using (var stream = new MemoryStream()) { file.InputStream.CopyTo(stream); stream.Position = 0; Write(cryptoStream, "blob {0}", stream.Length); cryptoStream.WriteByte(0); Write(cryptoStream, stream); cryptoStream.FlushFinalBlock(); var buffer = new StringBuilder(); foreach (var b in hasher.Hash) { buffer.Append(b.ToString("x2")); } stream.Position = 0; var name = buffer.ToString(); var filepath = Path.Combine(MvcApplication.FileDirectory, name); using (var filestream = System.IO.File.OpenWrite(filepath)) { stream.CopyTo(filestream); } var metapath = Path.Combine(MvcApplication.MetadataDirectory, name); var metadata = new FileMetadata(file.FileName, file.ContentLength, file.ContentType); var serializer = new BinaryFormatter(); using (var metastream = new FileStream(metapath, FileMode.OpenOrCreate, FileAccess.Write)) { serializer.Serialize(metastream, metadata); } var url = string.Format( "{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, VirtualPathUtility.ToAbsolute("~" + Url.RouteUrl("Default", new { id = name })) ); return(Json(new { Url = url })); } }
public static string ComputeHash(string plainText, string hashAlgorithm, byte[] saltBytes) { if (saltBytes == null) { int minSaltSize = 4; int maxSaltSize = 8; Random random = new Random(); int saltSize = random.Next(minSaltSize, maxSaltSize); saltBytes = new byte[saltSize]; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetNonZeroBytes(saltBytes); } byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length]; for (int i = 0; i < plainTextBytes.Length; i++) plainTextWithSaltBytes[i] = plainTextBytes[i]; for (int i = 0; i < saltBytes.Length; i++) plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i]; HashAlgorithm hash; if (hashAlgorithm == null) hashAlgorithm = ""; switch (hashAlgorithm.ToUpper()) { case "SHA1": hash = new SHA1Managed(); break; case "SHA256": hash = new SHA256Managed(); break; case "SHA384": hash = new SHA384Managed(); break; case "SHA512": hash = new SHA512Managed(); break; default: hash = new MD5CryptoServiceProvider(); break; } byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes); byte[] hashWithSaltBytes = new byte[hashBytes.Length + saltBytes.Length]; for (int i = 0; i < hashBytes.Length; i++) hashWithSaltBytes[i] = hashBytes[i]; for (int i = 0; i < saltBytes.Length; i++) hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i]; string hashValue = Convert.ToBase64String(hashWithSaltBytes); return hashValue; }
/// <summary> /// Creates a signature value given a signature base and the consumer secret and a known token secret. /// </summary> /// <param name="signatureMethod">The hashing method</param> /// <param name="signatureTreatment">The treatment to use on a signature value</param> /// <param name="signatureBase">The signature base</param> /// <param name="consumerSecret">The consumer secret</param> /// <param name="tokenSecret">The token secret</param> /// <returns></returns> public static string GetSignature( OAuthSignatureMethod signatureMethod, OAuthSignatureTreatment signatureTreatment, string signatureBase, string consumerSecret, string tokenSecret ) { if (tokenSecret.IsNullOrBlank()) { tokenSecret = string.Empty; } var unencodedConsumerSecret = consumerSecret; consumerSecret = Uri.EscapeDataString(consumerSecret); tokenSecret = Uri.EscapeDataString(tokenSecret); string signature; switch (signatureMethod) { case OAuthSignatureMethod.HmacSha1: { var crypto = new HMACSHA1(); var key = "{0}&{1}".FormatWith(consumerSecret, tokenSecret); crypto.Key = encoding.GetBytes(key); signature = signatureBase.HashWith(crypto); break; } case OAuthSignatureMethod.HmacSha256: { var crypto = new HMACSHA256(); var key = "{0}&{1}".FormatWith(consumerSecret, tokenSecret); crypto.Key = encoding.GetBytes(key); signature = signatureBase.HashWith(crypto); break; } case OAuthSignatureMethod.RsaSha1: { using (var provider = new RSACryptoServiceProvider { PersistKeyInCsp = false }) { provider.FromXmlString2(unencodedConsumerSecret); var hasher = new SHA1Managed(); var hash = hasher.ComputeHash(encoding.GetBytes(signatureBase)); signature = Convert.ToBase64String(provider.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"))); } break; } case OAuthSignatureMethod.PlainText: { signature = "{0}&{1}".FormatWith(consumerSecret, tokenSecret); break; } default: throw new NotImplementedException("Only HMAC-SHA1, HMAC-SHA256, and RSA-SHA1 are currently supported."); } var result = signatureTreatment == OAuthSignatureTreatment.Escaped ? UrlEncodeRelaxed(signature) : signature; return(result); }
//Usar Enum para o cypherType //Lançar exception caso o cypherType não seja conhecido. public string GetHash(string value, string saltValue, CypherType cypher) { saltValue = (saltValue == null) ? string.Empty : saltValue; StringBuilder strSenhaHash = new StringBuilder(); byte[] arrSenhaHash = null; switch (cypher) { case CypherType.SHA512: SHA512 alg = SHA512.Create(); if (saltValue.Length > 0) { value = string.Concat(saltValue.Substring(0, 18), value, saltValue.Substring(18)); } byte[] result = alg.ComputeHash(Encoding.ASCII.GetBytes(value)); arrSenhaHash = alg.ComputeHash(result); foreach (byte b in result) { strSenhaHash.Append(b.ToString("X2")); } return(strSenhaHash.ToString()); case CypherType.SHA1: HashAlgorithm AlgoritimoHash = new SHA1Managed(); byte[] arrSenhaBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(value); arrSenhaHash = AlgoritimoHash.ComputeHash(arrSenhaBytes); foreach (byte b in arrSenhaHash) { strSenhaHash.Append(b.ToString("X2")); } return(strSenhaHash.ToString()); case CypherType.MD5: string strSenhaMD5 = FormsAuthentication.HashPasswordForStoringInConfigFile(value, "md5"); return(strSenhaMD5.ToLower()); default: SHA512 algoSha = SHA512.Create(); if (saltValue.Length > 0) { value = string.Concat(saltValue.Substring(0, 18), value, saltValue.Substring(18)); } byte[] resultSha = algoSha.ComputeHash(Encoding.ASCII.GetBytes(value)); arrSenhaHash = algoSha.ComputeHash(resultSha); foreach (byte b in resultSha) { strSenhaHash.Append(b.ToString("X2")); } return(strSenhaHash.ToString()); } }
NadirContext ParseInputs() { NadirContext context = new NadirContext(this); context.PhaseExecuting = PARSEPHASE.Parse; // foreach (NadirFileDesc desc in nadirFiles) { // Capture the file contents for posterity. Compute a hash as we do so // so we can generate better output file names. // using (System.IO.StreamReader reader = OpenFileAsReader(context, desc.Filename)) { if (context.ExceptionOccurred) break; // string fileContents = reader.ReadToEnd(); // using (HashAlgorithm hasher = new SHA1Managed()) { hasher.Initialize(); byte[] bytes = new byte[fileContents.Length*2]; for (int ich = 0; ich < fileContents.Length; ich++) { int ch = (int)fileContents[ich]; byte low = (byte)(ch & 0xff); byte hi = (byte)((ch >> 8) & 0xff); bytes[2*ich] = low; bytes[2*ich + 1] = hi; } hasher.ComputeHash(bytes); byte[] hash = hasher.Hash; desc.Hash = (((int)hash[0])<<0) | (((int)hash[1])<<8) | (((int)hash[2])<<16) | (((int)hash[3])<<24); // just use the first four bytes as our signature of the file contents } // this.nadirFileContents.Append(Environment.NewLine); this.nadirFileContents.Append(new string('=', 120)); this.nadirFileContents.Append(Environment.NewLine); this.nadirFileContents.Append(fileContents); this.nadirFileContents.Append(Environment.NewLine); } // // Ok, now open and actually parse the file // ANTLRReaderStream inputStream = OpenFileForAntlr(context, desc.Filename); NadirLexer lexer = new NadirLexer(inputStream, context, true); CommonTokenStream tokens = new NadirTokenStream(lexer); NadirParser parser = new NadirParser(context, tokens); // ParseResult parseResult = new ParseResult(parser.root().Tree); if (context.ParseResults.IsEmpty<ParseResult>()) { // First guy in context.ParseResults.Add(parseResult); } else { // Since these later files were parsed with the contextual // symbols of the previous files (the symbol table is shared) // splice them all together into one conceptual compilation unit // context.ParseResults[0].Splice(parseResult); } // if (context.ExceptionOccurred) break; } // context.PhaseCompleted = PARSEPHASE.Parse; return context; }
public async Task OpenAsync(string uri) { if (Opened) { throw new ApplicationException("WebSocket is already opened."); } Uri u = new Uri(uri); HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, uri); byte[] nonce = new byte[16]; new Random().NextBytes(nonce); string requestKey = Convert.ToBase64String(nonce); req.Headers.Add("Host", u.Host); req.Headers.Add("User-Agent", UserAgent); req.Headers.Add("Accept", "text/html"); req.Headers.Add("Sec-WebSocket-Version", "13"); req.Headers.Add("Origin", "null"); req.Headers.Add("Sec-WebSocket-Key", requestKey); req.Headers.Add("Connection", "keep-alive, Upgrade"); req.Headers.Add("Pragma", "no-cache"); req.Headers.Add("Cache-Control", "no-cache"); req.Headers.Add("Upgrade", "websocket"); StringWriter tmpWriter = new StringWriter(); tmpWriter.WriteLine($"{req.Method} {req.RequestUri.PathAndQuery} HTTP/1.1"); tmpWriter.WriteLine(req.Headers.ToString()); await st.WriteAsyncWithTimeout(tmpWriter.AsciiToByteArray(), timeout : this.TimeoutOpen, cancel : this.Cancel); Dictionary <string, string> headers = new Dictionary <string, string>(); int num = 0; int responseCode = 0; StreamReader tmpReader = new StreamReader(st); while (true) { string line = await WebSocketHelper.DoAsyncWithTimeout((procCancel) => tmpReader.ReadLineAsync(), timeout : this.TimeoutOpen, cancel : this.Cancel); if (line == "") { break; } if (num == 0) { string[] tokens = line.Split(' '); if (tokens[0] != "HTTP/1.1") { throw new ApplicationException($"Cannot establish the WebSocket Protocol. Response: \"{tokens}\""); } responseCode = int.Parse(tokens[1]); } else { string[] tokens = line.Split(':'); string name = tokens[0].Trim(); string value = tokens[1].Trim(); headers[name] = value; } num++; } if (responseCode != 101) { throw new ApplicationException($"Cannot establish the WebSocket Protocol. Perhaps the destination host does not support WebSocket. Wrong response code: \"{responseCode}\""); } if (headers["Upgrade"].Equals("websocket", StringComparison.InvariantCultureIgnoreCase) == false) { throw new ApplicationException($"Wrong Upgrade header: \"{headers["Upgrade"]}\""); } string acceptKey = headers["Sec-WebSocket-Accept"]; string keyCalcStr = requestKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; SHA1 sha1 = new SHA1Managed(); string acceptKey2 = Convert.ToBase64String(sha1.ComputeHash(keyCalcStr.AsciiToByteArray())); if (acceptKey != acceptKey2) { throw new ApplicationException($"Wrong accept_key: \'{acceptKey}\'"); } Opened = true; }
/// <summary> /// 静态构造函数 /// </summary> static StorageWrapper() { shaM = new SHA1Managed(); }
private static void Decifrar(Mensagem post) { post.decifrado = null; var msg = post.cifrado; //var msg = "j pomz cfmjfwf jo tubujtujdt uibu j epdupsfe nztfmg. xjotupo t. divsdijmm?"; int num = 0; string text = ""; string[] data = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; for (int i = 0; i < msg.Length; i++) { if (msg[i].ToString() == ".") { text += msg[i].ToString(); } else if (msg[i].ToString() == " ") { text += msg[i].ToString(); } else { int t = Array.IndexOf(data, msg[i].ToString()); int v = t - 12; if (v > data.Count()) { v = v - data.Count(); } if (v < 0) { v = data.Count() + v; } text += data[v].ToString(); } } // for (int i = 0; i < msg.Length; i++) //{ // var toInt = Convert.ToInt32(msg[i]); // if (toInt == 46 || toInt == 32 || toInt == 63) // { // num = toInt; // } // else // { // num = toInt - post.Numero_casas; // } // if (num >= 33 && num <= 96) // { // num = toInt; // } // if (num < 32) // { // num += 32; // } post.decifrado += text; //Convert.ToChar(num); //} var hash = new SHA1Managed().ComputeHash(Encoding.ASCII.GetBytes(post.decifrado)); post.resumo_criptografico = string.Concat(hash.Select(b => b.ToString("x2"))); //byte[] bytes = Encoding.ASCII.GetBytes(post.decifrado); //SHA1 sha1 = new SHA1CryptoServiceProvider(); //var result = sha1.ComputeHash(bytes); //string converted = Encoding.ASCII.GetString(result, 0, result.Length); //post.resumo_criptografico = converted; Console.WriteLine($"\n"); Console.WriteLine($"Numero_casas:{post.Numero_casas}\nToken:{post.Token}\ncifrado:{post.cifrado}\ndecifrado:{post.decifrado}\nresumo_criptografico:{post.resumo_criptografico}"); json = JsonConvert.SerializeObject(post); }
/// <summary> /// Generates a hash for the given plain text value and returns a /// base64-encoded result. Before the hash is computed, a random salt /// is generated and appended to the plain text. This salt is stored at /// the end of the hash value, so it can be used later for hash /// verification. /// </summary> /// <param name="plainText"> /// Plaintext value to be hashed. /// </param> /// <param name="hashAlgorithm"> /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1", /// "SHA256", "SHA384", and "SHA512" (if any other value is specified /// MD5 hashing algorithm will be used). This value is case-insensitive. /// </param> /// <param name="saltBytes"> /// Salt bytes. This parameter can be null, in which case a random salt /// value will be generated. /// </param> /// <returns> /// Hash value formatted as a base64-encoded string. /// </returns> /// <remarks> /// ComputeHash code provided as an example by Obviex at /// http://www.obviex.com/samples/hash.aspx /// As noted by Obviex themselves, code is definitely not optimally efficient. /// Should performance requirements necessitate improvement, this should /// be improved. /// </remarks> public static string ComputeHash(string plainText, string hashAlgorithm, byte[] saltBytes) { if (plainText == null) return null; // If salt is not specified, generate it on the fly. if (saltBytes == null) { // Define min and max salt sizes. int minSaltSize = 4; int maxSaltSize = 8; // Generate a random number for the size of the salt. Random random = new Random(); int saltSize = random.Next(minSaltSize, maxSaltSize); // Allocate a byte array, which will hold the salt. saltBytes = new byte[saltSize]; // Initialize a random number generator. RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); // Fill the salt with cryptographically strong byte values. rng.GetNonZeroBytes(saltBytes); } // Convert plain text into a byte array. byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); // Allocate array, which will hold plain text and salt. byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length]; // Copy plain text bytes into resulting array. for (int i = 0; i < plainTextBytes.Length; i++) plainTextWithSaltBytes[i] = plainTextBytes[i]; // Append salt bytes to the resulting array. for (int i = 0; i < saltBytes.Length; i++) plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i]; // Because we support multiple hashing algorithms, we must define // hash object as a common (abstract) base class. We will specify the // actual hashing algorithm class later during object creation. HashAlgorithm hash; // Make sure hashing algorithm name is specified. if (hashAlgorithm == null) hashAlgorithm = ""; // Initialize appropriate hashing algorithm class. switch (hashAlgorithm.ToUpper()) { case "SHA1": hash = new SHA1Managed(); break; case "SHA256": hash = new SHA256Managed(); break; case "SHA384": hash = new SHA384Managed(); break; case "SHA512": hash = new SHA512Managed(); break; default: hash = new MD5CryptoServiceProvider(); break; } // Compute hash value of our plain text with appended salt. byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes); // Create array which will hold hash and original salt bytes. byte[] hashWithSaltBytes = new byte[hashBytes.Length + saltBytes.Length]; // Copy hash bytes into resulting array. for (int i = 0; i < hashBytes.Length; i++) hashWithSaltBytes[i] = hashBytes[i]; // Append salt bytes to the result. for (int i = 0; i < saltBytes.Length; i++) hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i]; // Convert result into a base64-encoded string. string hashValue = Convert.ToBase64String(hashWithSaltBytes); // Return the result. return hashValue; }
internal static string GenerateSha1(byte[] data) { using SHA1Managed sha1Managed = new SHA1Managed(); byte[] hash = sha1Managed.ComputeHash(data); return(string.Join("", hash.Select(b => b.ToString("x2", CultureInfo.InvariantCulture)))); }
protected String ToXML() { generateTimestamp(); // timestamp the request as it's generated generateSHA1Hash(); // ... and ensure that we have a correct hash // NOTE: element variable names are named in the XML case, not in camel case, so as to // avoid confusion in mapping between the two. XmlWriterSettings xmlSettings = new XmlWriterSettings(); xmlSettings.Indent = true; xmlSettings.NewLineOnAttributes = false; xmlSettings.NewLineChars = "\r\n"; xmlSettings.CloseOutput = true; StringBuilder strBuilder = new StringBuilder(); XmlWriter xml = XmlWriter.Create(strBuilder, xmlSettings); xml.WriteStartDocument(); xml.WriteStartElement("request"); { xml.WriteAttributeString("timestamp", m_transTimestamp); xml.WriteAttributeString("type", m_transType); xml.WriteElementString("merchantid", m_transMerchantName); xml.WriteElementString("account", m_transAccountName); xml.WriteElementString("orderid", m_transOrderID); switch(m_transType) { case("auth"): case("credit"): case("offline"): case("rebate"): case("tss"): xml.WriteStartElement("amount"); xml.WriteAttributeString("currency", m_transCurrency); xml.WriteString(m_transAmount.ToString()); xml.WriteEndElement(); m_transCard.WriteXML(xml); xml.WriteStartElement("autosettle"); xml.WriteAttributeString("flag", m_transAutoSettle.ToString()); xml.WriteEndElement(); break; } switch(m_transType) { case("credit"): case("rebate"): case("settle"): case("void"): xml.WriteElementString("pasref", m_transPASRef); break; } switch(m_transType) { case("credit"): case("offline"): case("rebate"): case("settle"): case("void"): xml.WriteElementString("authcode", m_transAuthCode); break; } xml.WriteElementString("sha1hash", m_transSHA1Hash); // if this is a transaction requiring an additional hash, include it here SHA1 sha = new SHA1Managed(); switch (m_transType) { case("credit"): String refundHash = hexEncode(sha.ComputeHash(Encoding.UTF8.GetBytes(m_refundPassword))); xml.WriteElementString("refundhash", refundHash); break; case("rebate"): String rebateHash = hexEncode(sha.ComputeHash(Encoding.UTF8.GetBytes(m_rebatePassword))); xml.WriteElementString("refundhash", rebateHash); // this is still sent as "refundhash", not "rebatehash" break; } xml.WriteStartElement("comments"); { int iComment = 1; // this must start from 1, not 0. foreach (String comment in m_transComments) { xml.WriteStartElement("comment"); xml.WriteAttributeString("id", iComment.ToString()); xml.WriteString(comment); xml.WriteEndElement(); iComment++; } } xml.WriteEndElement(); xml.WriteStartElement("tssinfo"); { { xml.WriteStartElement("address"); xml.WriteAttributeString("type", "billing"); xml.WriteElementString("code", m_transBillingAddressCode); xml.WriteElementString("country", m_transBillingAddressCountry); xml.WriteEndElement(); } { xml.WriteStartElement("address"); xml.WriteAttributeString("type", "shipping"); xml.WriteElementString("code", m_transShippingAddressCode); xml.WriteElementString("country", m_transShippingAddressCountry); xml.WriteEndElement(); } { xml.WriteElementString("custnum", m_transCustomerNumber); xml.WriteElementString("varref", m_transVariableReference); xml.WriteElementString("prodid", m_transProductID); } } xml.WriteEndElement(); } //TODO: if you wish to send Realex any additional variables, include them here //xml.WriteElementString("MyInterestingVariable", m_myInterestingVariableName); xml.WriteEndElement(); xml.Flush(); xml.Close(); return(strBuilder.ToString()); }
private static string b64_sha1(string source) { byte[] hash = new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(source)); return Convert.ToBase64String(hash); }
/// <summary> /// Applies the cryptographic hash function SHA-1 to the specified data /// array. /// </summary> /// <param name="data">The data array to apply the hash function to.</param> /// <returns>The hash value for the specified byte array.</returns> private byte[] H(byte[] data) { using (var sha1 = new SHA1Managed()) { return(sha1.ComputeHash(data)); } }
/// <summary> /// SHA1加密 /// </summary> /// <param name="inputString"></param> /// <returns></returns> public static string SHA1Encrypt(string inputString) { SHA1Managed sha1 = new SHA1Managed(); return(ByteToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(inputString))).ToLower()); }