Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat : HCX-964 Implement QR Code Generation #614

Open
wants to merge 25 commits into
base: sprint-55
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions hcx-qr-code-generator/pom.xml
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maintain an order when you add dependencies to a POM file.

  • Modules implemented within the project.
  • External dependencies.
  • Test dependencies.

Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.swasth</groupId>
<artifactId>hcx-platform</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>

<artifactId>hcx-qr-code-generator</artifactId>
<packaging>jar</packaging>

<name>hcx-qr-code-generator</name>
<url>http://maven.apache.org</url>

<properties>
<java.target.runtime>17</java.target.runtime>
</properties>

<dependencies>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
<dependency>
<groupId>org.swasth</groupId>
<artifactId>hcx-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<source>${java.target.runtime}</source>
<target>${java.target.runtime}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.7</version>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>default-report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.1</version>
</plugin>
</plugins>
</build>
</project>
140 changes: 140 additions & 0 deletions hcx-qr-code-generator/src/main/java/org/swasth/HcxQRCodeGenerator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
package org.swasth;

import com.google.gson.Gson;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.IOUtils;
import org.swasth.service.EncDeCode;
import org.swasth.utils.JWSUtils;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HcxQRCodeGenerator {
private static int width;
private static int height;
private static String privatekey;

static {
try {
loadConfig();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

private static void loadConfig() {
Yaml yaml = new Yaml();
try (InputStream inputStream = HcxQRCodeGenerator.class.getResourceAsStream("/application.yml")) {
Map<String, Object> config = yaml.load(inputStream);
Map<String, Object> qrCodeConfig = (Map<String, Object>) config.get("qr_code");
width = parseWidthHeight((String) qrCodeConfig.get("width"));
height = parseWidthHeight((String) qrCodeConfig.get("height"));
privatekey = resolvePlaceholder((String) qrCodeConfig.get("private_key"));
}catch (Exception e){
System.out.println(e.getMessage());
}
}

private static int parseWidthHeight(String value) {
if (value.startsWith("${") && value.endsWith("}")) {
Pattern pattern = Pattern.compile("\\$\\{(.+?):(\\d+)}");
Matcher matcher = pattern.matcher(value);
if (matcher.find()) {
return Integer.parseInt(matcher.group(2));
}
}
return Integer.parseInt(value);
}

private static String resolvePlaceholder(String value) {
if (value.startsWith("${") && value.endsWith("}")) {
int colonIndex = value.indexOf(':');
if (colonIndex != -1) {
return value.substring(colonIndex + 1, value.length() - 1);
}
}
return value;
}

public static void main(String[] args) throws TemplateException, IOException, NoSuchAlgorithmException, InvalidKeySpecException, WriterException, URISyntaxException {
if (args.length > 0) {
String json = args[0];
Gson gson = new Gson();
Map<String, Object> map = gson.fromJson(json, HashMap.class);
System.out.println("Map received from command line argument:");
String certificate = IOUtils.toString(new URI(privatekey), StandardCharsets.UTF_8);
generateQrToken((Map<String, Object>) map.get("payload"), certificate);
} else {
System.out.println("No input to process");
}
}

private static String getPrivateKey(String privateKey) {
privateKey = privateKey
.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "")
.replaceAll("\\s+", "");
return privateKey;
}

private static String generateQrToken(Map<String, Object> requestBody, String privateKey) throws TemplateException, IOException, WriterException, NoSuchAlgorithmException, InvalidKeySpecException {
Map<String, Object> headers = new HashMap<>();
String jwsToken = JWSUtils.generate(headers, requestBody, HcxQRCodeGenerator.getPrivateKey(privateKey));
String participantCode = null;
if (requestBody.containsKey("participantCode")) {
participantCode = (String) requestBody.get("participantCode");
}
System.out.println("QR Token generated");
String payload = createVerifiableCredential(requestBody, jwsToken);
generateQRCode(EncDeCode.encodePayload(payload), participantCode);
return payload;
}
private static final DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
private static String createVerifiableCredential(Map<String, Object> payload, String proofValue) throws IOException, TemplateException {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
cfg.setClassForTemplateLoading(HcxQRCodeGenerator.class, "/templates");
Template template = cfg.getTemplate("verifiable-credential.ftl");
LocalDateTime issuanceDate = LocalDateTime.now();
LocalDateTime expirationDate = LocalDateTime.now().plusYears(1);
Map<String, Object> data = new HashMap<>();
data.put("issuanceDate", formatter.format(issuanceDate));
data.put("expirationDate", formatter.format(expirationDate));
data.put("subjectId", UUID.randomUUID());
data.put("payload", new Gson().toJson(payload));
data.put("proofCreated", LocalDateTime.now());
data.put("proofValue", proofValue);
StringWriter out = new StringWriter();
template.process(data, out);
return out.toString();
}

private static void generateQRCode(String content, String participantCode) throws WriterException, IOException {
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix matrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height);
String currentDir = System.getProperty("user.dir");
Path path = FileSystems.getDefault().getPath(currentDir + "/" + participantCode + "_qr_code_" + System.currentTimeMillis() + ".png");
MatrixToImageWriter.writeToPath(matrix, "PNG", path);
System.out.println("QR code image generated and saved to: " + path.toAbsolutePath());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package org.swasth.service;

import com.fasterxml.jackson.core.JsonProcessingException;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

import static org.swasth.common.utils.JSONUtils.deserialize;

public class EncDeCode {

public static String encodePayload(String payload) {
String base64EncodedSignature = Base64.getEncoder().encodeToString(payload.getBytes());
System.out.println("Encoded Payload");
return base64EncodedSignature;
}

public static Map<String,Object> decodePayload(String payload) throws JsonProcessingException {
byte[] decodedBytes = Base64.getDecoder().decode(payload);
String decodedString = new String(decodedBytes, StandardCharsets.UTF_8);
Map<String,Object> decode = deserialize(decodedString, Map.class);
return decode;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package org.swasth.service;

import org.apache.commons.io.IOUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.Base64;
import java.util.Map;

public class VerifyQrCode {

public static Map<String, Object> getToken(Map<String, Object> payload) throws CertificateException, IOException, NoSuchAlgorithmException, SignatureException, InvalidKeyException {
String publicKeyUrl = "https://raw.githubusercontent.com/Swasth-Digital-Health-Foundation/hcx-platform/main/hcx-apis/src/test/resources/examples/test-keys/public-key.pem";
Map<String, Object> token = (Map<String, Object>) payload.get("proof");
if (token.containsKey("proofValue")) {
String jwsToken = (String) token.get("proofValue");
boolean isSignatureValid = isValidSignature(jwsToken, publicKeyUrl);
System.out.println(isSignatureValid + " Valid Signature");
} else System.out.println("proofValue is empty or null");
return token;
}

public static boolean isValidSignature(String payload, String publicKeyUrl) throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
String certificate = IOUtils.toString(new URL(publicKeyUrl), StandardCharsets.UTF_8.toString());
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream stream = new ByteArrayInputStream(certificate.getBytes());
Certificate cert = cf.generateCertificate(stream);
PublicKey publicKey = cert.getPublicKey();
String[] parts = payload.split("\\.");
String data = parts[0] + "." + parts[1];
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initVerify(publicKey);
sig.update(data.getBytes());
byte[] decodedSignature = Base64.getUrlDecoder().decode(parts[2]);
return sig.verify(decodedSignature);
}

}
21 changes: 21 additions & 0 deletions hcx-qr-code-generator/src/main/java/org/swasth/utils/JWSUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package org.swasth.utils;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.Map;

public class JWSUtils {
public static String generate(Map<String, Object> headers, Map<String, Object> payload, String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
byte[] privateKeyDecoded = Base64.getDecoder().decode(privateKey);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKeyDecoded);
PrivateKey rsaPrivateKey = KeyFactory.getInstance("RSA").generatePrivate(spec);
return Jwts.builder().setHeader(headers).setClaims(payload).signWith(SignatureAlgorithm.RS256, rsaPrivateKey).compact();
}
}
4 changes: 4 additions & 0 deletions hcx-qr-code-generator/src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
qr_code:
width: ${width:150}
height: ${height:150}
private_key: ${private_key:https://raw.githubusercontent.com/Swasth-Digital-Health-Foundation/hcx-platform/main/hcx-apis/src/test/resources/examples/test-keys/private-key.pem}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"@context": [
"https://www.w3.org/2018/credentials/v1",
"https://www.w3.org/2018/credentials/examples/v1"
],
"id": "http://hcxprotocol.io/credentials/3732",
"type": ["VerifiableCredential"],
"issuer": "https://hcxprotocol.io/participant/565049",
"issuanceDate": "${issuanceDate}",
"expirationDate": "${expirationDate}",
"preferredHCXPath": "http://hcx.swasth.app/api/v0.8/",
"credentialSubject": {
"id": "${subjectId}",
"payload": ${payload}
},
"proof": {
"type": "Ed25519Signature2020",
"created": "${proofCreated}",
"verificationMethod": "https://hcxprotocol.io/issuers/565049#key-1",
"proofPurpose": "assertionMethod",
"proofValue": "${proofValue}"
}
}
Loading
Loading