public static byte[] SHA256(byte[] data, int offset, int count) { #if USEBC || WINDOWS_UWP || NETCORE Sha256Digest sha256 = new Sha256Digest(); sha256.BlockUpdate(data, offset, count); byte[] rv = new byte[32]; sha256.DoFinal(rv, 0); return(rv); #else using (var sha = new SHA256Managed()) { return(sha.ComputeHash(data, offset, count)); } #endif }
/// <summary> /// Calculates RIPEMD160(SHA256(input)). This is used in Address calculations. /// </summary> public static byte[] Sha256Hash160(byte[] input) { var sha256 = new Sha256Digest(); var digest = new RipeMD160Digest(); sha256.BlockUpdate(input, 0, input.Length); var @out256 = new byte[sha256.GetDigestSize()]; sha256.DoFinal(@out256, 0); digest.BlockUpdate(@out256, 0, @out256.Length); var @out = new byte[digest.GetDigestSize()]; digest.DoFinal(@out, 0); return(@out); }
public static BigInteger Sha256Hash(this string str) { if (str == null) { return(BigInteger.Zero); } var digest = new Sha256Digest(); byte[] stringBytes = Encoding.UTF8.GetBytes(str); digest.BlockUpdate(stringBytes, 0, stringBytes.Length); digest.Finish(); byte[] bytes = new byte[digest.GetDigestSize()]; digest.DoFinal(bytes, 0); return(new BigInteger(bytes)); }
protected override string ComputeHashRaw(string input) { #if NET35 HashAlgorithm algorithm = SHA256.Create(); Byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(input); Byte[] hashedBytes = algorithm.ComputeHash(inputBytes); return(BitConverter.ToString(hashedBytes)); #else Sha256Digest algorithm = new Sha256Digest(); Byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(input); Byte[] bufferBytes = new byte[algorithm.GetDigestSize()]; algorithm.BlockUpdate(inputBytes, 0, inputBytes.Length); algorithm.DoFinal(bufferBytes, 0); return(BitConverter.ToString(bufferBytes)); #endif }
public static byte[] Compute(string s) { if (string.IsNullOrEmpty(s)) { throw new ArgumentNullException(nameof(s)); } var digest = new Sha256Digest(); var resBuf = new byte[digest.GetDigestSize()]; var input = Encoding.UTF8.GetBytes(s); digest.BlockUpdate(input, 0, input.Length); digest.DoFinal(resBuf, 0); return(resBuf); }
private byte[] GenerateAESKey(ECPublicKeyParameters bobPublicKey, AsymmetricKeyParameter alicePrivateKey) { IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDH"); aKeyAgree.Init(alicePrivateKey); BigInteger sharedSecret = aKeyAgree.CalculateAgreement(bobPublicKey); byte[] sharedSecretBytes = sharedSecret.ToByteArray(); IDigest digest = new Sha256Digest(); byte[] symmetricKey = new byte[digest.GetDigestSize()]; digest.BlockUpdate(sharedSecretBytes, 0, sharedSecretBytes.Length); digest.DoFinal(symmetricKey, 0); return(symmetricKey); }
private static byte[] GetDigestInByteArray(string content) { var digest = new Sha256Digest(); var input = Encoding.UTF8.GetBytes(content); var output = new byte[digest.GetDigestSize()]; digest.BlockUpdate( input, 0, input.Length ); digest.DoFinal( output, 0 ); return(output); }
public static BigInteger Concatenate(this BigInteger start, params BigInteger[] rest) { var digest = new Sha256Digest(); byte[] startBytes = start.ToByteArray(); digest.BlockUpdate(startBytes, 0, startBytes.Length); foreach (var b in rest) { byte[] blockBytes = b.ToByteArray(); digest.BlockUpdate(blockBytes, 0, blockBytes.Length); } digest.Finish(); byte[] bytes = new byte[digest.GetDigestSize()]; digest.DoFinal(bytes, 0); return(new BigInteger(bytes)); }
public void DJB_Ed25519_SHA256() { byte[] data = TEST; var digest = new Sha256Digest(); var m = new byte[digest.OutputSize]; digest.BlockUpdate(data, 0, data.Length); digest.DoFinal(m, 0); ECKeypair keypair = KeypairFactory.GenerateECKeypair(DjbCurve.Ed25519.ToString()); byte[] sig = Ed25519.Sign(m, keypair.EncodedPrivateKey); bool good = Ed25519.Verify(sig, m, keypair.EncodedPublicKey); Assert.IsTrue(good); }
/// <summary> /// sha256算签名,代付请求的时候用 /// </summary> /// <param name="text"></param> /// <returns></returns> public static string ComputeSha256(string text) { /* * SHA512Digest digester = new SHA512Digest(); * byte[] retValue = new byte[digester.getDigestSize()]; * digester.update(key.getBytes(), 0, key.length()); * digester.doFinal(retValue, 0); * return retValue; */ Sha256Digest sha256Digest = new Sha256Digest(); var retValue = new byte[sha256Digest.GetDigestSize()]; var bs = Encoding.UTF8.GetBytes(text); sha256Digest.BlockUpdate(bs, 0, bs.Length); sha256Digest.DoFinal(retValue, 0); return(BitConverter.ToString(retValue).Replace("-", "")); }
public void ShaTestSmall() { for (int i = 0; i < 100; i++) { byte[] bytes = new byte[8]; new Random().NextBytes(bytes); var d1 = new Digest().ComputeDigest(bytes); var _sha = new Sha256Digest(); _sha.BlockUpdate(bytes, 0, bytes.Length); byte[] d2 = new byte[_sha.GetDigestSize()]; _sha.DoFinal(d2, 0); Assert.Equal(d1, d2); } }
internal static byte[] GetCertificateAssocicationData(TlsaSelector selector, TlsaMatchingType matchingType, X509Certificate certificate) { byte[] selectedBytes; switch (selector) { case TlsaSelector.FullCertificate: selectedBytes = certificate.GetRawCertData(); break; case TlsaSelector.SubjectPublicKeyInfo: var asymmetricKeyParameter = PublicKeyFactory.CreateKey(certificate.GetRawCertData()); selectedBytes = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(asymmetricKeyParameter).GetDerEncoded(); break; default: throw new NotSupportedException(); } byte[] matchingBytes; switch (matchingType) { case TlsaMatchingType.Full: matchingBytes = selectedBytes; break; case TlsaMatchingType.Sha256Hash: Sha256Digest sha256Digest = new Sha256Digest(); sha256Digest.BlockUpdate(selectedBytes, 0, selectedBytes.Length); matchingBytes = new byte[sha256Digest.GetDigestSize()]; sha256Digest.DoFinal(matchingBytes, 0); break; case TlsaMatchingType.Sha512Hash: Sha512Digest sha512Digest = new Sha512Digest(); sha512Digest.BlockUpdate(selectedBytes, 0, selectedBytes.Length); matchingBytes = new byte[sha512Digest.GetDigestSize()]; sha512Digest.DoFinal(matchingBytes, 0); break; default: throw new NotSupportedException(); } return(matchingBytes); }
public SymmetricKey ExchangeKey(PublicKey publicKey) { ECPoint p = CalculatePoint(publicKey.KeyParam); BigInteger x = p.AffineXCoord.ToBigInteger(); BigInteger y = p.AffineYCoord.ToBigInteger(); byte[] xbuf = x.ToByteArrayUnsigned(); var ybuf = new byte[] { (byte)(y.TestBit(0) ? 0x03 : 0x02) }; var hash = new Sha256Digest(); var result = new byte[hash.GetDigestSize()]; hash.BlockUpdate(ybuf, 0, ybuf.Length); hash.BlockUpdate(xbuf, 0, xbuf.Length); hash.DoFinal(result, 0); return(new SymmetricKey(result)); }
public byte[] ECDH(PublicKey publicKey) { var P = CalculatePoint(publicKey.keyParam); var x = P.AffineXCoord.ToBigInteger(); var y = P.AffineYCoord.ToBigInteger(); var xbuf = x.ToByteArrayUnsigned(); var ybuf = y.TestBit(0) ? new byte[] { 0x03 } : new byte[] { 0x02 }; var hash = new Sha256Digest(); var result = new byte[hash.GetDigestSize()]; hash.BlockUpdate(ybuf, 0, ybuf.Length); hash.BlockUpdate(xbuf, 0, xbuf.Length); hash.DoFinal(result, 0); return(result); }
/// <summary> /// SHA256 computation /// </summary> /// <param name="data">the data to hash</param> /// <param name="key">optional hmac key</param> /// <returns>the hash value</returns> private static byte[] ComputeSha256(byte[] data, byte[] key) { byte[] outData = new byte[16]; if (key != null) { var digest = new HMac(new Sha256Digest()); digest.Init(new KeyParameter(key)); digest.BlockUpdate(data, 0, data.Length); digest.DoFinal(outData, 0); } else { var digest = new Sha256Digest(); digest.BlockUpdate(data, 0, data.Length); digest.DoFinal(outData, 0); } return(outData); }
/// <summary> /// Hashes the key for keyczar version look ups. /// </summary> /// <param name="size">The size.</param> /// <param name="components">The components.</param> /// <returns></returns> public static byte[] UnofficalHashKey(int size, params byte[][] components) { var sha1 = new Sha256Digest(); foreach (var data in components) { sha1.BlockUpdate(data, 0, data.Length); } var hash = new byte[sha1.GetDigestSize()]; sha1.DoFinal(hash, 0); sha1.Reset(); var outBytes = new byte[size]; Array.Copy(hash, 0, outBytes, 0, outBytes.Length); return(outBytes); }
private byte[] LmtosPublic(int node) { int p = Constants.Values[(int)_lmotsType].p; int limit = (1 << Constants.Values[(int)_lmotsType].w) - 1; ushort i; byte[] q = u32str(node); byte[] jX = new byte[1]; byte[][] y = new byte[p][]; for (i = 0; i < p; i++) { byte[] tmp = new byte[32]; Array.Copy(_x[node], i * 32, tmp, 0, 32); byte[] iX = u16str(i); for (int j = 0; j < limit; j++) { jX[0] = (byte)j; tmp = ComputeHash(new Sha256Digest(), new byte[][] { Identifier, q, iX, jX, tmp }); } y[i] = tmp; } IDigest dig = new Sha256Digest(); dig.BlockUpdate(Identifier, 0, Identifier.Length); dig.BlockUpdate(q, 0, q.Length); dig.BlockUpdate(D_PBLC, 0, 2); for (i = 0; i < p; i++) { dig.BlockUpdate(y[i], 0, y[i].Length); } byte[] K = new byte[32]; dig.DoFinal(K, 0); byte[] pubKey = new byte[4 + 16 + 4 + K.Length]; Array.Copy(u32str((int)_lmotsType), pubKey, 4); Array.Copy(Identifier, 0, pubKey, 4, Identifier.Length); Array.Copy(q, 0, pubKey, 20, 4); Array.Copy(K, 0, pubKey, 24, K.Length); return(pubKey); }
private byte[] GenerateSeed() { //Hash the passphrasse 50,000 times var passPhraseBytes = new byte[_password.Length * sizeof(char)]; Buffer.BlockCopy(_password.ToCharArray(), 0, passPhraseBytes, 0, passPhraseBytes.Length); var digester = new Sha256Digest(); var seed = new byte[digester.GetDigestSize()]; digester.BlockUpdate(seed, 0, seed.Length); digester.DoFinal(seed, 0); for (var i = 0; i < 49999; i++) { digester = new Sha256Digest(); digester.BlockUpdate(seed, 0, seed.Length); digester.DoFinal(seed, 0); } return(seed); }
static byte[] GenerateAESKey(ECPublicKeyParameters bobPublicKey, AsymmetricKeyParameter alicePrivateKey) { ECDHBasicAgreement aKeyAgree = new ECDHBasicAgreement(); aKeyAgree.Init(alicePrivateKey); byte[] sharedSecret = aKeyAgree.CalculateAgreement(bobPublicKey).ToByteArray(); // make sure each part has the correct and same size ResizeRight(ref sharedSecret, 66); // 66 is the desired key size Sha256Digest digest = new Sha256Digest(); byte[] symmetricKey = new byte[digest.GetDigestSize()]; digest.BlockUpdate(sharedSecret, 0, sharedSecret.Length); digest.DoFinal(symmetricKey, 0); return(symmetricKey); }
public static string GeradorHashCode(string mensagem) { // 1- Pega os bytes da mesagem byte[] bitsMensagem = Encoding.UTF8.GetBytes(mensagem); // 2- Cria o objeto SHA256 que irá calcular o hash da mesagem Sha256Digest CalculaHash = new Sha256Digest(); CalculaHash.BlockUpdate(bitsMensagem, 0, bitsMensagem.Length); // 3- Executa o método [ComputeHash] para calcular o Hash e retornar os bytes byte[] BytesHash = new byte[CalculaHash.GetDigestSize()]; CalculaHash.DoFinal(BytesHash, 0); // 4- Converte os bytes para hexadecimal e retorna um array de bytes byte[] sha256hex2 = Hex.Encode(BytesHash); // 4.1- Convert em uma string o array de bytes string sha256hex = Encoding.UTF8.GetString(sha256hex2).ToLower(); return(sha256hex); }
public byte[] CalculateSharedSecret(byte[] remotePublicKey) { if (!m_bInited) { Init(); } DHPublicKeyParameters remoteKeyParameters = new DHPublicKeyParameters(new BigInteger(1, remotePublicKey), m_dhParameters); DHBasicAgreement agreement = new DHBasicAgreement(); agreement.Init(m_keyPair.Private); byte[] resAgreement = agreement.CalculateAgreement(remoteKeyParameters).ToByteArrayUnsigned(); Sha256Digest digest = new Sha256Digest(); byte[] resHash = new byte[digest.GetDigestSize()]; digest.BlockUpdate(resAgreement, 0, resAgreement.Length); digest.DoFinal(resHash, 0); SharedSecret = resHash; return(resHash); }
public byte[] GetHash(byte[] input, int times = 1) { if (times <= 0) { throw new ArgumentException("times should be more than 0", nameof(times)); } var digest = new Sha256Digest(); var saltBytes = new byte[input.Length]; byte[] result = null; Array.Copy(input, saltBytes, input.Length); for (int i = 0; i < times; i++) { digest.BlockUpdate(saltBytes, 0, saltBytes.Length); result = new byte[digest.GetDigestSize()]; digest.DoFinal(result, 0); } return(result); }
private byte[] ComputePubPart(int i, int two2H) { Sha256Digest digest = new Sha256Digest(); digest.BlockUpdate(Identifier, 0, Identifier.Length); digest.BlockUpdate(u32str(i), 0, 4); if (i >= two2H) { digest.BlockUpdate(D_LEAF, 0, 2); digest.BlockUpdate(LmtosPublic(i - two2H), 24, 32); } else { digest.BlockUpdate(D_INTR, 0, 2); digest.BlockUpdate(ComputePubPart(i * 2, two2H), 0, 32); digest.BlockUpdate(ComputePubPart(i * 2 + 1, two2H), 0, 32); } byte[] result = new byte[32]; digest.DoFinal(result, 0); return(result); }
public static string HashSomething(string password, string something) { var dig = new Sha256Digest(); byte[] bpassword = Encoding.UTF8.GetBytes(password); dig.BlockUpdate(bpassword, 0, bpassword.Length); var key = new byte[dig.GetDigestSize()]; dig.DoFinal(key, 0); var hmac = new HMac(new Sha256Digest()); hmac.Init(new KeyParameter(key)); byte[] input = Encoding.UTF8.GetBytes(something); hmac.BlockUpdate(input, 0, input.Length); var output = new byte[hmac.GetMacSize()]; hmac.DoFinal(output, 0); var sb = new StringBuilder(output.Length*2); foreach (byte b in output) { sb.AppendFormat("{0:x2}", b); } return sb.ToString(); }
public static byte[] DoSignEcDsaSha256P256_old(IEnumerable <BufLen> bufs, I2PSigningPrivateKey key) { var sha = new Sha256Digest(); foreach (var buf in bufs) { sha.BlockUpdate(buf.BaseArray, buf.BaseArrayOffset, buf.Length); } var hash = new byte[sha.GetDigestSize()]; sha.DoFinal(hash, 0); var p = Org.BouncyCastle.Asn1.Nist.NistNamedCurves.GetByName("P-256"); var param = new ECDomainParameters(p.Curve, p.G, p.N, p.H); var pk = new ECPrivateKeyParameters(key.ToBigInteger(), param); var s = new Org.BouncyCastle.Crypto.Signers.ECDsaSigner(); s.Init(true, new ParametersWithRandom(pk)); var sig = s.GenerateSignature(hash); var result = new byte[64]; var b1 = sig[0].ToByteArrayUnsigned(); var b2 = sig[1].ToByteArrayUnsigned(); // https://geti2p.net/en/docs/spec/common-structures#type_Signature // When a signature is composed of two elements (for example values R,S), // it is serialized by padding each element to length/2 with leading zeros if necessary. // All types are Big Endian, except for EdDSA, which is stored and transmitted in a Little Endian format. // Pad msb. Big endian. Array.Copy(b1, 0, result, 0 + 20 - b1.Length, b1.Length); Array.Copy(b2, 0, result, 20 + 20 - b2.Length, b2.Length); DebugUtils.LogDebug("DoSignEcDsaSha256P256: Used."); return(result); }
/// <summary> /// Get Switcheo NEO Signature /// </summary> /// <param name="message">Message to sign</param> /// <param name="privateKey">Private key of wallet</param> /// <returns>String of signed message</returns> private string GetSwitcheoNeoSignature(byte[] message, byte[] privateKey) { var curve = SecNamedCurves.GetByName("secp256r1"); var domain = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H); var priv = new ECPrivateKeyParameters("ECDSA", (new Org.BouncyCastle.Math.BigInteger(1, privateKey)), domain); var signer = new ECDsaSigner(); var hash = new Sha256Digest(); hash.BlockUpdate(message, 0, message.Length); var result = new byte[32]; hash.DoFinal(result, 0); message = result; signer.Init(true, priv); var signature = signer.GenerateSignature(message); return(ProcessNeoSignature(signature)); }
/// <summary> /// Hash stream with SHA256 /// </summary> /// <param name="input">Input stream</param> /// <param name="bufferSize">Buffer size</param> /// <returns>Hash</returns> public static byte[] Hash(Stream input, int bufferSize = 4096) { byte[] result = new byte[32]; Sha256Digest sha256 = new Sha256Digest(); int bytesRead; byte[] buffer = new byte[bufferSize]; do { bytesRead = input.Read(buffer, 0, bufferSize); if (bytesRead > 0) { sha256.BlockUpdate(buffer, 0, bytesRead); } } while (bytesRead == bufferSize); sha256.DoFinal(result, 0); return(result); }
public static byte[] SignRFC6979(this ECDsa key, byte[] data) { var digest = new Sha256Digest(); var secp256r1 = SecNamedCurves.GetByName("secp256r1"); var ec_parameters = new ECDomainParameters(secp256r1.Curve, secp256r1.G, secp256r1.N); var private_key = new ECPrivateKeyParameters(new BigInteger(1, key.PrivateKey()), ec_parameters); var signer = new ECDsaSigner(new HMacDsaKCalculator(digest)); var hash = new byte[digest.GetDigestSize()]; digest.BlockUpdate(data, 0, data.Length); digest.DoFinal(hash, 0); signer.Init(true, private_key); var rs = signer.GenerateSignature(hash); var signature = new byte[RFC6979SignatureSize]; var rbytes = rs[0].ToByteArrayUnsigned(); var sbytes = rs[1].ToByteArrayUnsigned(); var index = RFC6979SignatureSize / 2 - rbytes.Length; rbytes.CopyTo(signature, index); index = RFC6979SignatureSize - sbytes.Length; sbytes.CopyTo(signature, index); return(signature); }
void OnSvAppSecureHandshake(string id, JsonObj args) { // https://davidtavarez.github.io/2019/implementing-elliptic-curve-diffie-hellman-c-sharp/ X9ECParameters x9Params = NistNamedCurves.GetByName("P-521"); ECDomainParameters domainParams = new ECDomainParameters(x9Params.Curve, x9Params.G, x9Params.N, x9Params.H, x9Params.GetSeed()); ECKeyPairGenerator generator = (ECKeyPairGenerator)GeneratorUtilities.GetKeyPairGenerator("ECDH"); generator.Init(new ECKeyGenerationParameters(domainParams, new SecureRandom())); AsymmetricCipherKeyPair aliceKeyPair = generator.GenerateKeyPair(); ECPublicKeyParameters alicePublicKeyParams = (ECPublicKeyParameters)aliceKeyPair.Public; string bobKey = args.Get <string>("key"); byte[] bobKeyBytes = System.Convert.FromBase64String(bobKey); var bobPoint = x9Params.Curve.DecodePoint(bobKeyBytes); ECPublicKeyParameters bobPublicKeyParams = new ECPublicKeyParameters("ECDH", bobPoint, SecObjectIdentifiers.SecP521r1); IBasicAgreement agreement = AgreementUtilities.GetBasicAgreement("ECDH"); agreement.Init(aliceKeyPair.Private); BigInteger sharedSecret = agreement.CalculateAgreement(bobPublicKeyParams); IDigest digest = new Sha256Digest(); byte[] sharedSecretBytes = sharedSecret.ToBytes(66); digest.BlockUpdate(sharedSecretBytes, 0, sharedSecretBytes.Length); derivedKeyBytes = new byte[digest.GetDigestSize()]; digest.DoFinal(derivedKeyBytes, 0); Debug.Log(System.BitConverter.ToString(sharedSecretBytes)); Debug.Log(System.Convert.ToBase64String(derivedKeyBytes)); ReturnSuccess(id, new JsonObj() { ["key"] = alicePublicKeyParams.Q.GetEncoded(), }); }
public bool Verify(byte[] message, byte[] signature) { if (message == null) { throw new ArgumentNullException(nameof(message)); } if (signature == null) { throw new ArgumentNullException(nameof(signature)); } var h = new Sha256Digest(); var hashed = new byte[h.GetDigestSize()]; h.BlockUpdate(message, 0, message.Length); h.DoFinal(hashed, 0); h.Reset(); return(CryptoConfig.CryptoBackend.Verify( new HashDigest <SHA256>(hashed), signature, this)); }