File: subtle_spec.cr

package info (click to toggle)
crystal 1.14.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 24,384 kB
  • sloc: javascript: 6,400; sh: 695; makefile: 269; ansic: 121; python: 105; cpp: 77; xml: 32
file content (45 lines) | stat: -rw-r--r-- 1,726 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
require "spec"
require "crypto/subtle"

describe "Subtle" do
  it "compares constant times" do
    data = [
      {"a" => Slice.new(1, 0x11), "b" => Slice.new(1, 0x11), "result" => true},
      {"a" => Slice.new(1, 0x12), "b" => Slice.new(1, 0x11), "result" => false},
      {"a" => Slice.new(1, 0x11), "b" => Slice.new(2) { |i| 0x11 + i }, "result" => false},
      {"a" => Slice.new(2) { |i| 0x11 + i }, "b" => Slice.new(1, 0x11), "result" => false},
    ]

    data.each do |test|
      Crypto::Subtle.constant_time_compare(test["a"].as(Slice(Int32)), test["b"].as(Slice(Int32))).should eq(test["result"])
    end
  end

  it "compares constant time bytes on equality" do
    data = [
      {"a" => 0x00_u8, "b" => 0x00_u8, "result" => 1},
      {"a" => 0x00_u8, "b" => 0x01_u8, "result" => 0},
      {"a" => 0x01_u8, "b" => 0x00_u8, "result" => 0},
      {"a" => 0xff_u8, "b" => 0xff_u8, "result" => 1},
      {"a" => 0xff_u8, "b" => 0xfe_u8, "result" => 0},
    ]

    data.each do |test|
      Crypto::Subtle.constant_time_byte_eq(test["a"], test["b"]).should eq(test["result"])
    end
  end

  it "compares constant time bytes bug" do
    h1 = "$2a$05$LEC1XBXgXECzKUO2LBDhKOa9lH9zigNKnksVaDwViFNgPU4WkrD53J"
    h2 = "$2a$05$LEC1XBXgXECzKUO2LBDhKOaHlSGFuDDwMuVg6gOzdxQ0xN4rFOwMUn"
    Crypto::Subtle.constant_time_compare(h1, h2).should eq(false)
  end

  it "compares constant time and slices strings" do
    h1 = "$2a$05$LEC1XBXgXECzKUO2LBDhKOa9lH9zigNKnksVaDwViFNgPU4WkrD53J"
    h2 = "$2a$05$LEC1XBXgXECzKUO2LBDhKOaHlSGFuDDwMuVg6gOzdxQ0xN4rFOwMUn"

    slice_result = Crypto::Subtle.constant_time_compare(h1.to_slice, h2.to_slice)
    Crypto::Subtle.constant_time_compare(h1, h2).should eq(slice_result)
  end
end