package com.tanakahda;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
TODO
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class Ob3LdpOid4vpDemo {
static final ObjectMapper M = new ObjectMapper();
static class LdpCrypto {
private final KeyPair issuerKeyPair;
LdpCrypto(KeyPair kp) { this.issuerKeyPair = kp; }
public ObjectNode sign(ObjectNode unsignedVc, String verificationMethodDidUrl) throws Exception {
byte[] canonical = canonicalizeWithoutProof(unsignedVc);
byte[] sig = signBytes(canonical, issuerKeyPair.getPrivate());
ObjectNode proof = M.createObjectNode();
proof.put("type", "DataIntegrityProof");
proof.put("created", Instant.now().toString());
proof.put("proofPurpose", "assertionMethod");
proof.put("verificationMethod", verificationMethodDidUrl);
proof.put("cryptosuite", "eddsa-rdfc-2022");
proof.put("proofValue", Base64.getUrlEncoder().withoutPadding().encodeToString(sig));
ObjectNode signed = unsignedVc.deepCopy();
signed.set("proof", proof);
return signed;
}
public boolean verify(ObjectNode signedVc) throws Exception {
if (!signedVc.has("proof")) return false;
ObjectNode proof = (ObjectNode) signedVc.get("proof");
byte[] sig = Base64.getUrlDecoder().decode(proof.get("proofValue").asText());
ObjectNode copy = signedVc.deepCopy();
copy.remove("proof");
byte[] canonical = canonicalizeWithoutProof(copy);
return verifyBytes(canonical, sig, issuerKeyPair.getPublic());
}
private static byte[] canonicalizeWithoutProof(ObjectNode obj) throws Exception {
String normalized = sortJson(obj).toString();
return normalized.getBytes(StandardCharsets.UTF_8);
}
private static JsonNode sortJson(JsonNode node) {
if (node.isObject()) {
ObjectNode in = (ObjectNode) node;
ObjectNode out = M.createObjectNode();
List<String> names = new ArrayList<>();
in.fieldNames().forEachRemaining(names::add);
Collections.sort(names);
for (String name : names) {
if ("proof".equals(name)) continue;
out.set(name, sortJson(in.get(name)));
}
return out;
} else if (node.isArray()) {
ArrayNode in = (ArrayNode) node;
ArrayNode out = M.createArrayNode();
for (JsonNode item : in) out.add(sortJson(item));
return out;
} else {
return node;
}
}
private static byte[] signBytes(byte[] data, PrivateKey sk) throws Exception {
Signature s = Signature.getInstance("SHA256withRSA");
s.initSign(sk);
s.update(data);
return s.sign();
}
private static boolean verifyBytes(byte[] data, byte[] sig, PublicKey pk) throws Exception {
Signature s = Signature.getInstance("SHA256withRSA");
s.initVerify(pk);
s.update(data);
return s.verify(sig);
}
}
static class IssuerService {
private final String issuerDid;
private final String verificationMethod;
private final LdpCrypto ldp;
IssuerService(String issuerDid, String verificationMethod, LdpCrypto ldp) {
this.issuerDid = issuerDid;
this.verificationMethod = verificationMethod;
this.ldp = ldp;
}
public ObjectNode issueOb3Credential(String subjectDid, String achievementId) throws Exception {
ObjectNode vc = M.createObjectNode();
ArrayNode ctx = M.createArrayNode();
ctx.add("https://www.w3.org/ns/credentials/v2");
ctx.add("https://purl.imsglobal.org/spec/vc/ob/vocab.jsonld");
vc.set("@context", ctx);
ArrayNode types = M.createArrayNode();
types.add("VerifiableCredential");
types.add("OpenBadgeCredential");
vc.set("type", types);
ObjectNode issuer = M.createObjectNode();
issuer.put("id", issuerDid);
vc.set("issuer", issuer);
ObjectNode cs = M.createObjectNode();
cs.put("id", subjectDid);
cs.put("achievement", achievementId);
vc.set("credentialSubject", cs);
vc.put("validFrom", Instant.now().toString());
return ldp.sign(vc, verificationMethod);
}
}
static class WalletService {
private final List<ObjectNode> vcs = new ArrayList<>();
public void store(ObjectNode vc) { vcs.add(vc); }
public ObjectNode handleOid4vpRequest(ObjectNode vpRequest) {
String requiredType = vpRequest.at("/presentation_definition/input_descriptors/0/constraints/fields/0/filter/const").asText("OpenBadgeCredential");
Optional<ObjectNode> match = vcs.stream().filter(vc -> {
for (JsonNode t : vc.withArray("type")) {
if (t.asText().equals(requiredType)) return true;
}
return false;
}).findFirst();
if (match.isEmpty()) throw new RuntimeException("No matching VC in wallet");
ObjectNode vp = M.createObjectNode();
ArrayNode ctx = M.createArrayNode();
ctx.add("https://www.w3.org/ns/credentials/v2");
vp.set("@context", ctx);
ArrayNode types = M.createArrayNode();
types.add("VerifiablePresentation");
vp.set("type", types);
ArrayNode arr = M.createArrayNode();
arr.add(match.get());
vp.set("verifiableCredential", arr);
String nonce = vpRequest.path("nonce").asText(null);
if (nonce != null) vp.put("nonce", nonce);
return vp;
}
}
static class VerifierService {
private final Set<String> trustedIssuers;
private final LdpCrypto ldpForVerify;
VerifierService(Set<String> trustedIssuers, LdpCrypto ldpForVerify) {
this.trustedIssuers = trustedIssuers;
this.ldpForVerify = ldpForVerify;
}
public ObjectNode buildVpRequest(String requiredType, String nonce) {
ObjectNode req = M.createObjectNode();
ObjectNode pd = M.createObjectNode();
ArrayNode ids = M.createArrayNode();
ObjectNode id0 = M.createObjectNode();
ObjectNode constraints = M.createObjectNode();
ArrayNode fields = M.createArrayNode();
ObjectNode f0 = M.createObjectNode();
ObjectNode filter = M.createObjectNode();
f0.put("path", "$.type");
filter.put("const", requiredType);
f0.set("filter", filter);
fields.add(f0);
constraints.set("fields", fields);
id0.set("constraints", constraints);
ids.add(id0);
pd.set("input_descriptors", ids);
req.set("presentation_definition", pd);
req.put("nonce", nonce);
req.put("client_id", "https://verifier.example.org");
return req;
}
public boolean verifyVp(ObjectNode vp) throws Exception {
if (!vp.has("nonce")) return false;
ArrayNode vcs = (ArrayNode) vp.get("verifiableCredential");
if (vcs == null || vcs.isEmpty()) return false;
ObjectNode vc = (ObjectNode) vcs.get(0);
boolean sigOk = ldpForVerify.verify(vc);
if (!sigOk) return false;
String issuerId = vc.path("issuer").path("id").asText();
return trustedIssuers.contains(issuerId);
}
}
Main method
@param args
@throws Exception
public static void main(String[] args) throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair issuerKeys = kpg.generateKeyPair();
LdpCrypto ldp = new LdpCrypto(issuerKeys);
IssuerService issuer = new IssuerService(
"did:web:issuer.example.org",
"did:web:issuer.example.org#keys-1",
ldp
);
WalletService wallet = new WalletService();
VerifierService verifier = new VerifierService(
new HashSet<>(List.of("did:web:issuer.example.org")),
ldp
);
ObjectNode vc = issuer.issueOb3Credential(
"did:key:z6Mkwalletsubject",
"https://issuer.example.org/achievements/java-basic"
);
System.out.println("[Issuer] VC (signed):\n" + M.writerWithDefaultPrettyPrinter().writeValueAsString(vc));
wallet.store(vc);
ObjectNode vpReq = verifier.buildVpRequest("OpenBadgeCredential", UUID.randomUUID().toString());
System.out.println("\n[Verifier] VP Request (presentation_definition):\n" + M.writerWithDefaultPrettyPrinter().writeValueAsString(vpReq));
ObjectNode vp = wallet.handleOid4vpRequest(vpReq);
System.out.println("\n[Wallet] VP Response:\n" + M.writerWithDefaultPrettyPrinter().writeValueAsString(vp));
boolean ok = verifier.verifyVp(vp);
System.out.println("\n[Verifier] VP verification result: " + ok);
}
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlnsxsi="http://www.w3.org/2001/XMLSchema-instance" xsischemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>OB3-java-example</groupId>
<artifactId>OB3-java-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>23</release>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.17.1</version>
</dependency>
</dependencies>
</project>