internal SecureMimeDigitalCertificate(X509Certificate certificate) { Certificate = certificate; var pubkey = certificate.GetPublicKey (); if (pubkey is DsaKeyParameters) PublicKeyAlgorithm = PublicKeyAlgorithm.Dsa; else if (pubkey is RsaKeyParameters) PublicKeyAlgorithm = PublicKeyAlgorithm.RsaGeneral; else if (pubkey is ElGamalKeyParameters) PublicKeyAlgorithm = PublicKeyAlgorithm.ElGamalGeneral; else if (pubkey is ECKeyParameters) PublicKeyAlgorithm = PublicKeyAlgorithm.EllipticCurve; else if (pubkey is DHKeyParameters) PublicKeyAlgorithm = PublicKeyAlgorithm.DiffieHellman; var encoded = certificate.GetEncoded (); var fingerprint = new StringBuilder (); var sha1 = new Sha1Digest (); var data = new byte[20]; sha1.BlockUpdate (encoded, 0, encoded.Length); sha1.DoFinal (data, 0); for (int i = 0; i < data.Length; i++) fingerprint.Append (data[i].ToString ("X2")); Fingerprint = fingerprint.ToString (); }
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; }
/// <summary> /// Compute the hash of the input byte array and return the hashed value as a byte array. /// </summary> /// <param name="inputData">Input data</param> /// <returns>SHA1 Hashed data.</returns> byte[] IHashProvider.ComputeHash( byte[] inputData ) { Sha1Digest digest = new Sha1Digest(); digest.BlockUpdate( inputData, 0, inputData.Length ); byte[] result = new byte[digest.GetDigestSize()]; digest.DoFinal( result, 0 ); return 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); }
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); }
/** * * 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; }
/** * * Calulates the keyidentifier using a SHA1 hash over the BIT STRING * from SubjectPublicKeyInfo as defined in RFC2459. * * Example of making a AuthorityKeyIdentifier: * <pre> * SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence)new ASN1InputStream( * publicKey.getEncoded()).readObject()); * AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); * </pre> * **/ public AuthorityKeyIdentifier( 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 = new DerOctetString(resBuf); }
/// <summary> /// Gets the fingerprint of the certificate. /// </summary> /// <remarks> /// A fingerprint is a SHA-1 hash of the raw certificate data and is often used /// as a unique identifier for a particular certificate in a certificate store. /// </remarks> /// <returns>The fingerprint.</returns> /// <param name="certificate">The certificate.</param> public static string GetFingerprint(this X509Certificate certificate) { var encoded = certificate.GetEncoded (); var fingerprint = new StringBuilder (); var sha1 = new Sha1Digest (); var data = new byte[20]; sha1.BlockUpdate (encoded, 0, encoded.Length); sha1.DoFinal (data, 0); for (int i = 0; i < data.Length; i++) fingerprint.Append (data[i].ToString ("x2")); return fingerprint.ToString (); }
/** * create an AuthorityKeyIdentifier with the GeneralNames tag and * the serial number provided as well. */ public AuthorityKeyIdentifier( SubjectPublicKeyInfo spki, GeneralNames name, BigInteger serialNumber) { 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 = new DerOctetString(resBuf); this.certissuer = name; this.certserno = new DerInteger(serialNumber); }
public static string CreateResponseKey(string requestKey) { var combined = requestKey + WebSocketResponseGuid; #if !PORTABLE var bytes = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(combined)); #else var bytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(combined); IDigest hash = new Sha1Digest(); byte[] result = new byte[hash.GetDigestSize()]; hash.BlockUpdate(bytes, 0, bytes.Length); hash.DoFinal(result, 0); bytes = result; //// Convert the message string to binary data. //IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(combined, BinaryStringEncoding.Utf8); //// Create a HashAlgorithmProvider object. //HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5); //// Demonstrate how to retrieve the name of the hashing algorithm. //String strAlgNameUsed = objAlgProv.AlgorithmName; //// Hash the message. //IBuffer buffHash = objAlgProv.HashData(buffUtf8Msg); //// Verify that the hash length equals the length specified for the algorithm. //if (buffHash.Length != objAlgProv.HashLength) //{ // throw new Exception("There was an error creating the hash"); //} //// Convert the hash to a string (for display). //String strHashBase64 = CryptographicBuffer.EncodeToBase64String(buffHash); //byte[] bytes = new byte[buffHash.Length]; //CryptographicBuffer.CopyToByteArray(buffHash, out bytes); #endif return Convert.ToBase64String(bytes); }
private static byte[] GetDigest( 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); return resBuf; }
public override void PerformTest() { IDigest digest = new Sha1Digest(); byte[] resBuf = new byte[digest.GetDigestSize()]; string resStr; // // test 1 // digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec1.Equals(resStr)) { Fail("failing standard vector test 1" + SimpleTest.NewLine + " expected: " + resVec1 + SimpleTest.NewLine + " got : " + resStr); } // // test 2 // byte[] bytes = Hex.Decode(testVec2); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec2.Equals(resStr)) { Fail("failing standard vector test 2" + SimpleTest.NewLine + " expected: " + resVec2 + SimpleTest.NewLine + " got : " + resStr); } // // test 3 // bytes = Hex.Decode(testVec3); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec3.Equals(resStr)) { Fail("failing standard vector test 3" + SimpleTest.NewLine + " expected: " + resVec3 + SimpleTest.NewLine + " got : " + resStr); } // // test 4 // bytes = Hex.Decode(testVec4); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec4.Equals(resStr)) { Fail("failing standard vector test 4" + SimpleTest.NewLine + " expected: " + resVec4 + SimpleTest.NewLine + " got : " + resStr); } // // test 5 // bytes = Hex.Decode(testVec4); digest.BlockUpdate(bytes, 0, bytes.Length / 2); // clone the IDigest IDigest d = new Sha1Digest((Sha1Digest)digest); digest.BlockUpdate(bytes, bytes.Length / 2, bytes.Length - bytes.Length / 2); digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec4.Equals(resStr)) { Fail("failing standard vector test 5" + SimpleTest.NewLine + " expected: " + resVec4 + SimpleTest.NewLine + " got : " + resStr); } d.BlockUpdate(bytes, bytes.Length / 2, bytes.Length - bytes.Length / 2); d.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec4.Equals(resStr)) { Fail("failing standard vector test 5" + SimpleTest.NewLine + " expected: " + resVec4 + SimpleTest.NewLine + " got : " + resStr); } }
/// <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> private 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 byte[] SignDsa(byte[] buffer, int length) { var signer = new DsaSigner(); signer.Init(true, new ParametersWithRandom(PrivateKeyFactory.CreateKey(PrivateKey), _secureRandom)); var sha1 = new Sha1Digest(); sha1.BlockUpdate(buffer, 0, length); byte[] hash = new byte[sha1.GetDigestSize()]; sha1.DoFinal(hash, 0); var signature = signer.GenerateSignature(hash); byte[] res = new byte[41]; res[0] = PublicKey[0]; signature[0].ToByteArrayUnsigned().CopyTo(res, 1); signature[1].ToByteArrayUnsigned().CopyTo(res, 21); return res; }
public static byte[] SHA1(byte[] data, int count) { var sha1 = new Sha1Digest(); sha1.BlockUpdate(data, 0, count); byte[] rv = new byte[20]; sha1.DoFinal(rv, 0); return rv; }
private bool VerifyDsa(byte[] buffer, int length, byte[] signature) { int numberSize = 64 + PublicKey[0] * 8; DsaPublicKeyParameters parameters = new DsaPublicKeyParameters( new BigInteger(1, PublicKey, 21 + 2 * numberSize, numberSize), new DsaParameters( new BigInteger(1, PublicKey, 21, numberSize), new BigInteger(1, PublicKey, 1, 20), new BigInteger(1, PublicKey, 21 + numberSize, numberSize)) ); var dsa = new DsaSigner(); dsa.Init(false, parameters); var sha1 = new Sha1Digest(); sha1.BlockUpdate(buffer, 0, length); byte[] hash = new byte[sha1.GetDigestSize()]; sha1.DoFinal(hash, 0); return dsa.VerifySignature(hash, new BigInteger(1, signature, 1, 20), new BigInteger(1, signature, 21, 20)); }
public override string hash(string pw) { Sha1Digest digest = new Sha1Digest(); // 8 byte random salt byte[] salt = randomSalt(8); // Generate the hash of the password + salt byte[] password = Encoding.UTF8.GetBytes(pw); digest.BlockUpdate(password, 0, password.Length); digest.BlockUpdate(salt, 0, salt.Length); int digestSize = digest.GetDigestSize(); byte[] hashData = new byte[digestSize]; digest.DoFinal(hashData, 0); // Put the salt on the end of the hashed password + salt byte[] result = new byte[hashData.Length + salt.Length]; hashData.CopyTo(result, 0); salt.CopyTo(result, hashData.Length); // Return in base 64 return "{SSHA}" + Convert.ToBase64String(result); }
// signature public static string CreateSignature(string email, string password, RsaKeyParameters key) { byte[] prefix = { 0x00 }; var keyStruct = KeyToStruct(key); var toEncrypt = Encoding.UTF8.GetBytes(email + "\x00" + password); var cipher = new OaepEncoding(new RsaEngine(), new Sha1Digest(), null); cipher.Init(true, key); var encrypted = cipher.ProcessBlock(toEncrypt, 0, toEncrypt.Length); var digest = new Sha1Digest(); var hash = new byte[digest.GetByteLength()]; digest.BlockUpdate(keyStruct, 0, keyStruct.Length); digest.DoFinal(hash, 0); var hashExcerpt = hash.Take(4).ToArray(); return DataTypeUtils.UrlSafeBase64(DataTypeUtils.CombineBytes(prefix, hashExcerpt, encrypted)); }
static void Main(string[] args) { var assembly = Assembly.GetExecutingAssembly(); var title = (AssemblyTitleAttribute)Attribute.GetCustomAttribute(assembly, typeof(AssemblyTitleAttribute)); Console.WriteLine("{0} version {1}", title.Title, assembly.GetName().Version); var copyright = (AssemblyCopyrightAttribute)Attribute.GetCustomAttribute(assembly, typeof(AssemblyCopyrightAttribute)); Console.WriteLine(copyright.Copyright); Console.WriteLine("More information can be found at https://Jexus.codeplex.com"); Console.WriteLine(); var baseAddress = args.Length > 0 ? args[0] : "https://*****:*****@"Remote services must be run as root on Linux."); return; } if (!File.Exists("jws")) { Console.WriteLine(@"Remote services must be running in Jexus installation folder."); return; } var loc = baseAddress.LastIndexOf(':'); var port = "443"; if (loc != -1) { port = baseAddress.Substring(loc + 1); } string dirname = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); string path = Path.Combine(dirname, ".mono", "httplistener"); if (false == Directory.Exists(path)) { Directory.CreateDirectory(path); } string target_cert = Path.Combine(path, string.Format("{0}.cer", port)); if (File.Exists(target_cert)) { Console.WriteLine("Use {0}", target_cert); } else { Console.WriteLine("Generating a self-signed certificate for Jexus Manager"); // Generate certificate string defaultIssuer = "CN=jexus.lextudio.com"; string defaultSubject = "CN=jexus.lextudio.com"; byte[] sn = Guid.NewGuid().ToByteArray(); string subject = defaultSubject; string issuer = defaultIssuer; DateTime notBefore = DateTime.Now; DateTime notAfter = new DateTime(643445675990000000); // 12/31/2039 23:59:59Z RSA issuerKey = new RSACryptoServiceProvider(2048); RSA subjectKey = null; bool selfSigned = true; string hashName = "SHA1"; CspParameters subjectParams = new CspParameters(); CspParameters issuerParams = new CspParameters(); BasicConstraintsExtension bce = new BasicConstraintsExtension { PathLenConstraint = BasicConstraintsExtension.NoPathLengthConstraint, CertificateAuthority = true }; ExtendedKeyUsageExtension eku = new ExtendedKeyUsageExtension(); eku.KeyPurpose.Add("1.3.6.1.5.5.7.3.1"); SubjectAltNameExtension alt = null; string p12file = Path.Combine(path, "temp.pfx"); string p12pwd = "test"; // serial number MUST be positive if ((sn[0] & 0x80) == 0x80) sn[0] -= 0x80; if (selfSigned) { if (subject != defaultSubject) { issuer = subject; issuerKey = subjectKey; } else { subject = issuer; subjectKey = issuerKey; } } if (subject == null) throw new Exception("Missing Subject Name"); X509CertificateBuilder cb = new X509CertificateBuilder(3); cb.SerialNumber = sn; cb.IssuerName = issuer; cb.NotBefore = notBefore; cb.NotAfter = notAfter; cb.SubjectName = subject; cb.SubjectPublicKey = subjectKey; // extensions if (bce != null) cb.Extensions.Add(bce); if (eku != null) cb.Extensions.Add(eku); if (alt != null) cb.Extensions.Add(alt); IDigest digest = new Sha1Digest(); byte[] resBuf = new byte[digest.GetDigestSize()]; var spki = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(DotNetUtilities.GetRsaPublicKey(issuerKey)); byte[] bytes = spki.PublicKeyData.GetBytes(); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); cb.Extensions.Add(new SubjectKeyIdentifierExtension { Identifier = resBuf }); cb.Extensions.Add(new AuthorityKeyIdentifierExtension { Identifier = resBuf }); // signature cb.Hash = hashName; byte[] rawcert = cb.Sign(issuerKey); PKCS12 p12 = new PKCS12(); p12.Password = p12pwd; ArrayList list = new ArrayList(); // we use a fixed array to avoid endianess issues // (in case some tools requires the ID to be 1). list.Add(new byte[4] { 1, 0, 0, 0 }); Hashtable attributes = new Hashtable(1); attributes.Add(PKCS9.localKeyId, list); p12.AddCertificate(new Mono.Security.X509.X509Certificate(rawcert), attributes); p12.AddPkcs8ShroudedKeyBag(subjectKey, attributes); p12.SaveToFile(p12file); var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(p12file, p12pwd, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable); // Install certificate string target_pvk = Path.Combine(path, string.Format("{0}.pvk", port)); using (Stream cer = File.OpenWrite(target_cert)) { byte[] raw = x509.RawData; cer.Write(raw, 0, raw.Length); } PrivateKey pvk = new PrivateKey(); pvk.RSA = subjectKey; pvk.Save(target_pvk); } } JexusServer.Credentials = args.Length > 2 ? args[1] + "|" + args[2] : "jexus|lextudio.com"; JexusServer.Timeout = args.Length > 3 ? double.Parse(args[3]) : 30D; using (WebApp.Start<Startup>(url: baseAddress)) { Console.WriteLine("Remote services have started at {0}.", baseAddress); Console.WriteLine("Credentials is {0}", JexusServer.Credentials); Console.WriteLine("Press Enter to quit."); Console.ReadLine(); } }
/** * which Generates the p and g values from the given parameters, * returning the DsaParameters object. * <p> * Note: can take a while...</p> */ public DsaParameters GenerateParameters() { byte[] seed = new byte[20]; byte[] part1 = new byte[20]; byte[] part2 = new byte[20]; byte[] u = new byte[20]; Sha1Digest sha1 = new Sha1Digest(); int n = (size - 1) / 160; byte[] w = new byte[size / 8]; BigInteger q = null, p = null, g = null; int counter = 0; bool primesFound = false; while (!primesFound) { do { random.NextBytes(seed); sha1.BlockUpdate(seed, 0, seed.Length); sha1.DoFinal(part1, 0); Array.Copy(seed, 0, part2, 0, seed.Length); Add(part2, seed, 1); sha1.BlockUpdate(part2, 0, part2.Length); sha1.DoFinal(part2, 0); for (int i = 0; i != u.Length; i++) { u[i] = (byte)(part1[i] ^ part2[i]); } u[0] |= (byte)0x80; u[19] |= (byte)0x01; q = new BigInteger(1, u); } while (!q.IsProbablePrime(certainty)); counter = 0; int offset = 2; while (counter < 4096) { for (int k = 0; k < n; k++) { Add(part1, seed, offset + k); sha1.BlockUpdate(part1, 0, part1.Length); sha1.DoFinal(part1, 0); Array.Copy(part1, 0, w, w.Length - (k + 1) * part1.Length, part1.Length); } Add(part1, seed, offset + n); sha1.BlockUpdate(part1, 0, part1.Length); sha1.DoFinal(part1, 0); Array.Copy(part1, part1.Length - ((w.Length - (n) * part1.Length)), w, 0, w.Length - n * part1.Length); w[0] |= (byte)0x80; BigInteger x = new BigInteger(1, w); BigInteger c = x.Mod(q.ShiftLeft(1)); p = x.Subtract(c.Subtract(BigInteger.One)); if (p.TestBit(size - 1)) { if (p.IsProbablePrime(certainty)) { primesFound = true; break; } } counter += 1; offset += n + 1; } } // // calculate the generator g // BigInteger pMinusOneOverQ = p.Subtract(BigInteger.One).Divide(q); for (;;) { BigInteger h = new BigInteger(size, random); if (h.CompareTo(BigInteger.One) <= 0 || h.CompareTo(p.Subtract(BigInteger.One)) >= 0) { continue; } g = h.ModPow(pMinusOneOverQ, p); if (g.CompareTo(BigInteger.One) <= 0) { continue; } break; } return new DsaParameters(p, q, g, new DsaValidationParameters(seed, counter)); }
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); }
public static byte[] Digest(byte[] data, String algo) { if (algo == null) { throw new ArgumentNullException("El algoritmo de huella digital no puede ser nulo"); } if (data == null) { throw new ArgumentNullException("Los datos no pueden ser nulos"); } switch (algo) { /** * ALGORITMOS DE HASING */ case AOSignConstants.SIGN_ALGORITHM_SHA1: { Sha1Digest dig = new Sha1Digest(); dig.BlockUpdate(data, 0, data.Length); byte[] result = new byte[dig.GetDigestSize()]; dig.DoFinal(result, 0); return result; } case AOSignConstants.SIGN_ALGORITHM_SHA256: { Sha256Digest dig = new Sha256Digest(); dig.BlockUpdate(data, 0, data.Length); byte[] result = new byte[dig.GetDigestSize()]; dig.DoFinal(result, 0); return result; } case AOSignConstants.SIGN_ALGORITHM_SHA384: { Sha384Digest dig = new Sha384Digest(); dig.BlockUpdate(data, 0, data.Length); byte[] result = new byte[dig.GetDigestSize()]; dig.DoFinal(result, 0); return result; } case AOSignConstants.SIGN_ALGORITHM_SHA512: { Sha512Digest dig = new Sha512Digest(); dig.BlockUpdate(data, 0, data.Length); byte[] result = new byte[dig.GetDigestSize()]; dig.DoFinal(result, 0); return result; } case AOSignConstants.SIGN_ALGORITHM_RIPEMD160: { RipeMD160Digest dig = new RipeMD160Digest(); dig.BlockUpdate(data, 0, data.Length); byte[] result = new byte[dig.GetDigestSize()]; dig.DoFinal(result, 0); return result; } case AOSignConstants.SIGN_ALGORITHM_MD5: { MD5Digest dig = new MD5Digest(); dig.BlockUpdate(data, 0, data.Length); byte[] result = new byte[dig.GetDigestSize()]; dig.DoFinal(result, 0); return result; } case AOSignConstants.SIGN_ALGORITHM_MD2: { MD2Digest dig = new MD2Digest(); dig.BlockUpdate(data, 0, data.Length); byte[] result = new byte[dig.GetDigestSize()]; dig.DoFinal(result, 0); return result; } default: // You can use the default case. throw new ArgumentNullException("El algoritmo no es reconocido"); } throw new ArgumentNullException("Algoritmo de hash no soportado: " + algo); }
/// <summary> /// Hashes each component of the key hash with it's length first. /// </summary> /// <param name="size">The size.</param> /// <param name="components">The components.</param> /// <returns></returns> public static byte[] HashKeyLengthPrefix(int size, params byte[][] components) { var sha1 = new Sha1Digest(); foreach (var data in components) { byte[] length = GetBytes(data.Length); sha1.BlockUpdate(length, 0, length.Length); 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; }