-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathverify.js
More file actions
72 lines (49 loc) · 1.53 KB
/
verify.js
File metadata and controls
72 lines (49 loc) · 1.53 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const fs = require("fs")
const crypto = require("crypto")
const nacl = require("tweetnacl")
function sha256(data) {
return crypto.createHash("sha256").update(data).digest("hex")
}
function canonicalize(value) {
if (Array.isArray(value)) {
return `[${value.map(v => canonicalize(v)).join(",")}]`
}
if (value !== null && typeof value === "object") {
const keys = Object.keys(value).sort()
return `{${keys.map(k =>
JSON.stringify(k) + ":" + canonicalize(value[k])
).join(",")}}`
}
return JSON.stringify(value)
}
function verifyArtifact(path) {
const artifact = JSON.parse(fs.readFileSync(path))
const signature = artifact.signature
const sigValue = Buffer.from(signature.value, "base64")
const pubKey = Buffer.from(signature.public_key, "base64")
const artifactCopy = JSON.parse(JSON.stringify(artifact))
delete artifactCopy.signature
const canonical = canonicalize(artifactCopy)
const message = Buffer.from(canonical)
const hash = sha256(message)
if (hash !== artifact.artifact_id) {
console.log("Artifact hash mismatch")
return
}
const verified = nacl.sign.detached.verify(
message,
sigValue,
pubKey
)
if (!verified) {
console.log("Signature verification FAILED")
return
}
console.log("Artifact verification: VALID")
}
const file = process.argv[2]
if (!file) {
console.log("Usage: node verify.js artifact.json")
process.exit(1)
}
verifyArtifact(file)