Skip to content

Commit 9ea657c

Browse files
committed
FEAT: simple crypt port test/example file
1 parent 7d0849b commit 9ea657c

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

src/tests/test-crypt.r3

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
Rebol [
2+
Title: "Test crypt port"
3+
Date: 3-Feb-2022
4+
Author: "Oldes"
5+
File: %test-crypt.r3
6+
Version: 1.0.0
7+
Requires: 3.8.0
8+
]
9+
10+
my-secret: context [
11+
password: checksum "my not much secret password" 'sha256
12+
]
13+
;- using just simple wrapper functions for [en/de]cryption
14+
encrypt: function [data cipher [word!]] [
15+
binary/write vector: #{} [random-bytes 16]
16+
port: open [
17+
scheme: 'crypt
18+
algorithm: :cipher
19+
key: :my-secret/password
20+
init-vector: :vector
21+
]
22+
bytes: length? data
23+
check: checksum/with data 'sha256 my-secret/password
24+
output: make binary! 48 + bytes
25+
binary/write output [UI32 :bytes :check :vector]
26+
if bytes > 0 [
27+
write port data
28+
; here could be more writes, for example for showing a progress...
29+
update port ; finish the stream... adds padding if needed
30+
append output read port ; resolve encrypted data
31+
]
32+
close port
33+
output
34+
]
35+
decrypt: function [data cipher [word!]] [
36+
binary/read data [
37+
bytes: UI32 ; real data size (ecrypted may be padded)
38+
expected-sum: BYTES 32 ; checksum using SHA256 and the password
39+
vector: BYTES 16 ; random initial vector used for encryption
40+
pos: INDEX
41+
]
42+
output: either bytes > 0 [
43+
port: open [
44+
scheme: 'crypt
45+
direction: 'decrypt
46+
algorithm: :cipher
47+
key: :my-secret/password
48+
init-vector: :vector
49+
]
50+
write port at data :pos ; decrypt the rest of data (skipping the header)
51+
; here could be more writes, for example for showing a progress...
52+
read update port ; get decrypted data
53+
][ copy #{} ] ; there were no data
54+
close port ; and close the port as is not needed anymore
55+
real-sum: checksum/with output 'sha256 my-secret/password
56+
either real-sum = expected-sum [output][none]
57+
]
58+
59+
original: read system/options/boot
60+
61+
print ["Encrypting and decrypting" length? original "bytes"]
62+
foreach cipher system/catalog/ciphers [
63+
if cipher = 'chacha20-poly1305 [continue]
64+
prin pad cipher 19
65+
t1: dt [encrypted: encrypt original :cipher]
66+
t2: dt [decrypted: decrypt encrypted :cipher]
67+
prin [pad t1 16 pad t2 16]
68+
print either decrypted [as-green " OK"][as-red reduce [" FAILED!" length? decrypted]]
69+
]
70+
71+
if system/options/script [ask "DONE"]

0 commit comments

Comments
 (0)