using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
namespace hng.encuestas.framework.Classes {
///
/// HashValuesProvider
///
public class HashValuesProvider {
private static byte[] seedValues = { 0x41, 0x6e, 0x64, 0x72, 0x65, 0x61, 0x20, 0x53, 0x6f, 0x66, 0x69, 0x61 };
private static int AUTH_KEY_LENGTH = 7;
///
/// Calculates SHA1 hash
///
///
///
/// Acceptable Terms are the following
/// (case sensitive):
///
- "MD5"
- "SHA1"
- "SHA256"
- "SHA384"
- "SHA512"
///
///
///
///
///
///
///
///
/// input string
/// Character encoding
/// Hash Algorithm Type
///
public static string CalculateHash(string text, Encoding enc, string hashType) {
//Convert string to byte buffer:
byte[] buffer = enc.GetBytes(text);
//HashAlgorithm is IDisposable:
using (HashAlgorithm hashAlgorithm =
HashAlgorithm.Create(hashType)) {
byte[] hashBuffer =
hashAlgorithm.ComputeHash(buffer);
byte[] combinedHash = new byte[hashBuffer.Length + seedValues.Length];
seedValues.CopyTo(combinedHash, 0);
hashBuffer.CopyTo(combinedHash, seedValues.Length);
//Method a:
//System.Text.StringBuilder sb =
// new System.Text.StringBuilder();
//foreach (byte b in hashBuffer) {
// sb.Append(b.ToString("x2"));//'X2' for uppercase
//}
//return sb.ToString();
//Method B:
//string hashString =
// BitConverter.ToString(hashBuffer);
//The output looks like:
//"19-E2-62-AE-3A-84-0D-72-1F-EF-32-C9-25-D1-A1-89-67-13-5F-58"
//so you want to remove the hashes in most cases:
//return hashString.Replace("-", "");
//Method C: Homebrewed speed:
//Convert 20byte buffer to string...
return ConvertHexByteArrayToString(combinedHash);
}
}
///
/// Convertir un Arreglo de Bytes a String
///
/// Buffer
///
private static string ConvertHexByteArrayToString(byte[] buffer) {
char[] result = new char[buffer.Length * 2];
int i = 0;
foreach (byte b in buffer) {
result[i] = GetHexValue(b / 0x10);
result[i + 1] = GetHexValue(b % 0x10);
i += 2;
}
return new string(result, 0, result.Length);
}
///
/// Obtener el Valor Hexadecimal del entero X
///
/// Int
///
private static char GetHexValue(int X) {
return (char)((X < 10) ? (X + 0x30) : ((X - 10) + 0x41));
}
///
/// Generar Llave de Autorización
///
/// Prefijo
/// Fecha
///
public static string GenerateAuthorizationKey(string prefix, DateTime date) {
string str;
if (prefix == null)
prefix = string.Empty;
prefix = prefix.Trim();
str = date.Ticks.ToString();
if(str.Length > 7)
str = str.Substring(str.Length - AUTH_KEY_LENGTH);
return prefix + str;
}
}
}
No hay comentarios:
Publicar un comentario