v

Зеркало из https://github.com/vlang/v
Форк
0
/
sha512.v 
370 строк · 9.2 Кб
1
// Copyright (c) 2019-2024 Alexander Medvednikov. All rights reserved.
2
// Use of this source code is governed by an MIT license
3
// that can be found in the LICENSE file.
4
// Package sha512 implements the SHA-384, SHA-512, SHA-512/224, and SHA-512/256
5
// hash algorithms as defined in FIPS 180-4.
6
// Based off:   https://github.com/golang/go/tree/master/src/crypto/sha512
7
// Last commit: https://github.com/golang/go/commit/3ce865d7a0b88714cc433454ae2370a105210c01
8
module sha512
9

10
import crypto
11
import encoding.binary
12

13
// size is the size, in bytes, of a SHA-512 checksum.
14
pub const size = 64
15
// size224 is the size, in bytes, of a SHA-512/224 checksum.
16
pub const size224 = 28
17
// size256 is the size, in bytes, of a SHA-512/256 checksum.
18
pub const size256 = 32
19
// size384 is the size, in bytes, of a SHA-384 checksum.
20
pub const size384 = 48
21
// block_size is the block size, in bytes, of the SHA-512/224,
22
// SHA-512/256, SHA-384 and SHA-512 hash functions.
23
pub const block_size = 128
24

25
const chunk = 128
26
const init0 = u64(0x6a09e667f3bcc908)
27
const init1 = u64(0xbb67ae8584caa73b)
28
const init2 = u64(0x3c6ef372fe94f82b)
29
const init3 = u64(0xa54ff53a5f1d36f1)
30
const init4 = u64(0x510e527fade682d1)
31
const init5 = u64(0x9b05688c2b3e6c1f)
32
const init6 = u64(0x1f83d9abfb41bd6b)
33
const init7 = u64(0x5be0cd19137e2179)
34
const init0_224 = u64(0x8c3d37c819544da2)
35
const init1_224 = u64(0x73e1996689dcd4d6)
36
const init2_224 = u64(0x1dfab7ae32ff9c82)
37
const init3_224 = u64(0x679dd514582f9fcf)
38
const init4_224 = u64(0x0f6d2b697bd44da8)
39
const init5_224 = u64(0x77e36f7304c48942)
40
const init6_224 = u64(0x3f9d85a86a1d36c8)
41
const init7_224 = u64(0x1112e6ad91d692a1)
42
const init0_256 = u64(0x22312194fc2bf72c)
43
const init1_256 = u64(0x9f555fa3c84c64c2)
44
const init2_256 = u64(0x2393b86b6f53b151)
45
const init3_256 = u64(0x963877195940eabd)
46
const init4_256 = u64(0x96283ee2a88effe3)
47
const init5_256 = u64(0xbe5e1e2553863992)
48
const init6_256 = u64(0x2b0199fc2c85b8aa)
49
const init7_256 = u64(0x0eb72ddc81c52ca2)
50
const init0_384 = u64(0xcbbb9d5dc1059ed8)
51
const init1_384 = u64(0x629a292a367cd507)
52
const init2_384 = u64(0x9159015a3070dd17)
53
const init3_384 = u64(0x152fecd8f70e5939)
54
const init4_384 = u64(0x67332667ffc00b31)
55
const init5_384 = u64(0x8eb44a8768581511)
56
const init6_384 = u64(0xdb0c2e0d64f98fa7)
57
const init7_384 = u64(0x47b5481dbefa4fa4)
58

59
// Digest represents the partial evaluation of a checksum.
60
struct Digest {
61
mut:
62
	h        []u64
63
	x        []u8
64
	nx       int
65
	len      u64
66
	function crypto.Hash
67
}
68

69
// free the resources taken by the Digest `d`
70
@[unsafe]
71
pub fn (mut d Digest) free() {
72
	$if prealloc {
73
		return
74
	}
75
	unsafe {
76
		d.x.free()
77
		d.h.free()
78
	}
79
}
80

81
fn (mut d Digest) init() {
82
	d.h = []u64{len: (8)}
83
	d.x = []u8{len: chunk}
84
	d.reset()
85
}
86

87
// reset the state of the Digest `d`
88
pub fn (mut d Digest) reset() {
89
	match d.function {
90
		.sha384 {
91
			d.h[0] = init0_384
92
			d.h[1] = init1_384
93
			d.h[2] = init2_384
94
			d.h[3] = init3_384
95
			d.h[4] = init4_384
96
			d.h[5] = init5_384
97
			d.h[6] = init6_384
98
			d.h[7] = init7_384
99
		}
100
		.sha512_224 {
101
			d.h[0] = init0_224
102
			d.h[1] = init1_224
103
			d.h[2] = init2_224
104
			d.h[3] = init3_224
105
			d.h[4] = init4_224
106
			d.h[5] = init5_224
107
			d.h[6] = init6_224
108
			d.h[7] = init7_224
109
		}
110
		.sha512_256 {
111
			d.h[0] = init0_256
112
			d.h[1] = init1_256
113
			d.h[2] = init2_256
114
			d.h[3] = init3_256
115
			d.h[4] = init4_256
116
			d.h[5] = init5_256
117
			d.h[6] = init6_256
118
			d.h[7] = init7_256
119
		}
120
		else {
121
			d.h[0] = init0
122
			d.h[1] = init1
123
			d.h[2] = init2
124
			d.h[3] = init3
125
			d.h[4] = init4
126
			d.h[5] = init5
127
			d.h[6] = init6
128
			d.h[7] = init7
129
		}
130
	}
131
	d.nx = 0
132
	d.len = 0
133
}
134

135
fn (d &Digest) clone() &Digest {
136
	return &Digest{
137
		...d
138
		h: d.h.clone()
139
		x: d.x.clone()
140
	}
141
}
142

143
// internal
144
fn new_digest(hash crypto.Hash) &Digest {
145
	mut d := &Digest{
146
		function: hash
147
	}
148
	d.init()
149
	return d
150
}
151

152
// new returns a new Digest (implementing hash.Hash) computing the SHA-512 checksum.
153
pub fn new() &Digest {
154
	return new_digest(.sha512)
155
}
156

157
// new512_224 returns a new Digest (implementing hash.Hash) computing the SHA-512/224 checksum.
158
pub fn new512_224() &Digest {
159
	return new_digest(.sha512_224)
160
}
161

162
// new512_256 returns a new Digest (implementing hash.Hash) computing the SHA-512/256 checksum.
163
pub fn new512_256() &Digest {
164
	return new_digest(.sha512_256)
165
}
166

167
// new384 returns a new Digest (implementing hash.Hash) computing the SHA-384 checksum.
168
pub fn new384() &Digest {
169
	return new_digest(.sha384)
170
}
171

172
// write writes the contents of `p_` to the internal hash representation.
173
pub fn (mut d Digest) write(p_ []u8) !int {
174
	unsafe {
175
		mut p := p_
176
		nn := p.len
177
		d.len += u64(nn)
178
		if d.nx > 0 {
179
			n := copy(mut d.x[d.nx..], p)
180
			d.nx += n
181
			if d.nx == chunk {
182
				block(mut d, d.x)
183
				d.nx = 0
184
			}
185
			if n >= p.len {
186
				p = []
187
			} else {
188
				p = p[n..]
189
			}
190
		}
191
		if p.len >= chunk {
192
			n := p.len & ~(chunk - 1)
193
			block(mut d, p[..n])
194
			if n >= p.len {
195
				p = []
196
			} else {
197
				p = p[n..]
198
			}
199
		}
200
		if p.len > 0 {
201
			d.nx = copy(mut d.x, p)
202
		}
203
		return nn
204
	}
205
}
206

207
// sum returns the SHA512 or SHA384 checksum of digest with the data bytes in `b_in`
208
pub fn (d &Digest) sum(b_in []u8) []u8 {
209
	// Make a copy of d so that caller can keep writing and summing.
210
	mut d0 := d.clone()
211
	hash := d0.checksum_internal()
212
	mut b_out := b_in.clone()
213
	match d0.function {
214
		.sha384 {
215
			for b in hash[..size384] {
216
				b_out << b
217
			}
218
		}
219
		.sha512_224 {
220
			for b in hash[..size224] {
221
				b_out << b
222
			}
223
		}
224
		.sha512_256 {
225
			for b in hash[..size256] {
226
				b_out << b
227
			}
228
		}
229
		else {
230
			for b in hash {
231
				b_out << b
232
			}
233
		}
234
	}
235
	return b_out
236
}
237

238
// TODO:
239
// When the deprecated "checksum()" is finally removed, restore this function name as: "checksum()"
240
fn (mut d Digest) checksum_internal() []u8 {
241
	// Padding. Add a 1 bit and 0 bits until 112 bytes mod 128.
242
	mut len := d.len
243
	mut tmp := []u8{len: (128)}
244
	tmp[0] = 0x80
245
	if int(len) % 128 < 112 {
246
		d.write(tmp[..112 - int(len) % 128]) or { panic(err) }
247
	} else {
248
		d.write(tmp[..128 + 112 - int(len) % 128]) or { panic(err) }
249
	}
250
	// Length in bits.
251
	len <<= u64(3)
252
	binary.big_endian_put_u64(mut tmp, u64(0)) // upper 64 bits are always zero, because len variable has type u64
253
	binary.big_endian_put_u64(mut tmp[8..], len)
254
	d.write(tmp[..16]) or { panic(err) }
255
	if d.nx != 0 {
256
		panic('d.nx != 0')
257
	}
258
	mut digest := []u8{len: size}
259
	binary.big_endian_put_u64(mut digest, d.h[0])
260
	binary.big_endian_put_u64(mut digest[8..], d.h[1])
261
	binary.big_endian_put_u64(mut digest[16..], d.h[2])
262
	binary.big_endian_put_u64(mut digest[24..], d.h[3])
263
	binary.big_endian_put_u64(mut digest[32..], d.h[4])
264
	binary.big_endian_put_u64(mut digest[40..], d.h[5])
265
	if d.function != .sha384 {
266
		binary.big_endian_put_u64(mut digest[48..], d.h[6])
267
		binary.big_endian_put_u64(mut digest[56..], d.h[7])
268
	}
269
	return digest
270
}
271

272
// checksum returns the current byte checksum of the Digest,
273
// it is an internal method and is not recommended because its results are not idempotent.
274
@[deprecated: 'checksum() will be changed to a private method, use sum() instead']
275
@[deprecated_after: '2024-04-30']
276
pub fn (mut d Digest) checksum() []u8 {
277
	out := d.checksum_internal()
278
	match d.function {
279
		.sha384 {
280
			return out[0..size384]
281
		}
282
		.sha512_224 {
283
			return out[0..size224]
284
		}
285
		.sha512_256 {
286
			return out[0..size256]
287
		}
288
		else {
289
			return out
290
		}
291
	}
292
}
293

294
// sum512 returns the SHA512 checksum of the data.
295
pub fn sum512(data []u8) []u8 {
296
	mut d := new_digest(.sha512)
297
	d.write(data) or { panic(err) }
298
	return d.checksum_internal()
299
}
300

301
// sum384 returns the SHA384 checksum of the data.
302
pub fn sum384(data []u8) []u8 {
303
	mut d := new_digest(.sha384)
304
	d.write(data) or { panic(err) }
305
	sum := d.checksum_internal()
306
	mut sum384 := []u8{len: size384}
307
	copy(mut sum384, sum[..size384])
308
	return sum384
309
}
310

311
// sum512_224 returns the Sum512/224 checksum of the data.
312
pub fn sum512_224(data []u8) []u8 {
313
	mut d := new_digest(.sha512_224)
314
	d.write(data) or { panic(err) }
315
	sum := d.checksum_internal()
316
	mut sum224 := []u8{len: size224}
317
	copy(mut sum224, sum[..size224])
318
	return sum224
319
}
320

321
// sum512_256 returns the Sum512/256 checksum of the data.
322
pub fn sum512_256(data []u8) []u8 {
323
	mut d := new_digest(.sha512_256)
324
	d.write(data) or { panic(err) }
325
	sum := d.checksum_internal()
326
	mut sum256 := []u8{len: size256}
327
	copy(mut sum256, sum[..size256])
328
	return sum256
329
}
330

331
fn block(mut dig Digest, p []u8) {
332
	// For now just use block_generic until we have specific
333
	// architecture optimized versions
334
	block_generic(mut dig, p)
335
}
336

337
// size returns the size of the checksum in bytes.
338
pub fn (d &Digest) size() int {
339
	match d.function {
340
		.sha512_224 { return size224 }
341
		.sha512_256 { return size256 }
342
		.sha384 { return size384 }
343
		else { return size }
344
	}
345
}
346

347
// block_size returns the block size of the checksum in bytes.
348
pub fn (d &Digest) block_size() int {
349
	return block_size
350
}
351

352
// hexhash returns a hexadecimal SHA512 hash sum `string` of `s`.
353
pub fn hexhash(s string) string {
354
	return sum512(s.bytes()).hex()
355
}
356

357
// hexhash_384 returns a hexadecimal SHA384 hash sum `string` of `s`.
358
pub fn hexhash_384(s string) string {
359
	return sum384(s.bytes()).hex()
360
}
361

362
// hexhash_512_224 returns a hexadecimal SHA512/224 hash sum `string` of `s`.
363
pub fn hexhash_512_224(s string) string {
364
	return sum512_224(s.bytes()).hex()
365
}
366

367
// hexhash_512_256 returns a hexadecimal 512/256 hash sum `string` of `s`.
368
pub fn hexhash_512_256(s string) string {
369
	return sum512_256(s.bytes()).hex()
370
}
371

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.