Skip to content

Commit 3ea1b74

Browse files
committed
feature: add pkcs #1 I2OSP & OS2IP
1 parent 9346744 commit 3ea1b74

File tree

5 files changed

+57
-0
lines changed

5 files changed

+57
-0
lines changed

benchmarks/utils.jl

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
using ToyPublicKeys
2+
using BenchmarkTools
3+
using Random
4+
5+
test_for_bitsizes = [1024, 2048, 4096]
6+
for bitsize in test_for_bitsizes
7+
Random.seed!(42)
8+
n = rand(big"2" << bitsize: big"2" << (bitsize + 1))
9+
println("Benchmarking ToyPublicKeys.I2OSP for bitsize $bitsize")
10+
display(@benchmark ToyPublicKeys.I2OSP($n))
11+
str = ToyPublicKeys.I2OSP(n)
12+
println("Benchmarking ToyPublicKeys.OS2IP for bitsize $bitsize")
13+
display(@benchmark ToyPublicKeys.OS2IP($str))
14+
end

src/ToyPublicKeys.jl

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ module ToyPublicKeys
33
include("utils/primes.jl")
44
include("utils/random.jl")
55
include("utils/number_theory.jl")
6+
include("utils/string.jl")
67
include("padding/pkcs_1_v1_5.jl")
78
include("rsa.jl")
89
include("dh.jl")

src/utils/string.jl

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
function I2OSP(x::BigInt)
2+
return I2OSP(x, Base.GMP.MPZ.sizeinbase(x, 16))
3+
end
4+
5+
function I2OSP(x::BigInt, xLen::Integer)
6+
xLen |> isodd && (xLen += 1)
7+
base_size = Base.GMP.MPZ.sizeinbase(x, 16)
8+
base_size > xLen && throw(error("integer too big for xLen"))
9+
buf = zeros(UInt8, xLen)
10+
fill!(buf, '0')
11+
buf_ptr = pointer(buf)
12+
Base.GMP.MPZ.get_str!(buf_ptr + xLen - base_size, 16, x)
13+
_buf = String(buf) |> uppercase
14+
it = Iterators.Stateful(_buf)
15+
part = Base.Iterators.partition(it, 2)
16+
return join(map(join, part), ':')
17+
end
18+
19+
function OS2IP(x::String)
20+
# use Cstring instead..?
21+
buf = replace(x, ":" => "") |> lowercase |> Vector{UInt8}
22+
push!(buf, 0)
23+
target = BigInt(0)
24+
Base.GMP.MPZ.set_str!(target, pointer(buf), 16) == 0 || throw(error("string not valid base 16"))
25+
return target
26+
end

test/runtests.jl

+1
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@ using Test
44
include("rsa.jl")
55
include("dh.jl")
66
include("padding.jl")
7+
include("utils.jl")

test/utils.jl

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
@testset "I2OSP" begin
2+
b = big"255"
3+
@test b |> ToyPublicKeys.I2OSP == "FF"
4+
@test b |> x -> ToyPublicKeys.I2OSP(x, 3) == "00:FF"
5+
end
6+
7+
@testset "OS2IP" begin
8+
b = "FF"
9+
@test b |> ToyPublicKeys.OS2IP == big"255"
10+
end
11+
12+
@testset "I2OSP |> OS2IP" begin
13+
b = big"255"
14+
@test b |> ToyPublicKeys.I2OSP |> ToyPublicKeys.OS2IP == b
15+
end

0 commit comments

Comments
 (0)