Geen omschrijving
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

hasher_sha256.rs 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. extern crate sha2;
  2. #[cfg(feature = "SHA2")]
  3. use self::sha2::Sha256;
  4. pub struct Sha256;
  5. pub trait Hasher {
  6. type Output: HashResult;
  7. fn hash(input: &[u8]) -> Self::Output;
  8. }
  9. pub trait HashResult {
  10. /// Get the output in hex notation.
  11. fn hex(&self) -> String;
  12. /// Size of the output in bytes.
  13. fn size() -> usize;
  14. }
  15. impl Hasher for Sha256 {
  16. type Output = [u8; 32];
  17. fn hash(input: &[u8]) -> Self::Output {
  18. use self::sha2::*;
  19. let mut tmp = Sha256::new();
  20. tmp.input(input);
  21. let r = tmp.result().as_slice().to_vec();
  22. [
  23. r[0],
  24. r[1],
  25. r[2],
  26. r[3],
  27. r[4],
  28. r[5],
  29. r[6],
  30. r[7],
  31. r[8],
  32. r[9],
  33. r[10],
  34. r[11],
  35. r[12],
  36. r[13],
  37. r[14],
  38. r[15],
  39. r[16],
  40. r[17],
  41. r[18],
  42. r[19],
  43. r[20],
  44. r[21],
  45. r[22],
  46. r[23],
  47. r[24],
  48. r[25],
  49. r[26],
  50. r[27],
  51. r[28],
  52. r[29],
  53. r[30],
  54. r[31],
  55. ]
  56. }
  57. }
  58. impl HashResult for [u8; 32] {
  59. fn hex(&self) -> String {
  60. const HEX: [char; 16] = [
  61. '0',
  62. '1',
  63. '2',
  64. '3',
  65. '4',
  66. '5',
  67. '6',
  68. '7',
  69. '8',
  70. '9',
  71. 'a',
  72. 'b',
  73. 'c',
  74. 'd',
  75. 'e',
  76. 'f',
  77. ];
  78. let mut tmp = String::with_capacity(32 * 2);
  79. for byte in self.iter() {
  80. tmp.push(HEX[*byte as usize / 16]);
  81. tmp.push(HEX[*byte as usize % 16]);
  82. }
  83. tmp
  84. }
  85. fn size() -> usize {
  86. 32
  87. }
  88. }
  89. #[test]
  90. fn test_hash() {
  91. assert_eq!(
  92. Sha256::hash("test".as_bytes()).hex(),
  93. "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
  94. );
  95. }