Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mhgp
Created November 5, 2016 13:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhgp/53f56a5a5468dc94669e70c998e51098 to your computer and use it in GitHub Desktop.
Save mhgp/53f56a5a5468dc94669e70c998e51098 to your computer and use it in GitHub Desktop.
Rust で SHA-2 を実装してみた
use std::boxed::Box;
macro_rules! Ch {
($x:expr, $y:expr, $z:expr) => { ($x & $y) ^ (!$x & $z) };
}
macro_rules! Maj {
($x:expr, $y:expr, $z:expr) => { ($x & $y) ^ ($x & $z) ^ ($y & $z) };
}
/// SHA256追加定数
const K256: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];
/// SHA512追加定数
const K512: [u64; 80] = [
0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc,
0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118,
0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2,
0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694,
0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,
0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5,
0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4,
0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70,
0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df,
0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b,
0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30,
0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8,
0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8,
0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3,
0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,
0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b,
0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178,
0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b,
0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c,
0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817
];
fn large_sigma0_256(x: u32) -> u32 {
x.rotate_right( 2) ^ x.rotate_right(13) ^ x.rotate_right(22)
}
fn large_sigma1_256(x: u32) -> u32 {
x.rotate_right( 6) ^ x.rotate_right(11) ^ x.rotate_right(25)
}
fn sigma0_256(x: u32) -> u32 {
x.rotate_right( 7) ^ x.rotate_right(18) ^ (x >> 3)
}
fn sigma1_256(x: u32) -> u32 {
x.rotate_right(17) ^ x.rotate_right(19) ^ (x >> 10)
}
fn large_sigma0_512(x: u64) -> u64 {
x.rotate_right(28) ^ x.rotate_right(34) ^ x.rotate_right(39)
}
fn large_sigma1_512(x: u64) -> u64 {
x.rotate_right(14) ^ x.rotate_right(18) ^ x.rotate_right(41)
}
fn sigma0_512(x: u64) -> u64 {
x.rotate_right( 1) ^ x.rotate_right( 8) ^ (x >> 7)
}
fn sigma1_512(x: u64) -> u64 {
x.rotate_right(19) ^ x.rotate_right(61) ^ (x >> 6)
}
fn change_u32_to_array_u8(from: u32) -> [u8; 4] {
use std::mem::transmute;
unsafe { transmute::<u32, [u8; 4]>(from.to_be()) }
}
fn change_u64_to_array_u32(from: u64) -> [u32; 2] {
use std::mem::transmute;
unsafe { transmute::<u64, [u32; 2]>(from) }
}
fn change_u64_to_array_u8(from: u64) -> [u8; 8] {
use std::mem::transmute;
unsafe { transmute::<u64, [u8; 8]>(from.to_be()) }
}
macro_rules! add_msg_len {
($self_:expr, $upper:expr, $lower:expr) => ({
let (val, overflow) = $self_.lower.overflowing_add($lower);
if overflow {
let (val, overflow) = $self_.upper.overflowing_add(1);
if overflow {
return Result::Err(());
}
$self_.upper = val;
}
$self_.lower = val;
let (val, overflow) = $self_.upper.overflowing_add($upper);
if overflow {
Result::Err(())
} else {
$self_.upper = val;
Result::Ok(())
}
})
}
pub struct Length<T> {
upper: T,
lower: T
}
impl Length<u32> {
pub fn new(val: u32) -> Length<u32> {
Length {
upper: 0,
lower: val
}
}
fn add_msg_len(&mut self, oct: usize, rem: u8) -> Result<(), ()> {
if oct & (usize::max_value() << 61) > 0 {
return Result::Err(());
}
let arry = change_u64_to_array_u32(((oct as u64) << 3) + rem as u64);
add_msg_len!(self, arry[1], arry[0])
}
}
impl Length<u64> {
pub fn new(val: u64) -> Length<u64> {
Length {
upper: 0,
lower: val
}
}
fn add_msg_len(&mut self, oct: usize, rem: u8) -> Result<(), ()> {
/*
if oct & (usize::max_value() << 125) > 0 {
return Result::Err(());
}
*/
let arry = [((oct as u64) << 3) + rem as u64, oct as u64 >> 61];
add_msg_len!(self, arry[1], arry[0])
}
}
trait Sha2DataRunner {
fn update(&mut self, data: &[u8], rem: u8) -> Result<(), ()>;
fn finish(mut self: Box<Self>) -> Box<[u8]>;
}
struct Sha2Data<T> {
/// 入力データの一時溜め置き
buffer: [T; 16],
/// 溜め置いているデータの bit サイズ
buffer_size: u16,
/// 内部状態
state: [T; 8],
/// メッセージ全体の bit サイズ
msg_length: Length<T>,
/// ハッシュサイズ[bit]
length: u16,
}
type Sha256 = Sha2Data<u32>;
type Sha512 = Sha2Data<u64>;
type Sha256Length = Length<u32>;
type Sha512Length = Length<u64>;
enum Sha256DigestSize {
Len224 = 224,
Len256 = 256,
}
impl Sha256 {
fn new(digest: Sha256DigestSize) -> Sha256 {
let init_state = match digest {
Sha256DigestSize::Len224 => [
0xc1059ed8,
0x367cd507,
0x3070dd17,
0xf70e5939,
0xffc00b31,
0x68581511,
0x64f98fa7,
0xbefa4fa4
],
Sha256DigestSize::Len256 => [
0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19
]
};
Sha256 {
buffer: [0; 16],
buffer_size: 0,
state: init_state,
msg_length: Sha256Length::new(0),
length: digest as u16,
}
}
fn run(&mut self) {
let w = {
let mut w = [0; 64];
for t in 0..16 {
w[t] = self.buffer[t];
}
for t in 16..64 {
w[t] = sigma1_256(w[t-2]).wrapping_add(w[t-7])
.wrapping_add(sigma0_256(w[t-15]))
.wrapping_add(w[t-16]);
}
w
};
let (mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h) = (
self.state[0],
self.state[1],
self.state[2],
self.state[3],
self.state[4],
self.state[5],
self.state[6],
self.state[7]
);
for t in 0..64 {
let t1 = h.wrapping_add(large_sigma1_256(e))
.wrapping_add(Ch!(e, f, g))
.wrapping_add(K256[t])
.wrapping_add(w[t]);
let t2 = large_sigma0_256(a).wrapping_add(Maj!(a, b, c));
h = g;
g = f;
f = e;
e = d.wrapping_add(t1);
d = c;
c = b;
b = a;
a = t1.wrapping_add(t2);
}
self.state = [
a.wrapping_add(self.state[0]),
b.wrapping_add(self.state[1]),
c.wrapping_add(self.state[2]),
d.wrapping_add(self.state[3]),
e.wrapping_add(self.state[4]),
f.wrapping_add(self.state[5]),
g.wrapping_add(self.state[6]),
h.wrapping_add(self.state[7])
];
}
}
impl Sha2DataRunner for Sha256 {
fn update(&mut self, data: &[u8], rem: u8) -> Result<(), ()> {
debug_assert!(if data.len() == 0 { rem == 0 } else { rem > 0 && rem <= 8 });
let mut num = (self.buffer_size / 32) as usize;
let mut bit = (self.buffer_size % 32) as u32;
for i in 0..data.len() {
let add_data = if i < (data.len() - 1) {
bit += 8;
data[i] as u32
} else {
bit += rem as u32;
(data[i] & u8::max_value() << (8 - rem)) as u32
};
self.buffer[num] |= if bit <= 32 {
add_data << (32 - bit)
} else {
add_data >> (bit - 32)
};
if bit >= 32 {
num += 1;
bit -= 32;
if num >= 16 {
self.run();
self.buffer = [0; 16];
num = 0;
}
if bit > 0 {
self.buffer[num] |= add_data << (32 - bit);
}
}
}
self.buffer_size = (num as u32 * 32 + bit) as u16;
if rem == 0 || rem == 8 {
self.msg_length.add_msg_len(data.len(), 0)
} else {
self.msg_length.add_msg_len(data.len() - 1, rem)
}
}
fn finish(mut self: Box<Self>) -> Box<[u8]> {
// add padding
let idx = (self.buffer_size / 32) as usize;
let shift = 31 - self.buffer_size % 32;
self.buffer[idx] |= 0x1 << shift;
if idx >= 14 {
self.run();
self.buffer = [0; 16];
self.buffer_size = 0;
}
self.buffer[14] = self.msg_length.upper;
self.buffer[15] = self.msg_length.lower;
self.run();
// create hash
let mut result: Vec<u8> = Vec::with_capacity(self.length as usize / 8);
let mut length = 0;
'outer: for x in self.state.iter() {
let array = change_u32_to_array_u8(*x);
for byte in array.iter() {
result.push(*byte);
length += 8;
if length == self.length {
break 'outer;
}
}
}
result.into_boxed_slice()
}
}
enum Sha512DigestSize {
Len224 = 224,
Len256 = 256,
Len384 = 384,
Len512 = 512,
}
impl Sha512 {
pub fn new(digest: Sha512DigestSize) -> Sha512 {
let init_state = match digest {
Sha512DigestSize::Len384 => [
0xcbbb9d5dc1059ed8,
0x629a292a367cd507,
0x9159015a3070dd17,
0x152fecd8f70e5939,
0x67332667ffc00b31,
0x8eb44a8768581511,
0xdb0c2e0d64f98fa7,
0x47b5481dbefa4fa4
],
Sha512DigestSize::Len512 => [
0x6a09e667f3bcc908,
0xbb67ae8584caa73b,
0x3c6ef372fe94f82b,
0xa54ff53a5f1d36f1,
0x510e527fade682d1,
0x9b05688c2b3e6c1f,
0x1f83d9abfb41bd6b,
0x5be0cd19137e2179
],
Sha512DigestSize::Len224 => [
0x8c3d37c819544da2,
0x73e1996689dcd4d6,
0x1dfab7ae32ff9c82,
0x679dd514582f9fcf,
0x0f6d2b697bd44da8,
0x77e36f7304c48942,
0x3f9d85a86a1d36c8,
0x1112e6ad91d692a1
],
Sha512DigestSize::Len256 => [
0x22312194fc2bf72c,
0x9f555fa3c84c64c2,
0x2393b86b6f53b151,
0x963877195940eabd,
0x96283ee2a88effe3,
0xbe5e1e2553863992,
0x2b0199fc2c85b8aa,
0x0eb72ddc81c52ca2
]
};
Sha2Data {
buffer: [0; 16],
buffer_size: 0,
state: init_state,
msg_length: Sha512Length::new(0),
length: digest as u16,
}
}
fn run(&mut self) {
let w = {
let mut w = [0; 80];
for t in 0..16 {
w[t] = self.buffer[t];
}
for t in 16..80 {
w[t] = sigma1_512(w[t-2]).wrapping_add(w[t-7])
.wrapping_add(sigma0_512(w[t-15]))
.wrapping_add(w[t-16]);
}
w
};
let (mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h) = (
self.state[0],
self.state[1],
self.state[2],
self.state[3],
self.state[4],
self.state[5],
self.state[6],
self.state[7]
);
for t in 0..80 {
let t1 = h.wrapping_add(large_sigma1_512(e))
.wrapping_add(Ch!(e, f, g))
.wrapping_add(K512[t])
.wrapping_add(w[t]);
let t2 = large_sigma0_512(a).wrapping_add(Maj!(a, b, c));
h = g;
g = f;
f = e;
e = d.wrapping_add(t1);
d = c;
c = b;
b = a;
a = t1.wrapping_add(t2);
}
self.state = [
a.wrapping_add(self.state[0]),
b.wrapping_add(self.state[1]),
c.wrapping_add(self.state[2]),
d.wrapping_add(self.state[3]),
e.wrapping_add(self.state[4]),
f.wrapping_add(self.state[5]),
g.wrapping_add(self.state[6]),
h.wrapping_add(self.state[7])
];
}
}
impl Sha2DataRunner for Sha512 {
fn update(&mut self, data: &[u8], rem: u8) -> Result<(), ()> {
debug_assert!(if data.len() == 0 { rem == 0 } else { rem > 0 && rem <= 8 });
let mut num = (self.buffer_size / 64) as usize;
let mut bit = (self.buffer_size % 64) as u32;
for i in 0..data.len() {
let add_data = if i < (data.len() - 1) {
bit += 8;
data[i] as u64
} else {
bit += rem as u32;
(data[i] & u8::max_value() << (8 - rem)) as u64
};
self.buffer[num] |= if bit <= 64 {
add_data << (64 - bit)
} else {
add_data >> (bit - 64)
};
if bit >= 64 {
num += 1;
bit -= 64;
if num >= 16 {
self.run();
self.buffer = [0; 16];
num = 0;
}
if bit > 0 {
self.buffer[num] |= add_data << (64 - bit);
}
}
}
self.buffer_size = (num as u32 * 64 + bit) as u16;
if rem == 0 || rem == 8 {
self.msg_length.add_msg_len(data.len(), 0)
} else {
self.msg_length.add_msg_len(data.len() - 1, rem)
}
}
fn finish(mut self: Box<Self>) -> Box<[u8]> {
// add padding
let idx = (self.buffer_size / 64) as usize;
let shift = 63 - self.buffer_size % 64;
self.buffer[idx] |= 0x1 << shift;
if idx >= 14 {
self.run();
self.buffer = [0; 16];
self.buffer_size = 0;
}
self.buffer[14] = self.msg_length.upper;
self.buffer[15] = self.msg_length.lower;
self.run();
// create hash
let mut result: Vec<u8> = Vec::with_capacity(self.length as usize / 8);
let mut length = 0;
'outer: for x in self.state.iter() {
let array = change_u64_to_array_u8(*x);
for byte in array.iter() {
result.push(*byte);
length += 8;
if length == self.length {
break 'outer;
}
}
}
result.into_boxed_slice()
}
}
pub enum Sha2HashType {
/// SHA 224
Len224,
/// SHA 256
Len256,
/// SHA 384
Len384,
/// SHA 512
Len512,
/// SHA 512/224
Len224By512,
/// SHA 512/256
Len256By512
}
pub struct Sha2 {
data: Box<Sha2DataRunner>
}
impl Sha2 {
pub fn new(hash_type: Sha2HashType) -> Self {
let data: Box<Sha2DataRunner> = match hash_type {
Sha2HashType::Len224 => Box::new(Sha256::new(
Sha256DigestSize::Len224
)),
Sha2HashType::Len256 => Box::new(Sha256::new(
Sha256DigestSize::Len256
)),
Sha2HashType::Len384 => Box::new(Sha512::new(
Sha512DigestSize::Len384
)),
Sha2HashType::Len512 => Box::new(Sha512::new(
Sha512DigestSize::Len512
)),
Sha2HashType::Len224By512 => Box::new(Sha512::new(
Sha512DigestSize::Len224
)),
Sha2HashType::Len256By512 => Box::new(Sha512::new(
Sha512DigestSize::Len256
))
};
Sha2 {
data: data
}
}
pub fn push(&mut self, data: &[u8], rem: u8) -> Result<(), ()> {
self.data.update(data, rem)
}
pub fn finish(self) -> Box<[u8]> {
self.data.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
/// 空のメッセージ "" に対し SHA-224 を取る
#[test]
fn sha2_224_hash_by_empty_msg() {
let sha2 = Sha2::new(Sha2HashType::Len224);
let hash = sha2.finish();
assert_eq!(hash, vec![
0xd1, 0x4a, 0x02, 0x8c, 0x2a, 0x3a, 0x2b, 0xc9,
0x47, 0x61, 0x02, 0xbb, 0x28, 0x82, 0x34, 0xc4,
0x15, 0xa2, 0xb0, 0x1f, 0x82, 0x8e, 0xa6, 0x2a,
0xc5, 0xb3, 0xe4, 0x2f
].into_boxed_slice());
}
/// メッセージ "abc" に対し SHA-224 を取る
#[test]
fn sha2_224_hash_by_abc_msg() {
let mut sha2 = Sha2::new(Sha2HashType::Len224);
sha2.push(b"abc".as_ref(), 8).unwrap();
let hash = sha2.finish();
assert_eq!(hash, vec![
0x23, 0x09, 0x7d, 0x22, 0x34, 0x05, 0xd8, 0x22,
0x86, 0x42, 0xa4, 0x77, 0xbd, 0xa2, 0x55, 0xb3,
0x2a, 0xad, 0xbc, 0xe4, 0xbd, 0xa0, 0xb3, 0xf7,
0xe3, 0x6c, 0x9d, 0xa7
].into_boxed_slice());
}
/// 空のメッセージ "" に対し SHA-256 を取る
#[test]
fn sha2_256_hash_by_empty_msg() {
let sha2 = Sha2::new(Sha2HashType::Len256);
let hash = sha2.finish();
assert_eq!(hash, vec![
0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14,
0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24,
0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c,
0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55
].into_boxed_slice());
}
/// メッセージ "abc" に対し SHA-256 を取る
#[test]
fn sha2_256_hash_by_abc_msg() {
let mut sha2 = Sha2::new(Sha2HashType::Len256);
sha2.push(b"abc".as_ref(), 8).unwrap();
let hash = sha2.finish();
assert_eq!(hash, vec![
0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea,
0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,
0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c,
0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad
].into_boxed_slice());
}
/// 447 bits の 0 で構成されたメッセージに対し SHA-256 を取る
#[test]
fn sha2_256_hash_by_447_zero_bits() {
let mut sha2 = Sha2::new(Sha2HashType::Len256);
sha2.push(&vec![
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
], 7).unwrap();
let hash = sha2.finish();
assert_eq!(hash, vec![
0x43, 0xfd, 0xd2, 0xee, 0xd4, 0xdf, 0x6d, 0x2c,
0x38, 0xe9, 0x71, 0xda, 0x88, 0x41, 0x15, 0x05,
0x19, 0x51, 0xaa, 0x68, 0xd8, 0x92, 0x72, 0x0f,
0x79, 0x68, 0x9d, 0x49, 0x62, 0xc9, 0xef, 0xae
].into_boxed_slice());
}
/// 448 bits の 0 で構成されたメッセージに対し SHA-256 を取る
#[test]
fn sha2_256_hash_by_448_zero_bits() {
let mut sha2 = Sha2::new(Sha2HashType::Len256);
sha2.push(&vec![
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
], 8).unwrap();
let hash = sha2.finish();
assert_eq!(hash, vec![
0xd4, 0x81, 0x7a, 0xa5, 0x49, 0x76, 0x28, 0xe7,
0xc7, 0x7e, 0x6b, 0x60, 0x61, 0x07, 0x04, 0x2b,
0xbb, 0xa3, 0x13, 0x08, 0x88, 0xc5, 0xf4, 0x7a,
0x37, 0x5e, 0x61, 0x79, 0xbe, 0x78, 0x9f, 0xbb
].into_boxed_slice());
}
/// 448 bits の 0 で構成されたメッセージに対し SHA-256 を取る
#[test]
fn sha2_256_hash_by_448_bits_ascii_msg() {
let mut sha2 = Sha2::new(Sha2HashType::Len256);
sha2.push(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".as_ref(), 8).unwrap();
let hash = sha2.finish();
assert_eq!(hash, vec![
0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8,
0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39,
0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67,
0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1
].into_boxed_slice());
}
/// 空のメッセージ "" に対し SHA521/224 を取る
#[test]
fn sha2_224_by_512_hash_by_empty_msg() {
let sha2 = Sha2::new(Sha2HashType::Len224By512);
let hash = sha2.finish();
assert_eq!(hash, vec![
0x6e, 0xd0, 0xdd, 0x02, 0x80, 0x6f, 0xa8, 0x9e,
0x25, 0xde, 0x06, 0x0c, 0x19, 0xd3, 0xac, 0x86,
0xca, 0xbb, 0x87, 0xd6, 0xa0, 0xdd, 0xd0, 0x5c,
0x33, 0x3b, 0x84, 0xf4
].into_boxed_slice());
}
/// 空のメッセージ "" に対し SHA521/256 を取る
#[test]
fn sha2_256_by_512_hash_by_empty_msg() {
let sha2 = Sha2::new(Sha2HashType::Len256By512);
let hash = sha2.finish();
assert_eq!(hash, vec![
0xc6, 0x72, 0xb8, 0xd1, 0xef, 0x56, 0xed, 0x28,
0xab, 0x87, 0xc3, 0x62, 0x2c, 0x51, 0x14, 0x06,
0x9b, 0xdd, 0x3a, 0xd7, 0xb8, 0xf9, 0x73, 0x74,
0x98, 0xd0, 0xc0, 0x1e, 0xce, 0xf0, 0x96, 0x7a
].into_boxed_slice());
}
/// 空のメッセージ "" に対し SHA384 を取る
#[test]
fn sha2_384_hash_by_empty_msg() {
let sha2 = Sha2::new(Sha2HashType::Len384);
let hash = sha2.finish();
assert_eq!(hash, vec![
0x38, 0xb0, 0x60, 0xa7, 0x51, 0xac, 0x96, 0x38,
0x4c, 0xd9, 0x32, 0x7e, 0xb1, 0xb1, 0xe3, 0x6a,
0x21, 0xfd, 0xb7, 0x11, 0x14, 0xbe, 0x07, 0x43,
0x4c, 0x0c, 0xc7, 0xbf, 0x63, 0xf6, 0xe1, 0xda,
0x27, 0x4e, 0xde, 0xbf, 0xe7, 0x6f, 0x65, 0xfb,
0xd5, 0x1a, 0xd2, 0xf1, 0x48, 0x98, 0xb9, 0x5b
].into_boxed_slice());
}
/// メッセージ "abc" に対し SHA384 を取る
#[test]
fn sha2_384_hash_by_abc_msg() {
let mut sha2 = Sha2::new(Sha2HashType::Len384);
sha2.push(b"abc".as_ref(), 8).unwrap();
let hash = sha2.finish();
assert_eq!(hash, vec![
0xcb, 0x00, 0x75, 0x3f, 0x45, 0xa3, 0x5e, 0x8b,
0xb5, 0xa0, 0x3d, 0x69, 0x9a, 0xc6, 0x50, 0x07,
0x27, 0x2c, 0x32, 0xab, 0x0e, 0xde, 0xd1, 0x63,
0x1a, 0x8b, 0x60, 0x5a, 0x43, 0xff, 0x5b, 0xed,
0x80, 0x86, 0x07, 0x2b, 0xa1, 0xe7, 0xcc, 0x23,
0x58, 0xba, 0xec, 0xa1, 0x34, 0xc8, 0x25, 0xa7
].into_boxed_slice());
}
/// 空のメッセージ "" に対し SHA512 を取る
#[test]
fn sha2_512_hash_by_empty_msg() {
let sha2 = Sha2::new(Sha2HashType::Len512);
let hash = sha2.finish();
assert_eq!(hash, vec![
0xcf, 0x83, 0xe1, 0x35, 0x7e, 0xef, 0xb8, 0xbd,
0xf1, 0x54, 0x28, 0x50, 0xd6, 0x6d, 0x80, 0x07,
0xd6, 0x20, 0xe4, 0x05, 0x0b, 0x57, 0x15, 0xdc,
0x83, 0xf4, 0xa9, 0x21, 0xd3, 0x6c, 0xe9, 0xce,
0x47, 0xd0, 0xd1, 0x3c, 0x5d, 0x85, 0xf2, 0xb0,
0xff, 0x83, 0x18, 0xd2, 0x87, 0x7e, 0xec, 0x2f,
0x63, 0xb9, 0x31, 0xbd, 0x47, 0x41, 0x7a, 0x81,
0xa5, 0x38, 0x32, 0x7a, 0xf9, 0x27, 0xda, 0x3e
].into_boxed_slice());
}
/// メッセージ "abc" に対し SHA512 を取る
#[test]
fn sha2_512_hash_by_abc_msg() {
let mut sha2 = Sha2::new(Sha2HashType::Len512);
sha2.push(b"abc".as_ref(), 8).unwrap();
let hash = sha2.finish();
assert_eq!(hash, vec![
0xdd, 0xaf, 0x35, 0xa1, 0x93, 0x61, 0x7a, 0xba,
0xcc, 0x41, 0x73, 0x49, 0xae, 0x20, 0x41, 0x31,
0x12, 0xe6, 0xfa, 0x4e, 0x89, 0xa9, 0x7e, 0xa2,
0x0a, 0x9e, 0xee, 0xe6, 0x4b, 0x55, 0xd3, 0x9a,
0x21, 0x92, 0x99, 0x2a, 0x27, 0x4f, 0xc1, 0xa8,
0x36, 0xba, 0x3c, 0x23, 0xa3, 0xfe, 0xeb, 0xbd,
0x45, 0x4d, 0x44, 0x23, 0x64, 0x3c, 0xe8, 0x0e,
0x2a, 0x9a, 0xc9, 0x4f, 0xa5, 0x4c, 0xa4, 0x9f
].into_boxed_slice());
}
/// 895 bit の 0 で構成されたメッセージに対し SHA512 を取る(境界テスト)
#[test]
fn sha2_512_hash_by_895_zero_bits() {
let mut sha2 = Sha2::new(Sha2HashType::Len512);
sha2.push(&vec![
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
], 7).unwrap();
let hash = sha2.finish();
assert_eq!(hash, vec![
0x12, 0xdd, 0x83, 0xc5, 0xb6, 0x54, 0x77, 0x58,
0x45, 0x2d, 0xc7, 0x02, 0x0e, 0xe3, 0x2f, 0x53,
0xf5, 0xa0, 0xeb, 0x65, 0xd3, 0x3c, 0x4d, 0x3f,
0xee, 0xbc, 0xe1, 0x7d, 0x71, 0x13, 0xdb, 0x14,
0x03, 0x93, 0xc8, 0xfb, 0xe4, 0x9f, 0xc0, 0x71,
0xe4, 0x0b, 0x58, 0x5d, 0xf9, 0x69, 0xc7, 0xaa,
0x3a, 0x81, 0x96, 0xce, 0x2b, 0x94, 0xe8, 0x3e,
0x79, 0x41, 0xec, 0x05, 0xe2, 0x01, 0x87, 0x51
].into_boxed_slice());
}
/// 896 bit の 0 で構成されたメッセージに対し SHA512 を取る(境界テスト)
#[test]
fn sha2_512_hash_by_896_zero_bits() {
let mut sha2 = Sha2::new(Sha2HashType::Len512);
sha2.push(&vec![
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
], 8).unwrap();
let hash = sha2.finish();
assert_eq!(hash, vec![
0x2b, 0xe2, 0xe7, 0x88, 0xc8, 0xa8, 0xad, 0xea,
0xa9, 0xc8, 0x9a, 0x7f, 0x78, 0x90, 0x4c, 0xac,
0xea, 0x6e, 0x39, 0x29, 0x7d, 0x75, 0xe0, 0x57,
0x3a, 0x73, 0xc7, 0x56, 0x23, 0x45, 0x34, 0xd6,
0x62, 0x7a, 0xb4, 0x15, 0x6b, 0x48, 0xa6, 0x65,
0x7b, 0x29, 0xab, 0x8b, 0xeb, 0x73, 0x33, 0x40,
0x40, 0xad, 0x39, 0xea, 0xd8, 0x14, 0x46, 0xbb,
0x09, 0xc7, 0x07, 0x04, 0xec, 0x70, 0x79, 0x52
].into_boxed_slice());
}
/// 896 bit の 0 で構成されたメッセージに対し SHA512 を取る(境界テスト)
#[test]
fn sha2_512_hash_by_896_bits_ascii_msg() {
let mut sha2 = Sha2::new(Sha2HashType::Len512);
sha2.push(b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu".as_ref(), 8).unwrap();
let hash = sha2.finish();
assert_eq!(hash, vec![
0x8e, 0x95, 0x9b, 0x75, 0xda, 0xe3, 0x13, 0xda,
0x8c, 0xf4, 0xf7, 0x28, 0x14, 0xfc, 0x14, 0x3f,
0x8f, 0x77, 0x79, 0xc6, 0xeb, 0x9f, 0x7f, 0xa1,
0x72, 0x99, 0xae, 0xad, 0xb6, 0x88, 0x90, 0x18,
0x50, 0x1d, 0x28, 0x9e, 0x49, 0x00, 0xf7, 0xe4,
0x33, 0x1b, 0x99, 0xde, 0xc4, 0xb5, 0x43, 0x3a,
0xc7, 0xd3, 0x29, 0xee, 0xb6, 0xdd, 0x26, 0x54,
0x5e, 0x96, 0xe5, 0x5b, 0x87, 0x4b, 0xe9, 0x09
].into_boxed_slice());
}
}
macro_rules! Ch {
($x:expr, $y:expr, $z:expr) => { ($x & $y) ^ (!$x & $z) };
}
macro_rules! Maj {
($x:expr, $y:expr, $z:expr) => { ($x & $y) ^ ($x & $z) ^ ($y & $z) };
}
/// 追加定数
const K256: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];
fn large_sigma0_256(x: u32) -> u32 {
x.rotate_right( 2) ^ x.rotate_right(13) ^ x.rotate_right(22)
}
fn large_sigma1_256(x: u32) -> u32 {
x.rotate_right( 6) ^ x.rotate_right(11) ^ x.rotate_right(25)
}
fn sigma0_256(x: u32) -> u32 {
x.rotate_right( 7) ^ x.rotate_right(18) ^ (x >> 3)
}
fn sigma1_256(x: u32) -> u32 {
x.rotate_right(17) ^ x.rotate_right(19) ^ (x >> 10)
}
/// 圧縮関数
fn round(state: [u32; 8], block: [u32; 16]) -> [u32; 8] {
let w = {
let mut w = [0; 64];
for t in 0..16 {
w[t] = block[t];
}
for t in 16..64 {
w[t] = sigma1_256(w[t-2]).wrapping_add(w[t-7])
.wrapping_add(sigma0_256(w[t-15]))
.wrapping_add(w[t-16]);
}
w
};
let (mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h) = (
state[0],
state[1],
state[2],
state[3],
state[4],
state[5],
state[6],
state[7]
);
for t in 0..64 {
let t1 = h.wrapping_add(large_sigma1_256(e))
.wrapping_add(Ch!(e, f, g))
.wrapping_add(K256[t])
.wrapping_add(w[t]);
let t2 = large_sigma0_256(a).wrapping_add(Maj!(a, b, c));
h = g;
g = f;
f = e;
e = d.wrapping_add(t1);
d = c;
c = b;
b = a;
a = t1.wrapping_add(t2);
}
[
a.wrapping_add(state[0]),
b.wrapping_add(state[1]),
c.wrapping_add(state[2]),
d.wrapping_add(state[3]),
e.wrapping_add(state[4]),
f.wrapping_add(state[5]),
g.wrapping_add(state[6]),
h.wrapping_add(state[7])
]
}
/// パディングを加えたデータをブロックに分割する。
fn separate_data(data: Vec<u8>) -> Vec<[u32; 16]> {
let mut blocks = Vec::with_capacity(data.len() / 512);
let mut idx = 0;
let mut shift = 32;
let mut block = [0; 16];
for byte in data.iter() {
shift -= 8;
block[idx] |= (*byte as u32) << shift;
if shift == 0 {
idx += 1;
shift = 32;
}
if idx == 16 {
blocks.push(block);
block = [0; 16];
idx = 0;
}
}
blocks
}
/// メッセージにパディングを追加する。
fn add_padding(message: &Vec<u8>, length: u64) -> Vec<u8> {
let data_len = ((length / 512) * 64 + if (length % 512) <= 447 { 64 } else { 128 }) as usize;
let mut data: Vec<u8> = Vec::with_capacity(data_len);
// copy message
for byte in message.iter() {
data.push(*byte);
}
// add padding
if length % 8 == 0 {
data.push(0x80);
} else {
let len = data.len();
data[len - 1] |= 1 << (7 - length % 8) as u32;
}
for _ in 0..(data_len - data.len() - 8) {
data.push(0x00);
}
for i in 0..8 {
data.push((length >> (56 - i * 8) as u32) as u8);
}
data
}
/// ハッシュ長
pub enum Sha256DigestSize {
Len224 = 224,
Len256 = 256,
}
/// メッセージ(データが length 分存在することを保証する)
pub struct Message {
data: Vec<u8>,
length: u64
}
impl Message {
pub fn new(input: &[u8], length: u64) -> Message {
let mut data = Vec::with_capacity((length / 8) as usize);
let mut data_length = 0;
for byte in input.iter() {
if data_length >= length {
let data_vec_last_idx = data.len() - 1;
data[data_vec_last_idx] &= 0xff << (data_length - length) as u32;
break;
}
data.push(*byte);
data_length += 8;
}
if data_length < length {
for _ in 0..((length - data_length) / 8) {
data.push(0x00);
}
if (length - data_length) % 8 != 0 {
data.push(0x00);
}
}
Message {
data: data,
length: length
}
}
/// メッセージの取得
fn get_message_vec(&self) -> &Vec<u8> {
&self.data
}
/// メッセージ長 [bit] の取得
fn get_message_len(&self) -> u64 {
self.length
}
}
/// ハッシュの取得
pub fn create_hash(message: Message, digest_size: Sha256DigestSize) -> Box<[u8]> {
// パディングの追加
let data = add_padding(message.get_message_vec(), message.get_message_len());
// データをブロックに分割
let blocks = separate_data(data);
// 初期値
let mut state = match digest_size {
Sha256DigestSize::Len224 => [
0xc1059ed8,
0x367cd507,
0x3070dd17,
0xf70e5939,
0xffc00b31,
0x68581511,
0x64f98fa7,
0xbefa4fa4
],
Sha256DigestSize::Len256 => [
0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19
],
};
// ブロックを圧縮関数に代入
for block in blocks.iter() {
state = round(state, *block);
}
// ハッシュの作成
let hash_length = digest_size as usize;
let mut hash: Vec<u8> = Vec::with_capacity(hash_length);
let mut length = 0;
'outer: for h in state.iter() {
use std::mem::transmute;
let from = if cfg!(target_endian = "big") {
*h
} else {
(*h).swap_bytes()
};
for byte in unsafe { transmute::<u32, [u8; 4]>(from) }.iter() {
hash.push(*byte);
length += 8;
if length == hash_length as usize {
break 'outer;
}
}
}
// 戻り値
hash.into_boxed_slice()
}
#[cfg(test)]
mod tests {
use super::*;
/// 空のメッセージ "" に対し SHA-224 を取る
#[test]
fn sha2_224_hash_by_empty_msg() {
let msg = Message::new(&vec![], 0);
let hash = create_hash(msg, Sha256DigestSize::Len224);
assert_eq!(hash, vec![
0xd1, 0x4a, 0x02, 0x8c, 0x2a, 0x3a, 0x2b, 0xc9,
0x47, 0x61, 0x02, 0xbb, 0x28, 0x82, 0x34, 0xc4,
0x15, 0xa2, 0xb0, 0x1f, 0x82, 0x8e, 0xa6, 0x2a,
0xc5, 0xb3, 0xe4, 0x2f
].into_boxed_slice());
}
/// メッセージ "abc" に対し SHA-224 を取る
#[test]
fn sha2_224_hash_by_abc_msg() {
let msg = Message::new(b"abc".as_ref(), 24);
let hash = create_hash(msg, Sha256DigestSize::Len224);
assert_eq!(hash, vec![
0x23, 0x09, 0x7d, 0x22, 0x34, 0x05, 0xd8, 0x22,
0x86, 0x42, 0xa4, 0x77, 0xbd, 0xa2, 0x55, 0xb3,
0x2a, 0xad, 0xbc, 0xe4, 0xbd, 0xa0, 0xb3, 0xf7,
0xe3, 0x6c, 0x9d, 0xa7
].into_boxed_slice());
}
/// 空のメッセージ "" に対し SHA-256 を取る
#[test]
fn sha2_256_hash_by_empty_msg() {
let msg = Message::new(&vec![], 0);
let hash = create_hash(msg, Sha256DigestSize::Len256);
assert_eq!(hash, vec![
0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14,
0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24,
0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c,
0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55
].into_boxed_slice());
}
/// メッセージ "abc" に対し SHA-256 を取る
#[test]
fn sha2_256_hash_by_abc_msg() {
let msg = Message::new(b"abc".as_ref(), 24);
let hash = create_hash(msg, Sha256DigestSize::Len256);
assert_eq!(hash, vec![
0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea,
0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,
0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c,
0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad
].into_boxed_slice());
}
/// 447 bits の 0 で構成されたメッセージに対し SHA-256 を取る
#[test]
fn sha2_256_hash_by_447_zero_bits() {
let msg = Message::new(&vec![
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
], 447);
let hash = create_hash(msg, Sha256DigestSize::Len256);
assert_eq!(hash, vec![
0x43, 0xfd, 0xd2, 0xee, 0xd4, 0xdf, 0x6d, 0x2c,
0x38, 0xe9, 0x71, 0xda, 0x88, 0x41, 0x15, 0x05,
0x19, 0x51, 0xaa, 0x68, 0xd8, 0x92, 0x72, 0x0f,
0x79, 0x68, 0x9d, 0x49, 0x62, 0xc9, 0xef, 0xae
].into_boxed_slice());
}
/// 448 bits の 0 で構成されたメッセージに対し SHA-256 を取る
#[test]
fn sha2_256_hash_by_448_zero_bits() {
let msg = Message::new(&vec![
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
], 448);
let hash = create_hash(msg, Sha256DigestSize::Len256);
assert_eq!(hash, vec![
0xd4, 0x81, 0x7a, 0xa5, 0x49, 0x76, 0x28, 0xe7,
0xc7, 0x7e, 0x6b, 0x60, 0x61, 0x07, 0x04, 0x2b,
0xbb, 0xa3, 0x13, 0x08, 0x88, 0xc5, 0xf4, 0x7a,
0x37, 0x5e, 0x61, 0x79, 0xbe, 0x78, 0x9f, 0xbb
].into_boxed_slice());
}
}
macro_rules! Ch {
($x:expr, $y:expr, $z:expr) => { ($x & $y) ^ (!$x & $z) };
}
macro_rules! Maj {
($x:expr, $y:expr, $z:expr) => { ($x & $y) ^ ($x & $z) ^ ($y & $z) };
}
/// 追加定数
const K512: [u64; 80] = [
0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc,
0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118,
0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2,
0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694,
0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,
0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5,
0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4,
0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70,
0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df,
0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b,
0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30,
0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8,
0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8,
0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3,
0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,
0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b,
0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178,
0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b,
0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c,
0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817
];
fn large_sigma0_512(x: u64) -> u64 {
x.rotate_right(28) ^ x.rotate_right(34) ^ x.rotate_right(39)
}
fn large_sigma1_512(x: u64) -> u64 {
x.rotate_right(14) ^ x.rotate_right(18) ^ x.rotate_right(41)
}
fn sigma0_512(x: u64) -> u64 {
x.rotate_right( 1) ^ x.rotate_right( 8) ^ (x >> 7)
}
fn sigma1_512(x: u64) -> u64 {
x.rotate_right(19) ^ x.rotate_right(61) ^ (x >> 6)
}
/// 圧縮関数
fn round(state: [u64; 8], block: [u64; 16]) -> [u64; 8] {
let w = {
let mut w = [0; 80];
for t in 0..16 {
w[t] = block[t];
}
for t in 16..80 {
w[t] = sigma1_512(w[t-2]).wrapping_add(w[t-7])
.wrapping_add(sigma0_512(w[t-15]))
.wrapping_add(w[t-16]);
}
w
};
let (mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h) = (
state[0],
state[1],
state[2],
state[3],
state[4],
state[5],
state[6],
state[7]
);
for t in 0..80 {
let t1 = h.wrapping_add(large_sigma1_512(e))
.wrapping_add(Ch!(e, f, g))
.wrapping_add(K512[t])
.wrapping_add(w[t]);
let t2 = large_sigma0_512(a).wrapping_add(Maj!(a, b, c));
h = g;
g = f;
f = e;
e = d.wrapping_add(t1);
d = c;
c = b;
b = a;
a = t1.wrapping_add(t2);
}
[
a.wrapping_add(state[0]),
b.wrapping_add(state[1]),
c.wrapping_add(state[2]),
d.wrapping_add(state[3]),
e.wrapping_add(state[4]),
f.wrapping_add(state[5]),
g.wrapping_add(state[6]),
h.wrapping_add(state[7])
]
}
/// パディングを加えたデータをブロックに分割する。
fn separate_data(data: Vec<u8>) -> Vec<[u64; 16]> {
let mut blocks = Vec::with_capacity(data.len() / 128);
let mut idx = 0;
let mut shift = 64;
let mut block = [0; 16];
for byte in data.iter() {
shift -= 8;
block[idx] |= (*byte as u64) << shift;
if shift == 0 {
idx += 1;
shift = 64;
}
if idx == 16 {
blocks.push(block);
block = [0; 16];
idx = 0;
}
}
blocks
}
pub struct Length {
uppper: u64,
lower: u64
}
impl Length {
pub fn new(val: u64) -> Length {
Length {
uppper: 0,
lower: val
}
}
fn get_data_length(&self) -> usize {
((self.lower / 1024) * 128 + if (self.lower % 1024) <= 895 { 128 } else { 256 }) as usize
}
fn seek_remainder_octet(&self) -> usize {
// self % 8
(self.lower & 0b111) as usize
}
fn get_octet_vec(&self) -> Vec<u8> {
let mut vec: Vec<u8> = Vec::with_capacity(16);
for j in 0..8 {
vec.push((self.uppper >> (56 - j * 8) as u32) as u8);
}
for j in 0..8 {
vec.push((self.lower >> (56 - j * 8) as u32) as u8);
}
vec
}
}
/// メッセージにパディングを追加する。
fn add_padding(message: &Vec<u8>, length: Length) -> Vec<u8> {
let data_len = length.get_data_length();
let mut data: Vec<u8> = Vec::with_capacity(data_len);
// copy message
for byte in message.iter() {
data.push(*byte);
}
// add padding
if length.seek_remainder_octet() == 0 {
data.push(0x80);
} else {
let len = data.len();
data[len - 1] |= 1 << (7 - length.seek_remainder_octet()) as u32;
}
for _ in 0..(data_len - data.len() - 16) {
data.push(0x00);
}
for byte in length.get_octet_vec().iter() {
data.push(*byte);
}
data
}
/// ハッシュ長
pub enum Sha521DigestSize {
Len224 = 224,
Len256 = 256,
Len384 = 384,
Len512 = 512,
}
/// ハッシュの取得。message にメッセージを代入し、 message_length にメッセージ長を代入する。
pub fn create_hash(message: &Vec<u8>, message_length: Length, digest_size: Sha521DigestSize) -> Box<[u8]> {
// パディングの追加
let data = add_padding(message, message_length);
// データをブロックに分割
let blocks = separate_data(data);
// 初期値
let mut state = match digest_size {
Sha521DigestSize::Len224 => [
0x8c3d37c819544da2,
0x73e1996689dcd4d6,
0x1dfab7ae32ff9c82,
0x679dd514582f9fcf,
0x0f6d2b697bd44da8,
0x77e36f7304c48942,
0x3f9d85a86a1d36c8,
0x1112e6ad91d692a1
],
Sha521DigestSize::Len256 => [
0x22312194fc2bf72c,
0x9f555fa3c84c64c2,
0x2393b86b6f53b151,
0x963877195940eabd,
0x96283ee2a88effe3,
0xbe5e1e2553863992,
0x2b0199fc2c85b8aa,
0x0eb72ddc81c52ca2
],
Sha521DigestSize::Len384 => [
0xcbbb9d5dc1059ed8,
0x629a292a367cd507,
0x9159015a3070dd17,
0x152fecd8f70e5939,
0x67332667ffc00b31,
0x8eb44a8768581511,
0xdb0c2e0d64f98fa7,
0x47b5481dbefa4fa4
],
Sha521DigestSize::Len512 => [
0x6a09e667f3bcc908,
0xbb67ae8584caa73b,
0x3c6ef372fe94f82b,
0xa54ff53a5f1d36f1,
0x510e527fade682d1,
0x9b05688c2b3e6c1f,
0x1f83d9abfb41bd6b,
0x5be0cd19137e2179
],
};
// ブロックを圧縮関数に代入
for block in blocks.iter() {
state = round(state, *block);
}
// ハッシュの作成
let hash_length = digest_size as usize;
let mut hash: Vec<u8> = Vec::with_capacity(hash_length);
let mut length = 0;
'outer: for h in state.iter() {
use std::mem::transmute;
let from = if cfg!(target_endian = "big") {
*h
} else {
(*h).swap_bytes()
};
for byte in unsafe { transmute::<u64, [u8; 8]>(from) }.iter() {
hash.push(*byte);
length += 8;
if length == hash_length as usize {
break 'outer;
}
}
}
// 戻り値
hash.into_boxed_slice()
}
#[cfg(test)]
mod tests {
use super::*;
/// 空のメッセージ "" に対し SHA521/224 を取る
#[test]
fn sha2_224_by_512_hash_by_empty_msg() {
let hash = create_hash(&vec![], Length::new(0), Sha521DigestSize::Len224);
assert_eq!(hash, vec![
0x6e, 0xd0, 0xdd, 0x02, 0x80, 0x6f, 0xa8, 0x9e,
0x25, 0xde, 0x06, 0x0c, 0x19, 0xd3, 0xac, 0x86,
0xca, 0xbb, 0x87, 0xd6, 0xa0, 0xdd, 0xd0, 0x5c,
0x33, 0x3b, 0x84, 0xf4
].into_boxed_slice());
}
/// 空のメッセージ "" に対し SHA521/256 を取る
#[test]
fn sha2_256_by_512_hash_by_empty_msg() {
let hash = create_hash(&vec![], Length::new(0), Sha521DigestSize::Len256);
assert_eq!(hash, vec![
0xc6, 0x72, 0xb8, 0xd1, 0xef, 0x56, 0xed, 0x28,
0xab, 0x87, 0xc3, 0x62, 0x2c, 0x51, 0x14, 0x06,
0x9b, 0xdd, 0x3a, 0xd7, 0xb8, 0xf9, 0x73, 0x74,
0x98, 0xd0, 0xc0, 0x1e, 0xce, 0xf0, 0x96, 0x7a
].into_boxed_slice());
}
/// 空のメッセージ "" に対し SHA384 を取る
#[test]
fn sha2_384_hash_by_empty_msg() {
let hash = create_hash(&vec![], Length::new(0), Sha521DigestSize::Len384);
assert_eq!(hash, vec![
0x38, 0xb0, 0x60, 0xa7, 0x51, 0xac, 0x96, 0x38,
0x4c, 0xd9, 0x32, 0x7e, 0xb1, 0xb1, 0xe3, 0x6a,
0x21, 0xfd, 0xb7, 0x11, 0x14, 0xbe, 0x07, 0x43,
0x4c, 0x0c, 0xc7, 0xbf, 0x63, 0xf6, 0xe1, 0xda,
0x27, 0x4e, 0xde, 0xbf, 0xe7, 0x6f, 0x65, 0xfb,
0xd5, 0x1a, 0xd2, 0xf1, 0x48, 0x98, 0xb9, 0x5b
].into_boxed_slice());
}
/// メッセージ "abc" に対し SHA384 を取る
#[test]
fn sha2_384_hash_by_abc_msg() {
let hash = create_hash(&vec![b'a', b'b', b'c'], Length::new(24), Sha521DigestSize::Len384);
assert_eq!(hash, vec![
0xcb, 0x00, 0x75, 0x3f, 0x45, 0xa3, 0x5e, 0x8b,
0xb5, 0xa0, 0x3d, 0x69, 0x9a, 0xc6, 0x50, 0x07,
0x27, 0x2c, 0x32, 0xab, 0x0e, 0xde, 0xd1, 0x63,
0x1a, 0x8b, 0x60, 0x5a, 0x43, 0xff, 0x5b, 0xed,
0x80, 0x86, 0x07, 0x2b, 0xa1, 0xe7, 0xcc, 0x23,
0x58, 0xba, 0xec, 0xa1, 0x34, 0xc8, 0x25, 0xa7
].into_boxed_slice());
}
/// 空のメッセージ "" に対し SHA512 を取る
#[test]
fn sha2_512_hash_by_empty_msg() {
let hash = create_hash(&vec![], Length::new(0), Sha521DigestSize::Len512);
assert_eq!(hash, vec![
0xcf, 0x83, 0xe1, 0x35, 0x7e, 0xef, 0xb8, 0xbd,
0xf1, 0x54, 0x28, 0x50, 0xd6, 0x6d, 0x80, 0x07,
0xd6, 0x20, 0xe4, 0x05, 0x0b, 0x57, 0x15, 0xdc,
0x83, 0xf4, 0xa9, 0x21, 0xd3, 0x6c, 0xe9, 0xce,
0x47, 0xd0, 0xd1, 0x3c, 0x5d, 0x85, 0xf2, 0xb0,
0xff, 0x83, 0x18, 0xd2, 0x87, 0x7e, 0xec, 0x2f,
0x63, 0xb9, 0x31, 0xbd, 0x47, 0x41, 0x7a, 0x81,
0xa5, 0x38, 0x32, 0x7a, 0xf9, 0x27, 0xda, 0x3e
].into_boxed_slice());
}
/// メッセージ "abc" に対し SHA512 を取る
#[test]
fn sha2_512_hash_by_abc_msg() {
let hash = create_hash(&vec![b'a', b'b', b'c'], Length::new(24), Sha521DigestSize::Len512);
assert_eq!(hash, vec![
0xdd, 0xaf, 0x35, 0xa1, 0x93, 0x61, 0x7a, 0xba,
0xcc, 0x41, 0x73, 0x49, 0xae, 0x20, 0x41, 0x31,
0x12, 0xe6, 0xfa, 0x4e, 0x89, 0xa9, 0x7e, 0xa2,
0x0a, 0x9e, 0xee, 0xe6, 0x4b, 0x55, 0xd3, 0x9a,
0x21, 0x92, 0x99, 0x2a, 0x27, 0x4f, 0xc1, 0xa8,
0x36, 0xba, 0x3c, 0x23, 0xa3, 0xfe, 0xeb, 0xbd,
0x45, 0x4d, 0x44, 0x23, 0x64, 0x3c, 0xe8, 0x0e,
0x2a, 0x9a, 0xc9, 0x4f, 0xa5, 0x4c, 0xa4, 0x9f
].into_boxed_slice());
}
/// 895 bit の 0 で構成されたメッセージに対し SHA512 を取る(境界テスト)
#[test]
fn sha2_512_hash_by_895_zero_bits() {
let hash = create_hash(&vec![
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
], Length::new(895), Sha521DigestSize::Len512);
assert_eq!(hash, vec![
0x12, 0xDD, 0x83, 0xC5, 0xB6, 0x54, 0x77, 0x58,
0x45, 0x2D, 0xC7, 0x02, 0x0E, 0xE3, 0x2F, 0x53,
0xF5, 0xA0, 0xEB, 0x65, 0xD3, 0x3C, 0x4D, 0x3F,
0xEE, 0xBC, 0xE1, 0x7D, 0x71, 0x13, 0xDB, 0x14,
0x03, 0x93, 0xC8, 0xFB, 0xE4, 0x9F, 0xC0, 0x71,
0xE4, 0x0B, 0x58, 0x5D, 0xF9, 0x69, 0xC7, 0xAA,
0x3A, 0x81, 0x96, 0xCE, 0x2B, 0x94, 0xE8, 0x3E,
0x79, 0x41, 0xEC, 0x05, 0xE2, 0x01, 0x87, 0x51
].into_boxed_slice());
}
/// 896 bit の 0 で構成されたメッセージに対し SHA512 を取る(境界テスト)
#[test]
fn sha2_512_hash_by_896_zero_bits() {
let hash = create_hash(&vec![
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
], Length::new(896), Sha521DigestSize::Len512);
assert_eq!(hash, vec![
0x2B, 0xE2, 0xE7, 0x88, 0xC8, 0xA8, 0xAD, 0xEA,
0xA9, 0xC8, 0x9A, 0x7F, 0x78, 0x90, 0x4C, 0xAC,
0xEA, 0x6E, 0x39, 0x29, 0x7D, 0x75, 0xE0, 0x57,
0x3A, 0x73, 0xC7, 0x56, 0x23, 0x45, 0x34, 0xD6,
0x62, 0x7A, 0xB4, 0x15, 0x6B, 0x48, 0xA6, 0x65,
0x7B, 0x29, 0xAB, 0x8B, 0xEB, 0x73, 0x33, 0x40,
0x40, 0xAD, 0x39, 0xEA, 0xD8, 0x14, 0x46, 0xBB,
0x09, 0xC7, 0x07, 0x04, 0xEC, 0x70, 0x79, 0x52
].into_boxed_slice());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment