-
Notifications
You must be signed in to change notification settings - Fork 85
/
6_sd_jwt.ts
209 lines (175 loc) · 7.97 KB
/
6_sd_jwt.ts
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
// Copyright 2020-2024 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
import {
Credential,
DecodedJwtCredential,
EdDSAJwsVerifier,
FailFast,
JwkMemStore,
JwsSignatureOptions,
JwsVerificationOptions,
JwtCredentialValidationOptions,
KeyBindingJwtClaims,
KeyBindingJWTValidationOptions,
KeyIdMemStore,
SdJwt,
SdJwtCredentialValidator,
SdObjectEncoder,
Storage,
Timestamp,
} from "@iota/identity-wasm/node";
import { Client, MnemonicSecretManager, Utils } from "@iota/sdk-wasm/node";
import { API_ENDPOINT, createDid } from "../util";
/**
* Demonstrates how to create a selective disclosure verifiable credential and validate it
* using the [Selective Disclosure for JWTs (SD-JWT)](https://www.ietf.org/archive/id/draft-ietf-oauth-selective-disclosure-jwt-07.html) specification.
*/
export async function sdJwt() {
// ===========================================================================
// Step 1: Create identities for the issuer and the holder.
// ===========================================================================
const client = new Client({
primaryNode: API_ENDPOINT,
localPow: true,
});
// Creates a new wallet and identity (see "0_create_did" example).
const issuerSecretManager: MnemonicSecretManager = {
mnemonic: Utils.generateMnemonic(),
};
const issuerStorage: Storage = new Storage(
new JwkMemStore(),
new KeyIdMemStore(),
);
let { document: issuerDocument, fragment: issuerFragment } = await createDid(
client,
issuerSecretManager,
issuerStorage,
);
// Create an identity for the holder, in this case also the subject.
const aliceSecretManager: MnemonicSecretManager = {
mnemonic: Utils.generateMnemonic(),
};
const aliceStorage: Storage = new Storage(
new JwkMemStore(),
new KeyIdMemStore(),
);
let { document: aliceDocument, fragment: aliceFragment } = await createDid(
client,
aliceSecretManager,
aliceStorage,
);
// ===========================================================================
// Step 2: Issuer creates and signs a selectively disclosable JWT verifiable credential.
// ===========================================================================
// Create an address credential subject.
const subject = {
id: aliceDocument.id(),
name: "Alice",
nationalities: ["DE", "US"],
address: {
locality: "Maxstadt",
postal_code: "12344",
country: "DE",
street_address: "Weidenstraße 22",
},
};
// Build credential using subject above and issuer.
const credential = new Credential({
id: "https://example.com/credentials/3732",
type: "AddressCredential",
issuer: issuerDocument.id(),
credentialSubject: subject,
});
// In Order to create an selective disclosure JWT, the plain text JWT
// claims set must be created first.
let payload = credential.toJwtClaims();
// The issuer can make all or subset of the claims selectively disclosable.
let encoder = new SdObjectEncoder(payload);
// Make "locality", "postal_code", "street_address" and the first entry of "nationalities"
// selectively disclosable while keeping other properties in plain text.
let disclosures = [
encoder.conceal("/vc/credentialSubject/address/locality"),
encoder.conceal("/vc/credentialSubject/address/postal_code"),
encoder.conceal("/vc/credentialSubject/address/street_address"),
encoder.conceal("/vc/credentialSubject/nationalities/1"),
];
// Add decoys in the credential top level, nationalities array and address object.
encoder.addDecoys("/vc/credentialSubject/nationalities", 3);
encoder.addDecoys("/vc", 4);
encoder.addDecoys("/vc/credentialSubject/address", 2);
// Add the `_sd_alg` property.
encoder.addSdAlgProperty();
console.log("Claims set with disclosure digests: ");
console.log(JSON.stringify(encoder.encodeToObject(), null, 2), "\n");
// Create the signed JWT.
const encodedPayload = encoder.encodeToString();
let jws = await issuerDocument.createJws(issuerStorage, issuerFragment, encodedPayload, new JwsSignatureOptions());
// ===========================================================================
// Step 3: Issuer sends the JWT and the disclosures to the holder.
// ===========================================================================
// One way to send the JWT and the disclosures, is by creating an SD-JWT with all the
// disclosures.
const strDisclosures = disclosures.map(disclosure => disclosure.toEncodedString());
let sdJwt = new SdJwt(jws.toString(), strDisclosures).presentation();
// ===========================================================================
// Step 4: Verifier sends the holder a challenge and requests a signed Verifiable Presentation.
// ===========================================================================
const VERIFIER_DID = "did:example:verifier";
// A unique random challenge generated by the requester per presentation can mitigate replay attacks.
let nonce = "475a7984-1bb5-4c4c-a56f-822bccd46440";
// ===========================================================================
// Step 5: Holder creates an SD-JWT to be presented to a verifier.
// ===========================================================================
const sdJwtReceived = SdJwt.parse(sdJwt);
// The holder only wants to present "locality" and "postal_code" but not "street_address" or the "US" nationality.
const receivedDisclosures = sdJwtReceived.disclosures();
const toBeDisclosed = [
receivedDisclosures[0],
receivedDisclosures[1],
];
// Optionally, the holder can add a Key Binding JWT (KB-JWT). This is dependent on the verifier's policy.
// Issuing the KB-JWT is done by creating the claims set and setting the header `typ` value
// with the help of `KeyBindingJwtClaims`.
const bindingClaims = new KeyBindingJwtClaims(
sdJwtReceived.jwt(),
toBeDisclosed,
nonce,
VERIFIER_DID,
Timestamp.nowUTC(),
);
// Setting the `typ` in the header is required.
const options = new JwsSignatureOptions({
typ: KeyBindingJwtClaims.keyBindingJwtHeaderTyp(),
});
const kbJwt = await aliceDocument.createJws(aliceStorage, aliceFragment, bindingClaims.toString(), options);
// Create the final SD-JWT.
let sdJwtWithKb = new SdJwt(sdJwtReceived.jwt().toString(), toBeDisclosed, kbJwt.toString());
// ===========================================================================
// Step 6: Holder presents the SD-JWT to the verifier.
// ===========================================================================
let sdJwtPresentation = sdJwtWithKb.presentation();
// ===========================================================================
// Step 7: Verifier receives the SD-JWT and verifies it.
// ===========================================================================
const sdJwtObj = SdJwt.parse(sdJwtPresentation);
// Verify the JWT.
let validator = new SdJwtCredentialValidator(new EdDSAJwsVerifier());
let decodedCredential: DecodedJwtCredential = validator.validateCredential(
sdJwtObj,
issuerDocument,
new JwtCredentialValidationOptions(),
FailFast.FirstError,
);
console.log("JWT successfully validated");
console.log("Decoded credential: \n", decodedCredential.credential());
// Verify the Key Binding JWT.
let kbValidationOptions = new KeyBindingJWTValidationOptions(
{
aud: VERIFIER_DID,
nonce: nonce,
jwsOptions: new JwsVerificationOptions(),
},
);
validator.validateKeyBindingJwt(sdJwtObj, aliceDocument, kbValidationOptions);
console.log("Key Binding JWT successfully validated");
}