| 1 | // This is a benchmark for`x.crypto.chacha20` encryption and decryption |
| 2 | // |
| 3 | // Current output on my tests |
| 4 | // |
| 5 | // Chacha20 Encryption |
| 6 | // ----------- |
| 7 | // Iterations: 10000 Total Duration: 76.045ms ns/op: 7604 B/op: 4 allocs/op: 2 |
| 8 | // |
| 9 | // ChaCha20 Decryption |
| 10 | // ----------- |
| 11 | // Iterations: 10000 Total Duration: 71.275ms ns/op: 7127 B/op: 11 allocs/op: 14 |
| 12 | // |
| 13 | // After the patch |
| 14 | // Chacha20 Encryption |
| 15 | // ----------- |
| 16 | // Iterations: 10000 Total Duration: 46.833ms ns/op: 4683 B/op: 11 allocs/op: 11 |
| 17 | // |
| 18 | // ChaCha20 Decryption |
| 19 | // ----------- |
| 20 | // Iterations: 10000 Total Duration: 48.242ms ns/op: 4824 B/op: 3 allocs/op: 4 |
| 21 | // |
| 22 | // Chacha20 old xor_key_stream_backup |
| 23 | // ----------- |
| 24 | // Iterations: 10000 Total Duration: 53.430ms ns/op: 5343 B/op: 11 allocs/op: 12 |
| 25 | // ChaCha20 new xor_key_stream |
| 26 | // ----------- |
| 27 | // Iterations: 10000 Total Duration: 43.668ms ns/op: 4366 B/op: 0 allocs/op: 1 |
| 28 | // |
| 29 | import x.benchmark |
| 30 | import encoding.hex |
| 31 | import x.crypto.chacha20 |
| 32 | |
| 33 | // randomly generated key and nonce, 32-bytes of key, 12-bytes of nonce |
| 34 | const key = hex.decode('9d9603f4fc460e273b80795ea50eab5873c04f589226c7d591b5336feb32fcba')! |
| 35 | const nonce = hex.decode('9a3c83e4236ea9a2c4e482da')! |
| 36 | |
| 37 | const plaintext = 'ChaCha20 encrypt decrypt benchmarking message'.bytes() |
| 38 | |
| 39 | // expected ciphertext |
| 40 | const ciphertext = hex.decode('dbddb264e4c478d96805b2d557649232b4b3f37c51035464d12e3675e5e36ce6f6822b49dd6494ccd5213a89c9')! |
| 41 | |
| 42 | fn bench_chacha20_encrypt() ! { |
| 43 | _ := chacha20.encrypt(key, nonce, plaintext)! |
| 44 | } |
| 45 | |
| 46 | fn bench_chacha20_decrypt() ! { |
| 47 | _ := chacha20.decrypt(key, nonce, ciphertext)! |
| 48 | } |
| 49 | |
| 50 | fn bench_chacha20_xor_key_stream() ! { |
| 51 | mut dst := []u8{len: plaintext.len} |
| 52 | mut cs := chacha20.new_cipher(key, nonce)! |
| 53 | cs.xor_key_stream(mut dst, plaintext) |
| 54 | } |
| 55 | |
| 56 | fn main() { |
| 57 | cf := benchmark.BenchmarkDefaults{ |
| 58 | n: 10000 |
| 59 | } |
| 60 | println('Chacha20 Encryption') |
| 61 | println('-----------') |
| 62 | mut b0 := benchmark.setup(bench_chacha20_encrypt, cf)! |
| 63 | b0.run() |
| 64 | |
| 65 | println('ChaCha20 Decryption') |
| 66 | println('-----------') |
| 67 | mut b1 := benchmark.setup(bench_chacha20_decrypt, cf)! |
| 68 | b1.run() |
| 69 | |
| 70 | println('ChaCha20 new xor_key_stream') |
| 71 | println('-----------') |
| 72 | mut b3 := benchmark.setup(bench_chacha20_xor_key_stream, cf)! |
| 73 | b3.run() |
| 74 | } |
| 75 | |