@intellectual-frontiers/crypto 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +8 -2
- package/dist/cms.d.ts +106 -0
- package/dist/cms.js +350 -0
- package/dist/cose.d.ts +34 -0
- package/dist/cose.js +204 -0
- package/dist/crypt.d.ts +30 -0
- package/dist/crypt.js +117 -0
- package/dist/dsse.d.ts +137 -0
- package/dist/dsse.js +243 -0
- package/dist/md5.d.ts +19 -0
- package/dist/md5.js +146 -0
- package/dist/mod.d.ts +25 -0
- package/dist/mod.js +25 -0
- package/dist/sha256.d.ts +25 -0
- package/dist/sha256.js +34 -0
- package/dist/sigv4.d.ts +67 -0
- package/dist/sigv4.js +169 -0
- package/dist/uuid.d.ts +53 -0
- package/dist/uuid.js +92 -0
- package/dist/webauthn.d.ts +212 -0
- package/dist/webauthn.js +381 -0
- package/package.json +84 -4
- package/src/cms.ts +387 -0
- package/src/cose.ts +199 -0
- package/src/crypt.ts +117 -0
- package/src/dsse.ts +339 -0
- package/src/md5.ts +150 -0
- package/src/mod.ts +26 -0
- package/src/sha256.ts +55 -0
- package/src/sigv4.ts +216 -0
- package/src/uuid.ts +111 -0
- package/src/webauthn.ts +548 -0
package/src/crypt.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// Spec: 0001-crypto FR-003
|
|
2
|
+
/**
|
|
3
|
+
* SHA-512 crypt (`$6$`), the password hash of glibc's `crypt(3)` that Linux accounts and Ubuntu's installer accept, on Web Crypto alone
|
|
4
|
+
* (commons 0001-crypto FR-003). The algorithm is Ulrich Drepper's "Unix crypt using SHA-256 and SHA-512". The salt is given,
|
|
5
|
+
* so the kernel stays free of effects: a caller makes one from random bytes with `cryptSalt(crypto.getRandomValues(new Uint8Array(16)))`.
|
|
6
|
+
* Taken from Stolos's `src/archon/core/crypt.ts`.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* import { sha512Crypt } from "./crypt.ts";
|
|
11
|
+
* await sha512Crypt("Hello world!", "saltstring");
|
|
12
|
+
* // "$6$saltstring$svn8UoSVapNtMuq1ukKS4tPQd8iKwSMHWjl/O817G3uBnIFNjnQJuesI68u4OTLiBFdcbYEdFCoEOfaS35inz1"
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* @module
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const B64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
19
|
+
|
|
20
|
+
/** The rounds glibc uses when none are named, and the least and most it accepts. */
|
|
21
|
+
export const CRYPT_ROUNDS = { default: 5000, min: 1000, max: 999_999_999 } as const;
|
|
22
|
+
|
|
23
|
+
async function sha512(parts: readonly Uint8Array[]): Promise<Uint8Array> {
|
|
24
|
+
const buf = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
25
|
+
let at = 0;
|
|
26
|
+
for (const p of parts) {
|
|
27
|
+
buf.set(p, at);
|
|
28
|
+
at += p.length;
|
|
29
|
+
}
|
|
30
|
+
return new Uint8Array(await crypto.subtle.digest("SHA-512", buf));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function repeatTo(src: Uint8Array, n: number): Uint8Array {
|
|
34
|
+
const out = new Uint8Array(n);
|
|
35
|
+
for (let i = 0; i < n; i++) out[i] = src[i % src.length] ?? 0;
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** A salt of crypt's alphabet (`./0-9A-Za-z`) made from bytes, one character each, at most 16. */
|
|
40
|
+
export function cryptSalt(bytes: Uint8Array): string {
|
|
41
|
+
return Array.from(bytes.subarray(0, 16), (b) => B64[b % 64] ?? ".").join("");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const ORDER: readonly (readonly [number, number, number])[] = [
|
|
45
|
+
[0, 21, 42],
|
|
46
|
+
[22, 43, 1],
|
|
47
|
+
[44, 2, 23],
|
|
48
|
+
[3, 24, 45],
|
|
49
|
+
[25, 46, 4],
|
|
50
|
+
[47, 5, 26],
|
|
51
|
+
[6, 27, 48],
|
|
52
|
+
[28, 49, 7],
|
|
53
|
+
[50, 8, 29],
|
|
54
|
+
[9, 30, 51],
|
|
55
|
+
[31, 52, 10],
|
|
56
|
+
[53, 11, 32],
|
|
57
|
+
[12, 33, 54],
|
|
58
|
+
[34, 55, 13],
|
|
59
|
+
[56, 14, 35],
|
|
60
|
+
[15, 36, 57],
|
|
61
|
+
[37, 58, 16],
|
|
62
|
+
[59, 17, 38],
|
|
63
|
+
[18, 39, 60],
|
|
64
|
+
[40, 61, 19],
|
|
65
|
+
[62, 20, 41],
|
|
66
|
+
];
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* A password hashed as SHA-512 crypt: `$6$<salt>$<hash>`, with `rounds=<n>$` after `$6$` where rounds are given (5000 where they are
|
|
70
|
+
* not). Only the first 16 characters of the salt count, and given rounds are clamped to what glibc accepts, as glibc does.
|
|
71
|
+
*/
|
|
72
|
+
export async function sha512Crypt(password: string, salt: string, rounds?: number): Promise<string> {
|
|
73
|
+
const enc = new TextEncoder();
|
|
74
|
+
const named = rounds !== undefined;
|
|
75
|
+
const r = rounds === undefined ? CRYPT_ROUNDS.default : Math.min(CRYPT_ROUNDS.max, Math.max(CRYPT_ROUNDS.min, Math.floor(rounds)));
|
|
76
|
+
const s = salt.slice(0, 16);
|
|
77
|
+
const P = enc.encode(password);
|
|
78
|
+
const S = enc.encode(s);
|
|
79
|
+
const B = await sha512([P, S, P]);
|
|
80
|
+
const aParts: Uint8Array[] = [P, S, repeatTo(B, P.length)];
|
|
81
|
+
for (let n = P.length; n > 0; n >>= 1) aParts.push(n & 1 ? B : P);
|
|
82
|
+
const A = await sha512(aParts);
|
|
83
|
+
const DP = await sha512(Array.from({ length: P.length }, () => P));
|
|
84
|
+
const Pbytes = repeatTo(DP, P.length);
|
|
85
|
+
const DS = await sha512(Array.from({ length: 16 + (A[0] ?? 0) }, () => S));
|
|
86
|
+
const Sbytes = repeatTo(DS, S.length);
|
|
87
|
+
let C = A;
|
|
88
|
+
for (let i = 0; i < r; i++) {
|
|
89
|
+
const parts: Uint8Array[] = [i & 1 ? Pbytes : C];
|
|
90
|
+
if (i % 3) parts.push(Sbytes);
|
|
91
|
+
if (i % 7) parts.push(Pbytes);
|
|
92
|
+
parts.push(i & 1 ? C : Pbytes);
|
|
93
|
+
C = await sha512(parts);
|
|
94
|
+
}
|
|
95
|
+
let out = "";
|
|
96
|
+
const b64 = (value: number, n: number): void => {
|
|
97
|
+
let v = value;
|
|
98
|
+
for (let i = 0; i < n; i++) {
|
|
99
|
+
out += B64[v & 63] ?? ".";
|
|
100
|
+
v >>= 6;
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
for (const [a, b, c] of ORDER) b64(((C[a] ?? 0) << 16) | ((C[b] ?? 0) << 8) | (C[c] ?? 0), 4);
|
|
104
|
+
b64(C[63] ?? 0, 2);
|
|
105
|
+
return `$6$${named ? `rounds=${r}$` : ""}${s}$${out}`;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Whether a password matches a `$6$` hash, by hashing it again with the hash's own salt and rounds. */
|
|
109
|
+
export async function verifySha512Crypt(password: string, hash: string): Promise<boolean> {
|
|
110
|
+
const m = /^\$6\$(?:rounds=(\d+)\$)?([^$]{0,16})\$[./0-9A-Za-z]{86}$/.exec(hash);
|
|
111
|
+
if (m === null) return false;
|
|
112
|
+
const again = await sha512Crypt(password, m[2] ?? "", m[1] === undefined ? undefined : Number(m[1]));
|
|
113
|
+
if (again.length !== hash.length) return false;
|
|
114
|
+
let d = 0;
|
|
115
|
+
for (let i = 0; i < hash.length; i++) d |= again.charCodeAt(i) ^ hash.charCodeAt(i);
|
|
116
|
+
return d === 0;
|
|
117
|
+
}
|
package/src/dsse.ts
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
// Spec: 0001-crypto FR-006
|
|
2
|
+
/**
|
|
3
|
+
* in-toto Statements v1 and DSSE envelopes (commons 0001-crypto FR-006): a statement says that a predicate of some type holds
|
|
4
|
+
* of its subjects, each named and identified by its digests; DSSE signs a payload of a stated type, by the pre-authentication encoding
|
|
5
|
+
* (PAE) of the two, and carries it in a JSON envelope with its signatures. Signing and verifying use Web Crypto (`crypto.subtle`) on keys
|
|
6
|
+
* the caller has imported as `CryptoKey`s, so the module has no effect beyond the computation: Ed25519, ECDSA on P-256, P-384 and P-521
|
|
7
|
+
* (with SHA-256, SHA-384 and SHA-512, the signature in ASN.1 DER as sigstore and in-toto's own tools write it), and RSA-PSS and
|
|
8
|
+
* RSASSA-PKCS1-v1_5 with the key's hash. Verification returns the payload, or an error that says why it was refused: an envelope that is
|
|
9
|
+
* malformed, a payload type not the one expected, a key not usable, or too few valid signatures.
|
|
10
|
+
*
|
|
11
|
+
* Taken from Stolos's `src/archon/export/intoto.ts`, which built a statement and an envelope for a signature callback but never verified
|
|
12
|
+
* one. What changed: the statement is generic in its predicate; the subject's digest is any map of algorithms; signing takes keys rather
|
|
13
|
+
* than a callback; verification, the envelope's decoder and the ECDSA signature form are new. Stolos's evidence bundle predicate (its
|
|
14
|
+
* predicate type, the manifest's summary and the subject list of a bundle's items) is Stolos's own domain and stays there.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```ts
|
|
18
|
+
* import { pae, signStatement, statement, subject, verifyStatement } from "./dsse.ts";
|
|
19
|
+
* import { unknownValue } from "@intellectual-frontiers/core";
|
|
20
|
+
* new TextDecoder().decode(pae("http://example.com/HelloWorld", new TextEncoder().encode("hello world")));
|
|
21
|
+
* // "DSSEv1 29 http://example.com/HelloWorld 11 hello world"
|
|
22
|
+
* const keys = await crypto.subtle.generateKey({ name: "Ed25519" }, false, ["sign", "verify"]);
|
|
23
|
+
* const s = statement([await subject("a.txt", new TextEncoder().encode("a"))], "https://example.com/Note/v1", { note: "hi" });
|
|
24
|
+
* const signed = await signStatement(s, [{ key: keys.privateKey, keyid: "me" }]);
|
|
25
|
+
* if (signed.kind === "ok") await verifyStatement(signed.value, [{ key: keys.publicKey, keyid: "me" }], unknownValue); // { kind: "ok", ... }
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* @module
|
|
29
|
+
*/
|
|
30
|
+
import {
|
|
31
|
+
absurd,
|
|
32
|
+
array,
|
|
33
|
+
type DecodeError,
|
|
34
|
+
type Decoder,
|
|
35
|
+
describe,
|
|
36
|
+
formatDecodeError,
|
|
37
|
+
json,
|
|
38
|
+
object,
|
|
39
|
+
record,
|
|
40
|
+
string,
|
|
41
|
+
unknownValue,
|
|
42
|
+
err,
|
|
43
|
+
ok,
|
|
44
|
+
type Result,
|
|
45
|
+
} from "@intellectual-frontiers/core";
|
|
46
|
+
import { fromBase64, toBase64 } from "@intellectual-frontiers/formats/base64";
|
|
47
|
+
import { children, integer, readTlv, sequence, TAG } from "@intellectual-frontiers/formats/der";
|
|
48
|
+
import { sha256 } from "./sha256.ts";
|
|
49
|
+
|
|
50
|
+
/** The `_type` of an in-toto Statement v1. */
|
|
51
|
+
export const STATEMENT_TYPE = "https://in-toto.io/Statement/v1";
|
|
52
|
+
|
|
53
|
+
/** The DSSE payload type of an in-toto statement. */
|
|
54
|
+
export const INTOTO_PAYLOAD_TYPE = "application/vnd.in-toto+json";
|
|
55
|
+
|
|
56
|
+
/** An in-toto ResourceDescriptor as a statement's subject: its name, its digests by algorithm (`sha256`, ...) in lower-case hexadecimal, and what else is known of it. */
|
|
57
|
+
export type ResourceDescriptor = {
|
|
58
|
+
readonly name: string;
|
|
59
|
+
readonly digest: Readonly<Record<string, string>>;
|
|
60
|
+
readonly uri?: string;
|
|
61
|
+
readonly mediaType?: string;
|
|
62
|
+
readonly annotations?: Readonly<Record<string, unknown>>;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/** An in-toto Statement v1: a predicate of type `predicateType` that holds of the subjects. */
|
|
66
|
+
export type Statement<P> = {
|
|
67
|
+
readonly _type: typeof STATEMENT_TYPE;
|
|
68
|
+
readonly subject: readonly ResourceDescriptor[];
|
|
69
|
+
readonly predicateType: string;
|
|
70
|
+
readonly predicate: P;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/** A DSSE envelope: the payload in base64, its type, and the signatures (base64) over PAE(payloadType, payload). */
|
|
74
|
+
export type DsseEnvelope = {
|
|
75
|
+
readonly payload: string;
|
|
76
|
+
readonly payloadType: string;
|
|
77
|
+
readonly signatures: readonly { readonly keyid?: string; readonly sig: string }[];
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/** A key to sign with (a private key) or verify with (a public key), and the id that names it in an envelope, if any. */
|
|
81
|
+
export type DsseKey = { readonly key: CryptoKey; readonly keyid?: string };
|
|
82
|
+
|
|
83
|
+
/** A signature algorithm this module signs and verifies with, as read from a key. */
|
|
84
|
+
export type DsseAlgorithm =
|
|
85
|
+
| { readonly kind: "ed25519" }
|
|
86
|
+
| { readonly kind: "ecdsa"; readonly curve: "P-256" | "P-384" | "P-521" }
|
|
87
|
+
| { readonly kind: "rsa-pss"; readonly hash: "SHA-256" | "SHA-384" | "SHA-512" }
|
|
88
|
+
| { readonly kind: "rsassa-pkcs1-v1_5"; readonly hash: "SHA-256" | "SHA-384" | "SHA-512" };
|
|
89
|
+
|
|
90
|
+
/** Why a key cannot sign or verify: its place in the list given, and the reason. */
|
|
91
|
+
export type DsseKeyError = { readonly kind: "key"; readonly index: number; readonly reason: string };
|
|
92
|
+
|
|
93
|
+
/** Why an envelope was refused. */
|
|
94
|
+
export type DsseError =
|
|
95
|
+
| { readonly kind: "malformed"; readonly reason: string }
|
|
96
|
+
| { readonly kind: "payload-type"; readonly expected: string; readonly found: string }
|
|
97
|
+
| DsseKeyError
|
|
98
|
+
| { readonly kind: "no-valid-signature"; readonly signatures: number; readonly verified: number; readonly threshold: number };
|
|
99
|
+
|
|
100
|
+
/** Why a signed statement was refused: the envelope's error, or a payload that is not an in-toto statement with the predicate expected. */
|
|
101
|
+
export type StatementError = DsseError | { readonly kind: "statement"; readonly error: DecodeError };
|
|
102
|
+
|
|
103
|
+
/** What a verified envelope carries: its payload type, its payload, and the keys that verified a signature. */
|
|
104
|
+
export type Verified = { readonly payloadType: string; readonly payload: Uint8Array; readonly keys: readonly DsseKey[] };
|
|
105
|
+
|
|
106
|
+
const utf8 = new TextEncoder();
|
|
107
|
+
|
|
108
|
+
/** A subject: the name, and the SHA-256 of the bytes; `more` adds a URI, a media type or annotations. */
|
|
109
|
+
export async function subject(
|
|
110
|
+
name: string,
|
|
111
|
+
bytes: Uint8Array,
|
|
112
|
+
more: { readonly uri?: string; readonly mediaType?: string; readonly annotations?: Readonly<Record<string, unknown>> } = {},
|
|
113
|
+
): Promise<ResourceDescriptor> {
|
|
114
|
+
return { name, digest: { sha256: await sha256(bytes) }, ...more };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** A statement of the predicate about the subjects. */
|
|
118
|
+
export function statement<P>(subjects: readonly ResourceDescriptor[], predicateType: string, predicate: P): Statement<P> {
|
|
119
|
+
return { _type: STATEMENT_TYPE, subject: subjects, predicateType, predicate };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const lowerHex: Decoder<string> = (input, path = "$") =>
|
|
123
|
+
typeof input === "string" && /^(?:[0-9a-f]{2})+$/.test(input)
|
|
124
|
+
? ok(input)
|
|
125
|
+
: err({ kind: "decode", path, expected: "lower-case hexadecimal", found: describe(input) });
|
|
126
|
+
|
|
127
|
+
const statementType: Decoder<typeof STATEMENT_TYPE> = (input, path = "$") =>
|
|
128
|
+
input === STATEMENT_TYPE ? ok(STATEMENT_TYPE) : err({ kind: "decode", path, expected: STATEMENT_TYPE, found: describe(input) });
|
|
129
|
+
|
|
130
|
+
/** The decoder of a ResourceDescriptor with a name and digests. */
|
|
131
|
+
export const resourceDescriptorDecoder: Decoder<ResourceDescriptor> = object(
|
|
132
|
+
{ name: string, digest: record(lowerHex) },
|
|
133
|
+
{ uri: string, mediaType: string, annotations: record(unknownValue) },
|
|
134
|
+
);
|
|
135
|
+
|
|
136
|
+
/** The decoder of an in-toto Statement v1 whose predicate `predicate` decodes. */
|
|
137
|
+
export function statementDecoder<P>(predicate: Decoder<P>): Decoder<Statement<P>> {
|
|
138
|
+
return object({ _type: statementType, subject: array(resourceDescriptorDecoder), predicateType: string, predicate });
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const base64Text: Decoder<string> = (input, path = "$") =>
|
|
142
|
+
typeof input === "string" && fromBase64(input).kind === "ok"
|
|
143
|
+
? ok(input)
|
|
144
|
+
: err({ kind: "decode", path, expected: "standard base64", found: describe(input) });
|
|
145
|
+
|
|
146
|
+
/** The decoder of a DSSE envelope: its fields present, and the payload and signatures in base64. */
|
|
147
|
+
export const envelopeDecoder: Decoder<DsseEnvelope> = object({
|
|
148
|
+
payload: base64Text,
|
|
149
|
+
payloadType: string,
|
|
150
|
+
signatures: array(object({ sig: base64Text }, { keyid: string })),
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
/** A DSSE envelope read from JSON text, or why it is not one. */
|
|
154
|
+
export function parseEnvelope(text: string): Result<DsseEnvelope, DsseError> {
|
|
155
|
+
const r = json(text, envelopeDecoder);
|
|
156
|
+
return r.kind === "ok" ? r : err({ kind: "malformed", reason: formatDecodeError(r.error) });
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** DSSE's pre-authentication encoding: `DSSEv1 <len(type)> <type> <len(payload)> <payload>`, the lengths in bytes as ASCII decimal. */
|
|
160
|
+
export function pae(payloadType: string, payload: Uint8Array): Uint8Array<ArrayBuffer> {
|
|
161
|
+
const type = utf8.encode(payloadType);
|
|
162
|
+
const head = utf8.encode(`DSSEv1 ${type.length} ${payloadType} ${payload.length} `);
|
|
163
|
+
const out = new Uint8Array(head.length + payload.length);
|
|
164
|
+
out.set(head);
|
|
165
|
+
out.set(payload, head.length);
|
|
166
|
+
return out;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const HASHES = ["SHA-256", "SHA-384", "SHA-512"] as const;
|
|
170
|
+
const CURVES = ["P-256", "P-384", "P-521"] as const;
|
|
171
|
+
|
|
172
|
+
function hashOf(algorithm: KeyAlgorithm): (typeof HASHES)[number] | undefined {
|
|
173
|
+
const hash: unknown = "hash" in algorithm ? algorithm.hash : undefined;
|
|
174
|
+
const name: unknown = typeof hash === "object" && hash !== null && "name" in hash ? hash.name : undefined;
|
|
175
|
+
return HASHES.find((h) => h === name);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** The signature algorithm of a key, or the reason it is not one this module uses. */
|
|
179
|
+
export function signatureAlgorithm(key: CryptoKey): Result<DsseAlgorithm, string> {
|
|
180
|
+
const a = key.algorithm;
|
|
181
|
+
switch (a.name) {
|
|
182
|
+
case "Ed25519":
|
|
183
|
+
return ok({ kind: "ed25519" });
|
|
184
|
+
case "ECDSA": {
|
|
185
|
+
const named: unknown = "namedCurve" in a ? a.namedCurve : undefined;
|
|
186
|
+
const curve = CURVES.find((c) => c === named);
|
|
187
|
+
return curve === undefined ? err(`the curve ${String(named)} is not one of ${CURVES.join(", ")}`) : ok({ kind: "ecdsa", curve });
|
|
188
|
+
}
|
|
189
|
+
case "RSA-PSS":
|
|
190
|
+
case "RSASSA-PKCS1-v1_5": {
|
|
191
|
+
const hash = hashOf(a);
|
|
192
|
+
if (hash === undefined) return err(`the key's hash is not one of ${HASHES.join(", ")}`);
|
|
193
|
+
return ok(a.name === "RSA-PSS" ? { kind: "rsa-pss", hash } : { kind: "rsassa-pkcs1-v1_5", hash });
|
|
194
|
+
}
|
|
195
|
+
default:
|
|
196
|
+
return err(`${a.name} is not a signature algorithm DSSE is used with here`);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const CURVE_BYTES = { "P-256": 32, "P-384": 48, "P-521": 66 } as const;
|
|
201
|
+
const CURVE_HASH = { "P-256": "SHA-256", "P-384": "SHA-384", "P-521": "SHA-512" } as const;
|
|
202
|
+
const HASH_BYTES = { "SHA-256": 32, "SHA-384": 48, "SHA-512": 64 } as const;
|
|
203
|
+
|
|
204
|
+
function webCryptoParams(a: DsseAlgorithm): AlgorithmIdentifier | EcdsaParams | RsaPssParams {
|
|
205
|
+
switch (a.kind) {
|
|
206
|
+
case "ed25519":
|
|
207
|
+
return { name: "Ed25519" };
|
|
208
|
+
case "ecdsa":
|
|
209
|
+
return { name: "ECDSA", hash: CURVE_HASH[a.curve] };
|
|
210
|
+
case "rsa-pss":
|
|
211
|
+
return { name: "RSA-PSS", saltLength: HASH_BYTES[a.hash] };
|
|
212
|
+
case "rsassa-pkcs1-v1_5":
|
|
213
|
+
return { name: "RSASSA-PKCS1-v1_5" };
|
|
214
|
+
default:
|
|
215
|
+
return absurd(a);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Web Crypto's ECDSA signature (r and s, each `n` bytes) as an ASN.1 DER SEQUENCE of two INTEGERs. */
|
|
220
|
+
function ecdsaToDer(raw: Uint8Array, n: number): Uint8Array {
|
|
221
|
+
return sequence(integer(raw.subarray(0, n)), integer(raw.subarray(n, 2 * n)));
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** An ASN.1 DER ECDSA signature as Web Crypto's r and s of `n` bytes each, or undefined where it is not one. */
|
|
225
|
+
function ecdsaFromDer(der: Uint8Array, n: number): Uint8Array<ArrayBuffer> | undefined {
|
|
226
|
+
const t = readTlv(der);
|
|
227
|
+
if (t.kind === "err" || t.value.tag !== TAG.sequence || t.value.raw.length !== der.length) return undefined;
|
|
228
|
+
const parts = children(t.value.content);
|
|
229
|
+
if (parts.kind === "err" || parts.value.length !== 2) return undefined;
|
|
230
|
+
const out = new Uint8Array(2 * n);
|
|
231
|
+
for (const [i, part] of parts.value.entries()) {
|
|
232
|
+
if (part.tag !== TAG.integer || ((part.content[0] ?? 0x80) & 0x80) !== 0) return undefined;
|
|
233
|
+
const magnitude = part.content[0] === 0 ? part.content.subarray(1) : part.content;
|
|
234
|
+
if (magnitude.length > n) return undefined;
|
|
235
|
+
out.set(magnitude, (i + 1) * n - magnitude.length);
|
|
236
|
+
}
|
|
237
|
+
return out;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** The payload of the type signed by every key given (private keys), in an envelope; or the first key that cannot sign. */
|
|
241
|
+
export async function signEnvelope(
|
|
242
|
+
payloadType: string,
|
|
243
|
+
payload: Uint8Array,
|
|
244
|
+
keys: readonly DsseKey[],
|
|
245
|
+
): Promise<Result<DsseEnvelope, DsseKeyError>> {
|
|
246
|
+
const message = pae(payloadType, payload);
|
|
247
|
+
const signatures: { readonly keyid?: string; readonly sig: string }[] = [];
|
|
248
|
+
for (const [index, k] of keys.entries()) {
|
|
249
|
+
const a = signatureAlgorithm(k.key);
|
|
250
|
+
if (a.kind === "err") return err({ kind: "key", index, reason: a.error });
|
|
251
|
+
let raw: Uint8Array;
|
|
252
|
+
try {
|
|
253
|
+
raw = new Uint8Array(await crypto.subtle.sign(webCryptoParams(a.value), k.key, message));
|
|
254
|
+
} catch (e) {
|
|
255
|
+
return err({ kind: "key", index, reason: e instanceof Error ? e.message : String(e) });
|
|
256
|
+
}
|
|
257
|
+
const sig = a.value.kind === "ecdsa" ? ecdsaToDer(raw, CURVE_BYTES[a.value.curve]) : raw;
|
|
258
|
+
signatures.push(k.keyid === undefined ? { sig: toBase64(sig) } : { keyid: k.keyid, sig: toBase64(sig) });
|
|
259
|
+
}
|
|
260
|
+
return ok({ payload: toBase64(payload), payloadType, signatures });
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* The payload of an envelope whose type is `payloadType` and which at least `threshold` of the keys given (public keys, 1 by default)
|
|
265
|
+
* each verify a signature of. A signature that names a key id is tried only with the keys of that id or of none.
|
|
266
|
+
*/
|
|
267
|
+
export async function verifyEnvelope(
|
|
268
|
+
envelope: DsseEnvelope,
|
|
269
|
+
payloadType: string,
|
|
270
|
+
keys: readonly DsseKey[],
|
|
271
|
+
threshold = 1,
|
|
272
|
+
): Promise<Result<Verified, DsseError>> {
|
|
273
|
+
if (envelope.payloadType !== payloadType) return err({ kind: "payload-type", expected: payloadType, found: envelope.payloadType });
|
|
274
|
+
const payload = fromBase64(envelope.payload);
|
|
275
|
+
if (payload.kind === "err") return err({ kind: "malformed", reason: `the payload: ${payload.error}` });
|
|
276
|
+
const signatures: Uint8Array[] = [];
|
|
277
|
+
for (const [i, s] of envelope.signatures.entries()) {
|
|
278
|
+
const sig = fromBase64(s.sig);
|
|
279
|
+
if (sig.kind === "err") return err({ kind: "malformed", reason: `signature ${i}: ${sig.error}` });
|
|
280
|
+
signatures.push(sig.value);
|
|
281
|
+
}
|
|
282
|
+
const algorithms: DsseAlgorithm[] = [];
|
|
283
|
+
for (const [index, k] of keys.entries()) {
|
|
284
|
+
const a = signatureAlgorithm(k.key);
|
|
285
|
+
if (a.kind === "err") return err({ kind: "key", index, reason: a.error });
|
|
286
|
+
algorithms.push(a.value);
|
|
287
|
+
}
|
|
288
|
+
const message = pae(envelope.payloadType, payload.value);
|
|
289
|
+
const verifiedBy: DsseKey[] = [];
|
|
290
|
+
for (const [index, k] of keys.entries()) {
|
|
291
|
+
const a = algorithms[index];
|
|
292
|
+
if (a === undefined) continue;
|
|
293
|
+
for (const [i, s] of envelope.signatures.entries()) {
|
|
294
|
+
const bytes = signatures[i];
|
|
295
|
+
if (bytes === undefined || (s.keyid !== undefined && k.keyid !== undefined && s.keyid !== k.keyid)) continue;
|
|
296
|
+
const sig = a.kind === "ecdsa" ? ecdsaFromDer(bytes, CURVE_BYTES[a.curve]) : new Uint8Array(bytes);
|
|
297
|
+
if (sig === undefined) continue;
|
|
298
|
+
let valid: boolean;
|
|
299
|
+
try {
|
|
300
|
+
valid = await crypto.subtle.verify(webCryptoParams(a), k.key, sig, message);
|
|
301
|
+
} catch (e) {
|
|
302
|
+
return err({ kind: "key", index, reason: e instanceof Error ? e.message : String(e) });
|
|
303
|
+
}
|
|
304
|
+
if (valid) {
|
|
305
|
+
verifiedBy.push(k);
|
|
306
|
+
break;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
const needed = Math.max(1, threshold);
|
|
311
|
+
if (verifiedBy.length < needed) {
|
|
312
|
+
return err({ kind: "no-valid-signature", signatures: envelope.signatures.length, verified: verifiedBy.length, threshold: needed });
|
|
313
|
+
}
|
|
314
|
+
return ok({ payloadType: envelope.payloadType, payload: payload.value, keys: verifiedBy });
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** A statement as JSON, signed by every key given, in an envelope of type `application/vnd.in-toto+json`. */
|
|
318
|
+
export function signStatement<P>(s: Statement<P>, keys: readonly DsseKey[]): Promise<Result<DsseEnvelope, DsseKeyError>> {
|
|
319
|
+
return signEnvelope(INTOTO_PAYLOAD_TYPE, utf8.encode(JSON.stringify(s)), keys);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** The statement an envelope of type `application/vnd.in-toto+json` carries, verified as `verifyEnvelope` does, its predicate decoded by `predicate`. */
|
|
323
|
+
export async function verifyStatement<P>(
|
|
324
|
+
envelope: DsseEnvelope,
|
|
325
|
+
keys: readonly DsseKey[],
|
|
326
|
+
predicate: Decoder<P>,
|
|
327
|
+
threshold = 1,
|
|
328
|
+
): Promise<Result<Statement<P>, StatementError>> {
|
|
329
|
+
const v = await verifyEnvelope(envelope, INTOTO_PAYLOAD_TYPE, keys, threshold);
|
|
330
|
+
if (v.kind === "err") return v;
|
|
331
|
+
let text: string;
|
|
332
|
+
try {
|
|
333
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(v.value.payload);
|
|
334
|
+
} catch {
|
|
335
|
+
return err({ kind: "statement", error: { kind: "decode", path: "$", expected: "UTF-8 text", found: "bytes that are not" } });
|
|
336
|
+
}
|
|
337
|
+
const s = json(text, statementDecoder(predicate));
|
|
338
|
+
return s.kind === "ok" ? s : err({ kind: "statement", error: s.error });
|
|
339
|
+
}
|
package/src/md5.ts
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// Spec: 0001-crypto FR-002
|
|
2
|
+
/**
|
|
3
|
+
* MD5 (RFC 1321), which Web Crypto does not give, for the protocols that still ask for it: S3's `Content-MD5` header (the digest in
|
|
4
|
+
* base64), the ETag of an S3 object put in one part, and old checksum files (commons 0001-crypto FR-002).
|
|
5
|
+
*
|
|
6
|
+
* MD5 is NOT for security: collisions are made in seconds, so it MUST NOT check that bytes are the ones expected against anyone who
|
|
7
|
+
* could choose them, sign, or hash a password. Use SHA-256 (`./sha256.ts`) for that; MD5 here only answers a protocol that names it.
|
|
8
|
+
*
|
|
9
|
+
* The digest is given whole (`md5`, `md5Hex`) or a piece at a time (`Md5`, and `md5Stream` for a `ReadableStream`), so a file larger
|
|
10
|
+
* than memory is digested as it is read.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { Md5, md5Hex } from "./md5.ts";
|
|
15
|
+
* md5Hex("abc"); // "900150983cd24fb0d6963f7d28e17f72"
|
|
16
|
+
* new Md5().update("a").update("bc").hex(); // the same
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* @module
|
|
20
|
+
*/
|
|
21
|
+
import { toHex } from "@intellectual-frontiers/formats/hex";
|
|
22
|
+
|
|
23
|
+
/** The per-round left rotations of RFC 1321 §3.4. */
|
|
24
|
+
const SHIFTS: readonly number[] = [
|
|
25
|
+
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11,
|
|
26
|
+
16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
|
|
27
|
+
];
|
|
28
|
+
|
|
29
|
+
/** T[i] = floor(2^32 * |sin(i + 1)|), the table of RFC 1321 §3.4. */
|
|
30
|
+
const T: readonly number[] = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 0x100000000) >>> 0);
|
|
31
|
+
|
|
32
|
+
const bytesOf = (data: Uint8Array | string): Uint8Array => (typeof data === "string" ? new TextEncoder().encode(data) : data);
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* An MD5 digest computed a piece at a time: `update` with each piece of the bytes in order (text is taken as UTF-8), then `digest` or
|
|
36
|
+
* `hex`. After the digest is taken, the object takes no more bytes. Not for security (see the module's documentation).
|
|
37
|
+
*/
|
|
38
|
+
export class Md5 {
|
|
39
|
+
#state = new Uint32Array([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]);
|
|
40
|
+
#block = new Uint8Array(64);
|
|
41
|
+
#words = new Uint32Array(16);
|
|
42
|
+
#filled = 0;
|
|
43
|
+
#length = 0;
|
|
44
|
+
#done: Uint8Array | undefined;
|
|
45
|
+
|
|
46
|
+
/** Takes the next piece of the bytes; throws where the digest was already taken. */
|
|
47
|
+
update(data: Uint8Array | string): this {
|
|
48
|
+
if (this.#done !== undefined) throw new Error("the MD5 digest was already taken; start a new Md5");
|
|
49
|
+
const bytes = bytesOf(data);
|
|
50
|
+
this.#length += bytes.length;
|
|
51
|
+
let at = 0;
|
|
52
|
+
while (at < bytes.length) {
|
|
53
|
+
const n = Math.min(64 - this.#filled, bytes.length - at);
|
|
54
|
+
this.#block.set(bytes.subarray(at, at + n), this.#filled);
|
|
55
|
+
this.#filled += n;
|
|
56
|
+
at += n;
|
|
57
|
+
if (this.#filled === 64) {
|
|
58
|
+
this.#compress();
|
|
59
|
+
this.#filled = 0;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return this;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The 16 bytes of the digest of every piece taken; the same each time it is asked. */
|
|
66
|
+
digest(): Uint8Array {
|
|
67
|
+
if (this.#done !== undefined) return this.#done.slice();
|
|
68
|
+
const bits = this.#length * 8;
|
|
69
|
+
const pad = new Uint8Array((this.#filled < 56 ? 56 : 120) - this.#filled + 8);
|
|
70
|
+
pad[0] = 0x80;
|
|
71
|
+
const view = new DataView(pad.buffer);
|
|
72
|
+
view.setUint32(pad.length - 8, bits >>> 0, true);
|
|
73
|
+
view.setUint32(pad.length - 4, Math.floor(bits / 0x100000000) >>> 0, true);
|
|
74
|
+
this.update(pad);
|
|
75
|
+
const out = new Uint8Array(16);
|
|
76
|
+
const outView = new DataView(out.buffer);
|
|
77
|
+
this.#state.forEach((w, i) => outView.setUint32(i * 4, w, true));
|
|
78
|
+
this.#done = out;
|
|
79
|
+
return out.slice();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The digest as 32 lower-case hexadecimal digits. */
|
|
83
|
+
hex(): string {
|
|
84
|
+
return toHex(this.digest());
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
#compress(): void {
|
|
88
|
+
const x = this.#words;
|
|
89
|
+
const b64 = this.#block;
|
|
90
|
+
for (let i = 0; i < 16; i++)
|
|
91
|
+
x[i] = ((b64[i * 4] ?? 0) | ((b64[i * 4 + 1] ?? 0) << 8) | ((b64[i * 4 + 2] ?? 0) << 16) | ((b64[i * 4 + 3] ?? 0) << 24)) >>> 0;
|
|
92
|
+
const s = this.#state;
|
|
93
|
+
let a = s[0] ?? 0;
|
|
94
|
+
let b = s[1] ?? 0;
|
|
95
|
+
let c = s[2] ?? 0;
|
|
96
|
+
let d = s[3] ?? 0;
|
|
97
|
+
for (let i = 0; i < 64; i++) {
|
|
98
|
+
let f: number;
|
|
99
|
+
let g: number;
|
|
100
|
+
if (i < 16) {
|
|
101
|
+
f = (b & c) | (~b & d);
|
|
102
|
+
g = i;
|
|
103
|
+
} else if (i < 32) {
|
|
104
|
+
f = (d & b) | (~d & c);
|
|
105
|
+
g = (5 * i + 1) % 16;
|
|
106
|
+
} else if (i < 48) {
|
|
107
|
+
f = b ^ c ^ d;
|
|
108
|
+
g = (3 * i + 5) % 16;
|
|
109
|
+
} else {
|
|
110
|
+
f = c ^ (b | ~d);
|
|
111
|
+
g = (7 * i) % 16;
|
|
112
|
+
}
|
|
113
|
+
const sum = (a + f + (T[i] ?? 0) + (x[g] ?? 0)) >>> 0;
|
|
114
|
+
const r = SHIFTS[i] ?? 0;
|
|
115
|
+
a = d;
|
|
116
|
+
d = c;
|
|
117
|
+
c = b;
|
|
118
|
+
b = (b + ((sum << r) | (sum >>> (32 - r)))) >>> 0;
|
|
119
|
+
}
|
|
120
|
+
s[0] = ((s[0] ?? 0) + a) >>> 0;
|
|
121
|
+
s[1] = ((s[1] ?? 0) + b) >>> 0;
|
|
122
|
+
s[2] = ((s[2] ?? 0) + c) >>> 0;
|
|
123
|
+
s[3] = ((s[3] ?? 0) + d) >>> 0;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The 16 bytes of the MD5 of bytes, or of text as UTF-8. Not for security. */
|
|
128
|
+
export function md5(data: Uint8Array | string): Uint8Array {
|
|
129
|
+
return new Md5().update(data).digest();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The MD5 of bytes, or of text as UTF-8, as 32 lower-case hexadecimal digits (`md5("")` is `d41d8cd98f00b204e9800998ecf8427e`). */
|
|
133
|
+
export function md5Hex(data: Uint8Array | string): string {
|
|
134
|
+
return toHex(md5(data));
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The 16 bytes of the MD5 of every byte of a stream, read a chunk at a time, so the whole is never held. Not for security. */
|
|
138
|
+
export async function md5Stream(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {
|
|
139
|
+
const h = new Md5();
|
|
140
|
+
const reader = stream.getReader();
|
|
141
|
+
try {
|
|
142
|
+
for (;;) {
|
|
143
|
+
const { done, value } = await reader.read();
|
|
144
|
+
if (done) return h.digest();
|
|
145
|
+
h.update(value);
|
|
146
|
+
}
|
|
147
|
+
} finally {
|
|
148
|
+
reader.releaseLock();
|
|
149
|
+
}
|
|
150
|
+
}
|
package/src/mod.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Spec: 0001-crypto FR-009
|
|
2
|
+
/**
|
|
3
|
+
* Crypto, the digests, signatures and envelopes of Intellectual Frontiers Commons, in pure code on Web Crypto with no outside package (its specification 0001-crypto): SHA-256 as a branded `Sha256`, MD5
|
|
4
|
+
* for the protocols that still ask for it (as `md5`), SHA-512 crypt, UUIDs (as `uuid`), AWS Signature Version 4 (as `sigv4`), CMS encrypted content (as `cms`), in-toto statements in DSSE envelopes
|
|
5
|
+
* (as `dsse`), COSE keys (as `cose`) and WebAuthn for a relying party (as `webauthn`). It depends on `core` and `formats`, names no host global and runs wherever ECMAScript and Web Crypto do: Bun, Node 26, a
|
|
6
|
+
* browser, a Worker.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* import { sha256 } from "@intellectual-frontiers/crypto";
|
|
11
|
+
* const sum = await sha256("abc");
|
|
12
|
+
* sum; // "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* @module
|
|
16
|
+
*/
|
|
17
|
+
export * as cms from "./cms.ts";
|
|
18
|
+
export * as cose from "./cose.ts";
|
|
19
|
+
export { CRYPT_ROUNDS, cryptSalt, sha512Crypt, verifySha512Crypt } from "./crypt.ts";
|
|
20
|
+
export * as dsse from "./dsse.ts";
|
|
21
|
+
export * as md5 from "./md5.ts";
|
|
22
|
+
export { parseSha256Sums, sameSha256, sha256, sha256Of } from "./sha256.ts";
|
|
23
|
+
export type { Sha256 } from "./sha256.ts";
|
|
24
|
+
export * as sigv4 from "./sigv4.ts";
|
|
25
|
+
export * as uuid from "./uuid.ts";
|
|
26
|
+
export * as webauthn from "./webauthn.ts";
|