-
Notifications
You must be signed in to change notification settings - Fork 11
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
KrutikaPhirangi
wants to merge
25
commits into
Swasth-Digital-Health-Foundation:sprint-55
Choose a base branch
from
KrutikaPhirangi:hcx-qr-code
base: sprint-55
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 14 commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
516e7dd
feat : Implement QR Code Generation
KrutikaPhirangi 77c5983
Update changes
KrutikaPhirangi e859332
Update pom.xml
KrutikaPhirangi 2dcaf9d
Merge branch 'sprint-55' into hcx-qr-code
KrutikaPhirangi a73d7b2
update changes
KrutikaPhirangi 4eacea4
Test cases
KrutikaPhirangi 50f6f0b
Update HcxQRCodeGenerator.java
KrutikaPhirangi 59e8c0f
Update VerifyQRCode.java
KrutikaPhirangi 70c2cbb
Update
KrutikaPhirangi f5b4487
update
KrutikaPhirangi aa77dc4
optimise code
KrutikaPhirangi 278fa29
Update VerifyQrCode.java
KrutikaPhirangi fe96d63
update
KrutikaPhirangi 5389835
update
KrutikaPhirangi df2e7fd
Update pom.xml
KrutikaPhirangi f568c79
Update pom.xml
KrutikaPhirangi f713de4
Update pom.xml
KrutikaPhirangi e1b67c9
update
KrutikaPhirangi 818a527
Update pom.xml
KrutikaPhirangi 360ba57
Update Testcases
KrutikaPhirangi 014cda3
Update issues
KrutikaPhirangi f480fff
Update VerifyQrCode.java
KrutikaPhirangi 50070d7
Update pom.xml
KrutikaPhirangi a9a7165
Merge branch 'sprint-55' into hcx-qr-code
AbhiGaddi a797066
Merge branch 'sprint-55' into hcx-qr-code
maheshkumargangula File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
140
hcx-qr-code-generator/src/main/java/org/swasth/HcxQRCodeGenerator.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | ||
} | ||
} |
26 changes: 26 additions & 0 deletions
26
hcx-qr-code-generator/src/main/java/org/swasth/service/EncDeCode.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
|
||
} |
45 changes: 45 additions & 0 deletions
45
hcx-qr-code-generator/src/main/java/org/swasth/service/VerifyQrCode.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
21
hcx-qr-code-generator/src/main/java/org/swasth/utils/JWSUtils.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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} |
23 changes: 23 additions & 0 deletions
23
hcx-qr-code-generator/src/main/resources/templates/verifiable-credential.ftl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}" | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.