Advertisement
dbadia

ctr_drbg.test.ts

Dec 29th, 2024
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. import test from "ava";
  2. import * as fs from "node:fs";
  3. import * as path from "node:path";
  4. import { CtrDRBG } from "./ctr_drbg";
  5.  
  6. function getVectors(alg: string) {
  7. const text = fs.readFileSync(
  8. path.join(__dirname, "ctr_drbg.test.vectors.txt"),
  9. "utf8",
  10. );
  11. const vectors = [];
  12.  
  13. let from = -1;
  14.  
  15. while (true) {
  16. from = text.indexOf(`[${alg}]`, from + 1);
  17.  
  18. if (from === -1) break;
  19.  
  20. for (let i = 0; i < 15; i++) {
  21. const vector: Record<string, any> = {};
  22. const start = text.indexOf(`COUNT = ${i}`, from);
  23. const end = text.indexOf("\n\n", start);
  24. const items = text.slice(start, end).split("\n");
  25.  
  26. for (let j = 1; j < items.length; j++) {
  27. const key = items[j].split(" = ")[0];
  28. const value = Buffer.from(items[j].split(" = ")[1], "hex");
  29.  
  30. if (vector[key]) vector[key] = [vector[key], value];
  31. else vector[key] = value;
  32. }
  33.  
  34. vectors.push(vector);
  35. }
  36. }
  37.  
  38. return vectors;
  39. }
  40.  
  41. for (const df of [false, true]) {
  42. for (const id of ["AES-128"]) {
  43. const name = id + (df ? " use df" : " no df");
  44. const vectors = getVectors(name);
  45. const bits = parseInt(id.slice(-3)) as 128;
  46.  
  47. for (const [i, vector] of vectors.entries()) {
  48. test(
  49. `CtrDRBG -> should pass ${name} NIST vector #${
  50. i + 1
  51. } (ctr,df=${df})`,
  52. (t) => {
  53. const drbg = new CtrDRBG(bits, df);
  54.  
  55. drbg.init(
  56. vector.EntropyInput,
  57. vector.Nonce,
  58. vector.PersonalizationString,
  59. );
  60.  
  61. drbg.reseed(
  62. vector.EntropyInputReseed,
  63. vector.AdditionalInputReseed,
  64. );
  65.  
  66. drbg.generate(
  67. vector.ReturnedBits.length,
  68. vector.AdditionalInput[0],
  69. );
  70.  
  71. const result = drbg.generate(
  72. vector.ReturnedBits.length,
  73. vector.AdditionalInput[1],
  74. );
  75.  
  76. t.deepEqual(result, vector.ReturnedBits);
  77. },
  78. );
  79. }
  80. }
  81. }
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement