Debian Codegraph @

test/lua/unit/rsa.lua

raw
1 -- Test rsa signing
2
3 context("RSA signature verification test", function()
4 local rsa_privkey = require "rspamd_rsa_privkey"
5 local rsa_pubkey = require "rspamd_rsa_pubkey"
6 local rsa_signature = require "rspamd_rsa_signature"
7 local rsa = require "rspamd_rsa"
8 local hash = require "rspamd_cryptobox_hash"
9 local pubkey = 'testkey.pub'
10 local privkey = 'testkey.sec'
11 local data = 'test.data'
12 local signature = 'test.sig'
13 local signature_bytes = 'test.sig_bytes'
14 local test_dir = string.gsub(debug.getinfo(1).source, "^@(.+/)[^/]+$", "%1")
15 local rsa_key, rsa_sig
16
17 test("RSA sign", function()
18 -- Signing test
19 rsa_key = rsa_privkey.load_file(string.format('%s/%s', test_dir, privkey))
20 assert_not_nil(rsa_key)
21
22 local h = hash.create_specific('sha256')
23 local d = io.open(string.format('%s/%s', test_dir, data), "rb"):read "*a"
24 h:update(d)
25 local sig = rsa.sign_memory(rsa_key, h:bin())
26 assert_not_nil(sig)
27 sig:save(string.format('%s/%s', test_dir, signature_bytes), true)
28 local sig_actual = string.format('%s\n', sig:base64(80, 'lf'))
29 local sig_expected = io.open(string.format('%s/%s', test_dir, signature), "rb"):read "*a"
30 assert_equal(sig_actual, sig_expected)
31 end)
32
33 test("RSA verify", function()
34 -- Verifying test
35 local h = hash.create_specific('sha256')
36 local d = io.open(string.format('%s/%s', test_dir, data), "rb"):read "*a"
37 h:update(d)
38 rsa_key = rsa_pubkey.load(string.format('%s/%s', test_dir, pubkey))
39 assert_not_nil(rsa_key)
40 rsa_sig = rsa_signature.load(string.format('%s/%s', test_dir, signature_bytes))
41 assert_not_nil(rsa_sig)
42 assert_true(rsa.verify_memory(rsa_key, rsa_sig, h:bin()))
43 end)
44
45 test("RSA keypair + sign + verify", function()
46 local sk, pk = rsa.keypair()
47 local sig = rsa.sign_memory(sk, "test_012345678901234567890123456")
48 assert_true(rsa.verify_memory(pk, sig, "test_012345678901234567890123456"))
49 assert_false(rsa.verify_memory(pk, sig, "blah_012345678901234567890123456"))
50 -- Overwrite
51 sk, pk = rsa.keypair()
52 assert_false(rsa.verify_memory(pk, sig, "test_012345678901234567890123456"))
53 end)
54
55 test("RSA-2048 keypair + sign + verify", function()
56 local sk, pk = rsa.keypair(2048)
57 local sig = rsa.sign_memory(sk, "test_012345678901234567890123456")
58 assert_true(rsa.verify_memory(pk, sig, "test_012345678901234567890123456"))
59 assert_false(rsa.verify_memory(pk, sig, "blah_012345678901234567890123456"))
60 -- Overwrite
61 sk, pk = rsa.keypair(2048)
62 assert_false(rsa.verify_memory(pk, sig, "test_012345678901234567890123456"))
63 end)
64 end)