public byte[] GetHash(Version version) { if (version == null) { throw new ArgumentNullException(nameof(version)); } byte[] handshakeHash; if (version < DTLSRecord.Version1_2) { IDigest sha1 = new Sha1Digest(this._VerifyHandshakeSHA1); IDigest md5 = new MD5Digest(this._VerifyHandshakeMD5); handshakeHash = new byte[sha1.GetDigestSize() + md5.GetDigestSize()]; md5.DoFinal(handshakeHash, 0); sha1.DoFinal(handshakeHash, md5.GetDigestSize()); } else { IDigest hash = new Sha256Digest((Sha256Digest)this._VerifyHandshake); handshakeHash = new byte[hash.GetDigestSize()]; hash.DoFinal(handshakeHash, 0); } return(handshakeHash); }
private static byte[] GetDigestInByteArray( FileInfo file, CancellationToken cancellationToken) { using (var readStream = file.OpenRead()) { var digest = new Sha1Digest(); var output = new byte[digest.GetDigestSize()]; var buffer = new byte[BufferSizeInByte]; int read; while ((read = readStream.Read( buffer, 0, buffer.Length)) > 0) { cancellationToken.ThrowIfCancellationRequested(); digest.BlockUpdate( buffer, 0, read ); } digest.DoFinal( output, 0 ); return(output); } }
private static async Task <byte[]> GetDigestInByteArrayAsync( FileInfo file, CancellationToken cancellationToken) { using (var readStream = file.OpenRead()) { var digest = new Sha1Digest(); var output = new byte[digest.GetDigestSize()]; var buffer = new byte[BufferSizeInByte]; int read; while ((read = await readStream.ReadAsync( buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) > 0) { cancellationToken.ThrowIfCancellationRequested(); digest.BlockUpdate( buffer, 0, read ); } digest.DoFinal( output, 0 ); return(output); } }
internal byte[] GetNSec3Hash(NSec3HashAlgorithm algorithm, int iterations, byte[] salt) { IDigest digest; switch (algorithm) { case NSec3HashAlgorithm.Sha1: digest = new Sha1Digest(); break; default: throw new NotSupportedException(); } byte[] buffer = new byte[Math.Max(MaximumRecordDataLength + 1, digest.GetDigestSize()) + salt.Length]; int length = 0; DnsMessageBase.EncodeDomainName(buffer, 0, ref length, this, null, true); for (int i = 0; i <= iterations; i++) { DnsMessageBase.EncodeByteArray(buffer, ref length, salt); digest.BlockUpdate(buffer, 0, length); digest.DoFinal(buffer, 0); length = digest.GetDigestSize(); } byte[] res = new byte[length]; Buffer.BlockCopy(buffer, 0, res, 0, length); return(res); }
public static bool DoVerifyDsaSha1(IEnumerable <BufLen> bufs, I2PSigningPublicKey key, I2PSignature signed) { if (!SupportedSignatureType(signed.Certificate.SignatureType)) { throw new NotImplementedException(); } var sha = new Sha1Digest(); foreach (var buf in bufs) { sha.BlockUpdate(buf.BaseArray, buf.BaseArrayOffset, buf.Length); } var hash = new byte[sha.GetDigestSize()]; sha.DoFinal(hash, 0); var dsa = new Org.BouncyCastle.Crypto.Signers.DsaSigner(); var sigsize = signed.Certificate.SignatureLength; var r = new BigInteger(1, signed.Sig.BaseArray, signed.Sig.BaseArrayOffset + 0, sigsize / 2); var s = new BigInteger(1, signed.Sig.BaseArray, signed.Sig.BaseArrayOffset + sigsize / 2, sigsize / 2); var dsaparams = new DsaPublicKeyParameters( key.ToBigInteger(), new DsaParameters( I2PConstants.DsaP, I2PConstants.DsaQ, I2PConstants.DsaG)); dsa.Init(false, dsaparams); return(dsa.VerifySignature(hash, r, s)); }
/// <summary> /// Calculate the restore code for an authenticator. This is taken from the last 10 bytes of a digest of the serial and secret key, /// which is then specially encoded to alphanumerics. /// </summary> /// <returns>restore code for authenticator (always 10 chars)</returns> protected string BuildRestoreCode() { // return if not set if (string.IsNullOrEmpty(Serial) == true || SecretKey == null) { return(string.Empty); } // get byte array of serial byte[] serialdata = Encoding.UTF8.GetBytes(Serial.ToUpper().Replace("-", string.Empty)); byte[] secretdata = SecretKey; // combine serial data and secret data byte[] combined = new byte[serialdata.Length + secretdata.Length]; Array.Copy(serialdata, 0, combined, 0, serialdata.Length); Array.Copy(secretdata, 0, combined, serialdata.Length, secretdata.Length); // create digest of combined data IDigest digest = new Sha1Digest(); digest.BlockUpdate(combined, 0, combined.Length); byte[] digestdata = new byte[digest.GetDigestSize()]; digest.DoFinal(digestdata, 0); // take last 10 chars of hash and convert each byte to our encoded string that doesn't use I,L,O,S StringBuilder code = new StringBuilder(); int startpos = digestdata.Length - 10; for (int i = 0; i < 10; i++) { code.Append(ConvertRestoreCodeByteToChar(digestdata[startpos + i])); } return(code.ToString()); }
private static string FromStream_BOUNCY(Stream stream) { int BUFFER_SIZE = 5 * 1024 * 1024; byte[] buffer = new byte[BUFFER_SIZE]; int total_read = 0; int num_read = 0; Sha1Digest sha1 = new Sha1Digest(); while (0 < (num_read = stream.Read(buffer, 0, BUFFER_SIZE))) { total_read += num_read; sha1.BlockUpdate(buffer, 0, num_read); } byte[] hash = new byte[sha1.GetDigestSize()]; sha1.DoFinal(hash, 0); // Convert to string StringBuilder buff = new StringBuilder(); foreach (byte hash_byte in hash) { buff.Append(String.Format("{0:X1}", hash_byte)); } return(buff.ToString()); }
private void btnFirmaMasiva_Click(object sender, EventArgs e) { FolderBrowserDialog fbd = new FolderBrowserDialog(); DialogResult dresult = fbd.ShowDialog(); if (dresult == DialogResult.OK) { foreach (string file in Directory.GetFiles(fbd.SelectedPath)) { FileInfo fInfo = new FileInfo(file); AsymmetricKeyParameter akp = ReadPrivateKey(lblFirma.Text); Sha1Digest dig = new Sha1Digest(); byte[] msgBytes = File.ReadAllBytes(file); dig.BlockUpdate(msgBytes, 0, msgBytes.Length); byte[] result = new byte[dig.GetDigestSize()]; dig.DoFinal(result, 0); Org.BouncyCastle.Crypto.Signers.RsaDigestSigner signer = new Org.BouncyCastle.Crypto.Signers.RsaDigestSigner(dig); signer.Init(true, akp); signer.BlockUpdate(result, 0, result.Length); byte[] sig = signer.GenerateSignature(); string signString = Convert.ToBase64String(sig); string signPath = string.Format("{0}{1}", fInfo.FullName, "sgn"); File.WriteAllText(signPath, signString, System.Text.Encoding.UTF8); } MessageBox.Show("Firma finalizada."); } }
private byte[] ComputeHash(byte[] input) { var sha = new Sha1Digest(); sha.BlockUpdate(input, 0, input.Length); byte[] result = new byte[sha.GetDigestSize()]; sha.DoFinal(result, 0); return(result); }
static byte[] Sha1(byte[] dat) { Sha1Digest digester = new Sha1Digest(); byte[] retValue = new byte[digester.GetDigestSize()]; digester.BlockUpdate(dat, 0, dat.Length); digester.DoFinal(retValue, 0); return(retValue); }
/// <seealso cref="IDigest.DoFinal"/> public int DoFinal( byte[] output, int outOff) { int i1 = md5.DoFinal(output, outOff); int i2 = sha1.DoFinal(output, outOff + i1); return(i1 + i2); }
public static byte[] SHA1(byte[] data, int offset, int count) { var sha1 = new Sha1Digest(); sha1.BlockUpdate(data, offset, count); byte[] rv = new byte[20]; sha1.DoFinal(rv, 0); return(rv); }
private string ExecuteHash() { IDigest hash; switch (this.HashFunctionComboBox.Text) { case "Blake2b - 256 bit": hash = new Blake2bDigest(256); break; case "Blake2b - 512 bit": hash = new Blake2bDigest(512); break; case "SHA-1": hash = new Sha1Digest(); break; case "SHA-2 256 bit": hash = new Sha256Digest(); break; case "SHA-2 512 bit": hash = new Sha512Digest(); break; case "SHA-3 256 bit": hash = new Sha3Digest(256); break; case "SHA-3 512 bit": hash = new Sha3Digest(512); break; default: hash = new Sha1Digest(); break; } byte[] result = new byte[hash.GetDigestSize()]; using (Stream source = File.OpenRead(this.LocationTextBox.Text)) { int BytesRead; while ((BytesRead = source.Read(this._Data, 0, this._Data.Length)) > 0) { hash.BlockUpdate(this._Data, 0, BytesRead); } } hash.DoFinal(result, 0); Array.Clear(this._Data, 0, this._Data.Length); return(Entities.HashFunctionList.ByteArrayToHexString(result)); }
static Asn1OctetString CreateDigestFromBytes(byte[] bytes) { var digest = new Sha1Digest(); digest.BlockUpdate(bytes, 0, bytes.Length); var digestBytes = new byte[digest.GetDigestSize()]; digest.DoFinal(digestBytes, 0); return(new DerOctetString(digestBytes)); }
/// <summary> /// Compute the Hash of <paramref name="data"/> using the SHA-1 algorithm. /// </summary> /// <remarks>The approved algorithm for hashing is SHA-1 as specified in ISO/IEC 10118-3 [5].</remarks> /// <param name="data">Data to hash.</param> /// <returns>Hash value.</returns> public static byte[] ComputeHashSha1(this byte[] data) { IDigest sha1 = new Sha1Digest(); var h = new byte[sha1.GetDigestSize()]; sha1.BlockUpdate(data, 0, data.Length); sha1.DoFinal(h, 0); return(h); }
private void btnDigest_Click2(object sender, EventArgs e) { Sha1Digest dig = new Sha1Digest(); byte[] msgBytes = File.ReadAllBytes(lblDocument.Text); dig.BlockUpdate(msgBytes, 0, msgBytes.Length); byte[] result = new byte[dig.GetDigestSize()]; dig.DoFinal(result, 0); textBox1.Text = Convert.ToBase64String(result); }
private static byte[] GetDigest(SubjectPublicKeyInfo spki) { IDigest digest = new Sha1Digest(); byte[] array = new byte[digest.GetDigestSize()]; byte[] bytes = spki.PublicKeyData.GetBytes(); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(array, 0); return(array); }
public static string Sha1(string input) { var data = System.Text.Encoding.UTF8.GetBytes(input); Sha1Digest hash = new Sha1Digest(); hash.BlockUpdate(data, 0, data.Length); byte[] result = new byte[hash.GetDigestSize()]; hash.DoFinal(result, 0); return(Hex.ToHexString(result)); }
/// <summary> /// sha1算签名, 代付回调验签 /// </summary> /// <param name="text"></param> /// <returns></returns> public static string ComputeSha1(string text) { Sha1Digest sha1Digest = new Sha1Digest(); var retValue = new byte[sha1Digest.GetDigestSize()]; var bs = Encoding.UTF8.GetBytes(text); sha1Digest.BlockUpdate(bs, 0, bs.Length); sha1Digest.DoFinal(retValue, 0); return(BitConverter.ToString(retValue).Replace("-", "")); }
public static string ComputeHash(string input) { var data = Encoding.UTF8.GetBytes(input); Sha1Digest hash = new Sha1Digest(); hash.BlockUpdate(data, 0, data.Length); byte[] result = new byte[hash.GetDigestSize()]; hash.DoFinal(result, 0); return(Convert.ToBase64String(result)); }
public AuthorityKeyIdentifier(SubjectPublicKeyInfo spki) { IDigest digest = new Sha1Digest(); byte[] array = new byte[digest.GetDigestSize()]; byte[] bytes = spki.PublicKeyData.GetBytes(); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(array, 0); keyidentifier = new DerOctetString(array); }
public override void HandlePacket(WorldClient client, ServerPacket packet) { var reader = packet.Reader; int returnCode = reader.ReadInt32(); if (returnCode != 0) { Log.Error($"WS2GC_ANS_DISTRICT_ENTER response had invalid return code {returnCode}"); client.OnDistrictEnterFailed(client, returnCode); return; } var data = new DistrictEnterInfo() { ReturnCode = returnCode, DistrictServerIpAddress = new IPAddress(reader.ReadBytes(4)), DistrictServerPort = reader.ReadUInt16(), Timestamp = reader.ReadUInt64(), }; // Calculate the hash used in the UDP handshake var timestampBytes = BitConverter.GetBytes(data.Timestamp); var sha1 = new Sha1Digest(); sha1.BlockUpdate(client._encryptionKey, 0, client._encryptionKey.Length); sha1.BlockUpdate(timestampBytes, 0, timestampBytes.Length); var handshakeHash = new byte[sha1.GetDigestSize()]; sha1.DoFinal(handshakeHash, 0); data.HandshakeHash = handshakeHash; // Calculate the encryption key used for UDP packets sha1 = new Sha1Digest(); sha1.BlockUpdate(client._encryptionKey, 0, client._encryptionKey.Length); sha1.BlockUpdate(handshakeHash, 0, handshakeHash.Length); var encryptionHash = new byte[sha1.GetDigestSize()]; sha1.DoFinal(encryptionHash, 0); var encryptionKey = new byte[16]; Buffer.BlockCopy(encryptionHash, 0, encryptionKey, 0, 16); data.XXTEAKey = encryptionKey; Log.Debug($"m_nReturnCode = {returnCode}"); Log.Debug($"m_nDistrictServerIPAddress = {data.DistrictServerIpAddress}"); Log.Debug($"m_nDistrictServerPort = {data.DistrictServerPort}"); Log.Debug($"m_nTimestamp = {data.Timestamp}"); Log.Debug($"m_bHandshakeHash = {Util.ByteToHexBitFiddle(data.HandshakeHash)}"); Log.Debug($"m_bXXTEAKey = {Util.ByteToHexBitFiddle(data.XXTEAKey)}"); client.OnDistrictEnterSuccess(client, data); }
public byte[] ComputeSHA1(byte[] data, int offset, int count) { var digest = new Sha1Digest(); digest.BlockUpdate(data, offset, count); var output = new byte[20]; digest.DoFinal(output, 0); return(output); }
public static byte[] GenerateSHA1Hash(byte[] namespaceId, byte[] data) { IDigest digest = new Sha1Digest(); digest.BlockUpdate(namespaceId, 0, namespaceId.Length); digest.BlockUpdate(data, 0, data.Length); var output = new byte[128]; digest.DoFinal(output, 0); return(output); }
/// <summary> /// Hash data with SHA1 /// </summary> /// <param name="data">Data to hash</param> /// <returns>Hash</returns> public static byte[] Hash(byte[] data) { byte[] result = new byte[20]; Sha1Digest sha1 = new Sha1Digest(); sha1.BlockUpdate(data, 0, data.Length); sha1.DoFinal(result, 0); return(result); }
public AuthorityKeyIdentifier(SubjectPublicKeyInfo spki, GeneralNames name, BigInteger serialNumber) { IDigest digest = new Sha1Digest(); byte[] array = new byte[digest.GetDigestSize()]; byte[] bytes = spki.PublicKeyData.GetBytes(); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(array, 0); keyidentifier = new DerOctetString(array); certissuer = name; certserno = new DerInteger(serialNumber); }
/** * * Calulates the keyIdentifier using a SHA1 hash over the BIT STRING * from SubjectPublicKeyInfo as defined in RFC2459. * **/ public SubjectKeyIdentifier( SubjectPublicKeyInfo spki) { IDigest digest = new Sha1Digest(); byte[] resBuf = new byte[digest.GetDigestSize()]; byte[] bytes = spki.PublicKeyData.GetBytes(); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); this.keyIdentifier = resBuf; }
public override string hash(string pw) { Sha1Digest digest = new Sha1Digest(); byte[] password = Encoding.UTF8.GetBytes(pw); digest.BlockUpdate(password, 0, password.Length); int digestSize = digest.GetDigestSize(); byte[] hashData = new byte[digestSize]; digest.DoFinal(hashData, 0); return("{SHA}" + Convert.ToBase64String(hashData)); }
/// <inheritdoc/> /// <remarks> /// <para> /// <strong>Algorithm Description:</strong> hex strings are generated in /// 40-byte segments using a 3-step process. /// <list type="numbers"> /// <item> /// 20 random bytes are generated using the underlying /// <code>SecureRandom</code>.</item> /// <item> /// SHA-1 hash is applied to yield a 20-byte binary digest.</item> /// <item> /// Each byte of the binary digest is converted to 2 hex digits.</item> /// </list> /// </para> /// </remarks> /// <exception cref="NotStrictlyPositiveException"> if <c>len <= 0</c></exception> public String nextSecureHexString(int len) { if (len <= 0) { throw new NotStrictlyPositiveException <Int32>(new LocalizedFormats("LENGTH"), len); } // Get SecureRandom and setup Digest provider RandomGenerator secRan = getSecRan(); Sha1Digest alg = new Sha1Digest(); //The buildin HashAlgorithm is not supported as portable, so I used the BouncyCastle, from NuGet alg.Reset(); // Compute number of iterations required (40 bytes each) int numIter = (len / 40) + 1; StringBuilder outBuffer = new StringBuilder(); for (int iter = 1; iter < numIter + 1; iter++) { byte[] randomBytes = new byte[40]; secRan.nextBytes(randomBytes); alg.BlockUpdate(randomBytes, 0, randomBytes.Length - 1); // Compute hash -- will create 20-byte binary hash byte[] hash = new byte[20]; alg.DoFinal(hash, 0); // Loop over the hash, converting each byte to 2 hex digits for (int i = 0; i < hash.Length; i++) { Int32 c = hash[i]; /* * /// Add 128 to byte value to make interval 0-255 This guarantees * /// <= 2 hex digits from toHexString() toHexString would * /// otherwise add 2^32 to negative arguments */ String hex = (c + 128).ToString("X"); // Keep strings uniform length -- guarantees 40 bytes if (hex.Length == 1) { hex = "0" + hex; } outBuffer.Append(hex); } } return(outBuffer.ToString().Substring(0, len)); }
protected override void PostConnect() { var sha1 = new Sha1Digest(); sha1.BlockUpdate(EncryptionKey, 0, EncryptionKey.Length); sha1.BlockUpdate(BitConverter.GetBytes(Timestamp), 0, 8); var hash = new byte[sha1.GetDigestSize()]; sha1.DoFinal(hash, 0); var req = new GC2WS_ASK_WORLD_ENTER(AccountID, hash); SendPacket(req); SetEncryptionKey(EncryptionKey); }