Not able to send data on Push Url

I am not able to use C# code. But Java implementation of encryption is working fine

Hi @Gayatrij I tried that solution but that didn’t work. I am attaching the request and response

Request Received from NDHM:

{
    "transactionId": "05ff7f8b-734b-41e3-bca9-f9715efa96d9",
    "requestId": "542113f8-b567-4103-a339-4086775c0d6f",
    "timestamp": "2020-12-19T13:38:15.564637",
    "hiRequest": {
    "consent": {
        "id": "4697105b-5dcf-48e3-98e6-4bb8e5bfe841"
    },
    "dateRange": {
        "from": "2013-12-19T13:37:55.029632",
        "to": "2020-12-19T13:37:55.029663"
    },
    "dataPushUrl": "https://dev.ndhm.gov.in/patient-hiu/data/notification",
    "keyMaterial": {
        "cryptoAlg": "ECDH",
        "curve": "curve25519",
        "dhPublicKey": {
            "expiry": "2020-12-21T13:37:55.459407",
            "parameters": "Ephemeral public key",
            "keyValue": "BDS9mHsXiBPDjdPQDg0YySmUoWnd9OPB34+FFb0O+Hh5KZiUc32iBY/1mq78ixgDrIKQXWPShWpAcVAnfKdzBgU="
        },
            "nonce": "yaXlycEGymbiBXw3lhA16r/7FYzsD0dbcaQAVUdI6dA="
        }
    }
}


### Java Snippet Output:

senderKeyPair DH Key 1: MIIBMTCB6gYHKoZIzj0CATCB3gIBATArBgcqhkjOPQEBAiB/////////////////////////////////////////7TBEBCAqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqYSRShRAQge0Je0Je0Je0Je0Je0Je0Je0Je0Je0Je0JgtenHcQyGQEQQQqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq0kWiCuGaG4oIa04B7dLHdI0UySPU1+bXxhsinpxaJ+ztPZAiAQAAAAAAAAAAAAAAAAAAAAFN753qL3nNZYEmMaXPXT7QIBCANCAAR958uExjZ09+aw8apdVcFRHq/QtKgz6owUQqJp20LLAiCmzVOT29xxrHSVuF9p2GAarO475ZcNZ8qTBQV+IEqQ
generateRandomKey Nonce: om443fGHXLVkd5wnwhi5Wtc/SYT9gQePqPZTWrQyR1g=
encrypted Data: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fmAlOeL4gDG7dzLHNeIIqr+YMpTD/AAzGVBaMkwCdUNxcwZCrv4nB4E3WugBRSLhiLlXMUurA==
decrypted data:  (error: mac check in GCM failed)


### Request Send to NDHM:

[2020-12-19 13:59:39] local.INFO: ---------------------------------------  
[2020-12-19 13:59:39] local.INFO: header  
[2020-12-19 13:59:39] local.INFO: {"Authorization":"Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJBbFJiNVdDbThUbTlFSl9JZk85ejA2ajlvQ3Y1MXBLS0ZrbkdiX1RCdkswIn0.eyJleHAiOjE2MDgzODY5NjksImlhdCI6MTYwODM4NjM2OSwianRpIjoiNjRmYTcyNDMtMGRjNS00NWQwLWFmZGYtYzNkNmU1YTJjZTlkIiwiaXNzIjoiaHR0cHM6Ly9kZXYubmRobS5nb3YuaW4vYXV0aC9yZWFsbXMvY2VudHJhbC1yZWdpc3RyeSIsImF1ZCI6ImFjY291bnQiLCJzdWIiOiI1NTllZjkyMi0zZTc3LTQzODctYWE4OS05NDgwYzBiNThiMmYiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJQVFBMXzE2MjY5OCIsInNlc3Npb25fc3RhdGUiOiIxZDc4OWMwNS1jZDQxLTRlYWEtOGUzZi1jYWQ5MTY3ZWRmMzAiLCJhY3IiOiIxIiwiYWxsb3dlZC1vcmlnaW5zIjpbImh0dHA6Ly9sb2NhbGhvc3Q6OTAwNyJdLCJyZWFsbV9hY2Nlc3MiOnsicm9sZXMiOlsiaGl1Iiwib2ZmbGluZV9hY2Nlc3MiLCJoZWFsdGhJZCIsImhpcCJdfSwicmVzb3VyY2VfYWNjZXNzIjp7IlBUUExfMTYyNjk4Ijp7InJvbGVzIjpbInVtYV9wcm90ZWN0aW9uIl19LCJhY2NvdW50Ijp7InJvbGVzIjpbIm1hbmFnZS1hY2NvdW50IiwibWFuYWdlLWFjY291bnQtbGlua3MiLCJ2aWV3LXByb2ZpbGUiXX19LCJzY29wZSI6Im9wZW5pZCBlbWFpbCBwcm9maWxlIiwiY2xpZW50SG9zdCI6IjEwLjIzMy42OS40MyIsImNsaWVudElkIjoiUFRQTF8xNjI2OTgiLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsInByZWZlcnJlZF91c2VybmFtZSI6InNlcnZpY2UtYWNjb3VudC1wdHBsXzE2MjY5OCIsImNsaWVudEFkZHJlc3MiOiIxMC4yMzMuNjkuNDMifQ.CKDJTqy6fg1K70KFsAzkBz1sNvFJ1umt2V8kHI_xCd6lxE5z-IC-eZn60bvL0QT0x2LbJ64bFqOdc4GLzIzCNHs78_xY6vNgSXzcrv5MsSdyLMBiVIfDJk00e_umqlQ-utjlS2dAzYEkCOUBGt8OuAx_EHsmQPiFAZX1tLp38xH_WQb8s8Jue-7gP_D4NoHURnB38TQX2tjOZcOCfvpXFkgb7aH7ssmGz8jvxtoU5YEgYEYa6XpOpSVFKRYRfX9d8BrhyYrr9HGRq4tUwZ7Z-OB_irNfHqtKrrkGuAXgHqtxw8ejVDivAG_yr4QB5mABndTZIx_WDCorWk5oIsgemQ","X-CM-ID":"sbx"}  
[2020-12-19 13:59:39] local.INFO: reqest  
[2020-12-19 13:59:39] local.INFO: {"pageNumber":1,"pageCount":1,"dataPushUrl":"https:\/\/dev.ndhm.gov.in\/patient-hiu\/data\/notification","transactionId":"05ff7f8b-734b-41e3-bca9-f9715efa96d9","entries":[{"content":"emuS7WdHq8nL\/simP+0tm1UXj\/PFD0dnE7rWSp1oKhfcAZ3w7Ptw\/4KrCuuh3BA4dvTtcfu\/nGnndMe3WmZapGAYi7XViwr3Dor\/K4+qBv2tSqtSO0JEXt57VvR4tSaFmnIVduRyL98vMWgeAGzPFXEeayHjkMbQZywxf\/xihU8JZp1+QUljKNf8bHd5vmVXcsvbrDwwUALLRgFLDBmgmwVSr21fmb4RyaNyj6HEjarNdjR78FQLB1ro6FJM4uycbCiE2vb4bXD5NQ00T9iVnF7Y6MX9gMi\/ATyGXozLi8AONSRkHjqYeUio4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127Z7xND1+Yhn6WJHP10C5AprDZ8pypgrESDHNkNR8nk0NQXdbwuuciaD5dRREG7O0iPZ9CBvzqwHpKkAVzQS9zMPRE7l\/DmwiV9LGmmLRAZ5K7M4NnL6mKFf2TtPKswIjsuzq5f09lYKSrfmBAR8Gd0jSxyjnwHUDRKusJgXqNNYazRS1KT84P3oFzM7g+\/SB4dAFVWkjp8hYXrzC5FOxz4pPXDixqiYvvBMRVypVV5+W+lSZgBqjHTYuXHdx8YQ3cETJ7TkVOJozDTNK1+sVEsoldRaAbSrqBaWrPbzXcliJONQFlg3N+kqcpDfHNm7zwi\/v9cXOxud6k+qFcVTAyXmvd+QDt9wknoHztDcsjyxgIyfd4yYlP\/Wqgbh1W0WHsq4\/UmiH57DIrfAiQPMI1kB+y6u1ijdu3G1\/C1bY84qLNLuB9PPjNo4vtA4vIf6nLA9gYecTHsIR2dPvkfl6qcmOOsRYy5lDEu2IdAlGjt\/V1JdBfXx\/MwrclLITOE1kYvhEmNqmwZuCBJKr59RobABKy+sHeavTgUaS4jVeDItALLXwomOmhS2QbNTWlN2y3lD\/2Z50n9F\/mwuEpaCJInWBcxSIV7VCLoRt8CrcOHdh+hYvtJTgZfwfuSsfmkGPc0nkWgRTfeQAl0gzbEY+8Vd8sIYRntLKs2DB+U2aWQ1eFcW3LQ\/Gjcccn98f5wBvncaNMNtHyw5GHBC46nnBfru7YpEGtrO28TCHkNv4ZLglKKffqdNAlCE0bd6DLfHtGKzm2e78nBuOmg03wfiJAp7U7MfmAlOeL4gDG7dzLHNeIIqr+YMpTD\/AAzGVBaMkwCdUNxcwZCrv4nB4E3WugBRSLhiLlXMUurA==","media":"application\/fhir+json","checksum":"87c3117efeccb5f55907e0e490ee6b36","careContextReference":"4697105b-5dcf-48e3-98e6-4bb8e5bfe841"}],"keyMaterial":{"cryptoAlg":"ECDH","curve":"curve25519","dhPublicKey":{"expiry":"2020-12-21T13:37:55.459407","parameters":"Ephemeral public key","keyValue":"MIIBMTCB6gYHKoZIzj0CATCB3gIBATArBgcqhkjOPQEBAiB\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/7TBEBCAqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqYSRShRAQge0Je0Je0Je0Je0Je0Je0Je0Je0Je0Je0JgtenHcQyGQEQQQqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq0kWiCuGaG4oIa04B7dLHdI0UySPU1+bXxhsinpxaJ+ztPZAiAQAAAAAAAAAAAAAAAAAAAAFN753qL3nNZYEmMaXPXT7QIBCANCAAR958uExjZ09+aw8apdVcFRHq\/QtKgz6owUQqJp20LLAiCmzVOT29xxrHSVuF9p2GAarO475ZcNZ8qTBQV+IEqQ"},"nonce":"om443fGHXLVkd5wnwhi5Wtc\/SYT9gQePqPZTWrQyR1g="}}  
[2020-12-19 13:59:39] local.INFO: response  
[2020-12-19 13:59:39] local.INFO: []  
[2020-12-19 13:59:39] local.INFO: --------------------------------------  



### Java Snippet to generate the encrypted data:

import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.ec.CustomNamedCurves;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.generators.HKDFBytesGenerator;
import org.bouncycastle.crypto.modes.GCMBlockCipher;
import org.bouncycastle.crypto.params.AEADParameters;
import org.bouncycastle.crypto.params.HKDFParameters;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.jce.interfaces.ECPrivateKey;
import org.bouncycastle.jce.interfaces.ECPublicKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.jce.spec.ECPrivateKeySpec;
import org.bouncycastle.jce.spec.ECPublicKeySpec;

import javax.crypto.KeyAgreement;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;

public class main {
    public static final String ALGORITHM = "ECDH";
    public static final String CURVE = "curve25519";
    public static final String PROVIDER = BouncyCastleProvider.PROVIDER_NAME;
    public static final String strToPerformActionOn = "{\"resourceType\":\"Bundle\",\"id\":\"733319b9-0590-4560-a60f-db27092d63bf\",\"meta\":{\"lastUpdated\":\"2018-08-01T00:00:00.000+05:30\"},\"identifier\":{\"system\":\"https:\\/\\/www.max.in\\/bundle\",\"value\":\"733319b9-0590-4560-a60f-db27092d63bf\"},\"type\":\"document\",\"timestamp\":\"2018-08-01T00:00:00.000+05:30\",\"entry\":[{\"fullUrl\":\"Composition\\/733353a5-097c-4265-959a-9fa9d62833d5\",\"resource\":{\"resourceType\":\"Composition\",\"id\":\"733353a5-097c-4265-959a-9fa9d62833d5\",\"identifier\":{\"system\":\"https:\\/\\/www.max.in\\/document\",\"value\":\"733353a5-097c-4265-959a-9fa9d62833d5\"},\"status\":\"final\",\"type\":{\"coding\":[{\"system\":\"https:\\/\\/projecteka.in\\/sct\",\"code\":\"440545006\",\"display\":\"Prescription record\"}]},\"subject\":{\"reference\":\"Patient\\/TEST-HIP-002\"},\"date\":\"2018-08-01T00:00:00.605+05:30\",\"author\":[{\"reference\":\"Practitioner\\/MAX191101\",\"display\":\"Dr Amit M K\"}],\"title\":\"Prescription\",\"section\":[{\"title\":\"OPD Prescription\",\"code\":{\"coding\":[{\"system\":\"https:\\/\\/projecteka.in\\/sct\",\"code\":\"440545006\",\"display\":\"Prescription record\"}]},\"entry\":[{\"reference\":\"MedicationRequest\\/67fa1415-6834-41b8-99b2-ca73d241fb07\"}]}]}},{\"fullUrl\":\"Practitioner\\/MAX191101\",\"resource\":{\"resourceType\":\"Practitioner\",\"id\":\"MAX191101\",\"identifier\":[{\"system\":\"https:\\/\\/www.mciindia.in\\/doctor\",\"value\":\"MAX191101\"}],\"name\":[{\"text\":\"Amit M K\",\"prefix\":[\"Dr\"],\"suffix\":[\"MD\"]}]}},{\"fullUrl\":\"Patient\\/TEST-HIP-003\",\"resource\":{\"resourceType\":\"Patient\",\"id\":\"TEST-HIP-002\",\"name\":[{\"text\":\"Sadio Mane\"}],\"gender\":\"male\"}},{\"fullUrl\":\"Condition\\/85554d86-0a41-4b92-9ae2-933edaf8fd2c\",\"resource\":{\"resourceType\":\"Condition\",\"id\":\"85554d86-0a41-4b92-9ae2-933edaf8fd2c\",\"code\":{\"text\":\"worm infection\"},\"subject\":{\"reference\":\"Patient\\/TEST-HIP-002\"}}},{\"fullUrl\":\"Medication\\/7741f00b-fb45-4562-9c8f-d3bc316bb971\",\"resource\":{\"resourceType\":\"Medication\",\"id\":\"7741f00b-fb45-4562-9c8f-d3bc316bb971\",\"code\":{\"text\":\"albendazole 400 mg\"}}},{\"fullUrl\":\"MedicationRequest\\/67fa1415-6834-41b8-99b2-ca73d241fb07\",\"resource\":{\"resourceType\":\"MedicationRequest\",\"id\":\"67fa1415-6834-41b8-99b2-ca73d241fb07\",\"status\":\"active\",\"intent\":\"order\",\"medicationReference\":{\"reference\":\"Medication\\/7741f00b-fb45-4562-9c8f-d3bc316bb971\"},\"subject\":{\"reference\":\"Patient\\/TEST-HIP-002\"},\"authoredOn\":\"2018-08-01T00:00:00+05:30\",\"requester\":{\"reference\":\"Practitioner\\/MAX191101\"},\"reasonReference\":[{\"reference\":\"Condition\\/85554d86-0a41-4b92-9ae2-933edaf8fd2c\"}],\"dosageInstruction\":[{\"text\":\"1 time only\"}]}}]}";

    // Driver function
    public static void main(String[] args) throws Exception {
        Security.addProvider(new BouncyCastleProvider());

        System.out.println("Details");
        System.out.println("ALGORITHM: " + ALGORITHM);
        System.out.println("CURVE: " + CURVE);
        System.out.println("DATA: " + strToPerformActionOn);
        System.out.println("<---------------- BEGIN ------------------->");
        System.out.println("\n");

        // Generate the DH keys for sender and receiver
        KeyPair receiverKeyPair = generateKeyPair();
        String receiverPrivateKey = getBase64String(getEncodedPrivateKey(receiverKeyPair.getPrivate()));
        //KeyMaterial.dhPublicKey.keyValue from POST
        String receiverPublicKey = "BDS9mHsXiBPDjdPQDg0YySmUoWnd9OPB34+FFb0O+Hh5KZiUc32iBY/1mq78ixgDrIKQXWPShWpAcVAnfKdzBgU=";

        KeyPair senderKeyPair = generateKeyPair();
        String senderPrivateKey = getBase64String(getEncodedPrivateKey(senderKeyPair.getPrivate()));
        String senderPublicKey = getBase64String(getEncodedPublicKey(senderKeyPair.getPublic()));
        String senderPublicKey1 = getBase64String(getEncodedPublicKeyForProjectEKAHIU(senderKeyPair.getPublic()));
        String senderPrivateKey1 = getBase64String(getEncodedPrivateKey(senderKeyPair.getPrivate()));
        // Generate random key for sender and receiver
        String randomSender = generateRandomKey();
        // nonce from POST
        String randomReceiver = "yaXlycEGymbiBXw3lhA16r/7FYzsD0dbcaQAVUdI6dA=";

        // Generating Xor of random Keys
        byte[] xorOfRandom = xorOfRandom(randomSender, randomReceiver);

        String encryptedData = encrypt(xorOfRandom, senderPrivateKey1, receiverPublicKey, strToPerformActionOn);

        System.out.println("\n");

        String decryptedData = decrypt(xorOfRandom, receiverPrivateKey, senderPublicKey, encryptedData);

        System.out.println("\n");
        // POST in content
        System.out.println("encrypted Data: " + encryptedData);
        System.out.println("decrypted data: " + decryptedData);
        //System.out.println("senderKeyPair DH Key: "+senderPublicKey);
        
        //POST in keyValue
        System.out.println("senderKeyPair DH Key 1: "+senderPublicKey1);
        //POST in Nonce
        System.out.println("generateRandomKey Nonce: "+randomSender);
        System.out.println("\n");
        System.out.println("<---------------- DONE ------------------->");

    }

    // Method for encryption
    public static String encrypt(byte[] xorOfRandom, String senderPrivateKey, String receiverPublicKey, String stringToEncrypt) throws Exception {
        System.out.println("<------------------- ENCRYPTION -------------------->");
        // Generating shared secret
        String sharedKey = doECDH(getBytesForBase64String(senderPrivateKey), getBytesForBase64String(receiverPublicKey));
        System.out.println("Shared key: " + sharedKey);

        // Generating iv and HKDF-AES key
        byte[] iv = Arrays.copyOfRange(xorOfRandom, xorOfRandom.length - 12, xorOfRandom.length);
        byte[] aesKey = generateAesKey(xorOfRandom, sharedKey);
        System.out.println("HKDF AES key: " + getBase64String(aesKey));

        // Perform Encryption
        String encryptedData = "";
        try {
            byte[] stringBytes = stringToEncrypt.getBytes();

            GCMBlockCipher cipher = new GCMBlockCipher(new AESEngine());
            AEADParameters parameters =
                    new AEADParameters(new KeyParameter(aesKey), 128, iv, null);

            cipher.init(true, parameters);
            byte[] plainBytes = new byte[cipher.getOutputSize(stringBytes.length)];
            int retLen = cipher.processBytes
                    (stringBytes, 0, stringBytes.length, plainBytes, 0);
            cipher.doFinal(plainBytes, retLen);

            encryptedData = getBase64String(plainBytes);
        } catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
        }

        System.out.println("EncryptedData: " + encryptedData);
        System.out.println("<---------------- Done ------------------->");
        return encryptedData;
    }

    // Method for decryption
    public static String decrypt(byte[] xorOfRandom, String receiverPrivateKey, String senderPublicKey, String stringToDecrypt) throws Exception {
        System.out.println("<------------------- DECRYPTION -------------------->");
        // Generating shared secret
        String sharedKey = doECDH(getBytesForBase64String(receiverPrivateKey),getBytesForBase64String(senderPublicKey));
        System.out.println("Shared key: " + sharedKey);

        // Generating iv and HKDF-AES key
        byte[] iv = Arrays.copyOfRange(xorOfRandom, xorOfRandom.length - 12, xorOfRandom.length);
        byte[] aesKey = generateAesKey(xorOfRandom, sharedKey);
        System.out.println("HKDF AES key: " + getBase64String(aesKey));

        // Perform Decryption
        String decryptedData = "";
        try {
            byte[] encryptedBytes = getBytesForBase64String(stringToDecrypt);

            GCMBlockCipher cipher = new GCMBlockCipher(new AESEngine());
            AEADParameters parameters =
                    new AEADParameters(new KeyParameter(aesKey), 128, iv, null);

            cipher.init(false, parameters);
            byte[] plainBytes = new byte[cipher.getOutputSize(encryptedBytes.length)];
            int retLen = cipher.processBytes
                    (encryptedBytes, 0, encryptedBytes.length, plainBytes, 0);
            cipher.doFinal(plainBytes, retLen);

            decryptedData = new String(plainBytes);
        } catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
        }

        System.out.println("DecryptedData: " + decryptedData);
        System.out.println("<---------------- Done ------------------->");
        return decryptedData;
    }
    // Method for generating random string
    public static String generateRandomKey() {
        byte[] salt = new byte[32];
        SecureRandom random = new SecureRandom();
        random.nextBytes(salt);
        return getBase64String(salt);
    }

    // Method for generating DH Keys
    public static KeyPair generateKeyPair() throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException {
        Security.addProvider(new BouncyCastleProvider());
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM, PROVIDER);
        X9ECParameters ecParameters = CustomNamedCurves.getByName(CURVE);
        ECParameterSpec ecSpec=new ECParameterSpec(ecParameters.getCurve(), ecParameters.getG(),
                ecParameters.getN(), ecParameters.getH(), ecParameters.getSeed());

        keyPairGenerator.initialize(ecSpec, new SecureRandom());
        //System.out.println("DH keys "+ keyPairGenerator.generateKeyPair());
        return keyPairGenerator.generateKeyPair();
    }

    private static PrivateKey loadPrivateKey (byte [] data) throws Exception
    {
        X9ECParameters ecP = CustomNamedCurves.getByName(CURVE);
        ECParameterSpec params=new ECParameterSpec(ecP.getCurve(), ecP.getG(),
                ecP.getN(), ecP.getH(), ecP.getSeed());
        ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(data), params);
        KeyFactory kf = KeyFactory.getInstance(ALGORITHM, PROVIDER);
        return kf.generatePrivate(privateKeySpec);
    }

    private static PublicKey loadPublicKey (byte [] data) throws Exception
    {
        Security.addProvider(new BouncyCastleProvider());
        X9ECParameters ecP = CustomNamedCurves.getByName(CURVE);
        ECParameterSpec ecNamedCurveParameterSpec = new ECParameterSpec(ecP.getCurve(), ecP.getG(),
                ecP.getN(), ecP.getH(), ecP.getSeed());

        return KeyFactory.getInstance(ALGORITHM, PROVIDER)
                .generatePublic(new ECPublicKeySpec(ecNamedCurveParameterSpec.getCurve().decodePoint(data),
                        ecNamedCurveParameterSpec));
    }

    // Method for generating shared secret
    private static String doECDH (byte[] dataPrv, byte[] dataPub) throws Exception
    {
        KeyAgreement ka = KeyAgreement.getInstance(ALGORITHM, PROVIDER);
        ka.init(loadPrivateKey(dataPrv));
        ka.doPhase(loadPublicKey(dataPub), true);
        byte [] secret = ka.generateSecret();
        return getBase64String(secret);
    }

    // method to perform Xor of random keys
    private static byte [] xorOfRandom(String randomKeySender, String randomKeyReceiver)
    {
        byte[] randomSender = getBytesForBase64String(randomKeySender);
        byte[] randomReceiver = getBytesForBase64String(randomKeyReceiver);

        byte[] out = new byte[randomSender.length];
        for (int i = 0; i < randomSender.length; i++) {
            out[i] = (byte) (randomSender[i] ^ randomReceiver[i%randomReceiver.length]);
        }
        return out;
    }

    // Method for generating HKDF AES key
    private static byte [] generateAesKey(byte[] xorOfRandoms, String sharedKey ){
        byte[] salt = Arrays.copyOfRange(xorOfRandoms, 0, 20);
        HKDFBytesGenerator hkdfBytesGenerator = new HKDFBytesGenerator(new SHA256Digest());
        HKDFParameters hkdfParameters = new HKDFParameters(getBytesForBase64String(sharedKey), salt, null);
        hkdfBytesGenerator.init(hkdfParameters);
        byte[] aesKey = new byte[32];
        hkdfBytesGenerator.generateBytes(aesKey, 0, 32);
        return aesKey;
    }

    public static String getBase64String(byte[] value){

        return new String(org.bouncycastle.util.encoders.Base64.encode(value));
    }

    public static byte[] getBytesForBase64String(String value){
        return org.bouncycastle.util.encoders.Base64.decode(value);
    }

    public static byte [] getEncodedPublicKey(PublicKey key) throws Exception
    {
        ECPublicKey ecKey = (ECPublicKey)key;
        return ecKey.getQ().getEncoded(true);
    }

    public static byte [] getEncodedPrivateKey(PrivateKey key) throws Exception
    {
        ECPrivateKey ecKey = (ECPrivateKey)key;
        return ecKey.getD().toByteArray();
    }

    /*
     If using ProjectEka HIU for the decryption then Please use below methods for converting public keys
    * */
    // Replacement for ------> getEncodedPublicKey
    public static byte[] getEncodedPublicKeyForProjectEKAHIU(PublicKey key){
        ECPublicKey ecKey = (ECPublicKey)key;
        return ecKey.getEncoded();
    }

    // Replacement for ------> loadPublicKey
    private static PublicKey loadPublicKeyForProjectEKAHIU (byte [] data) throws Exception
    {
        KeyFactory ecKeyFac = KeyFactory.getInstance(ALGORITHM, PROVIDER);
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(data);
        PublicKey publicKey = ecKeyFac.generatePublic(x509EncodedKeySpec);
        return publicKey;
    }
}

Actually We tried the Java snippet as it is. Java snippet with changes for the last methods & above suggested solution but none of them worked.

Here are url to the files:

@Gayatrij @Mounica @dheerajp Let me know if we are doing anything wrong.

@mrobin were you able to do encryption decryption with PHP? We tried many solutions but it didn’t work.

Hi @bhaskar.dabhi,
For the given request, we see this error when the HIU is trying to decrypt the content.

Error while decrypting {exception}",“logger_name”:“in.org.projecteka.hiu.dataprocessor.HealthDataProcessor”,“thread_name”:“SimpleAsyncTaskExecutor-1”,“level”:“ERROR”,“level_value”:40000,“stack_trace”:"java.security.spec.InvalidKeySpecException: encoded key spec not recognized: failed to construct sequence from byte[]

This is happening when it it trying to load the public keys shared in the data-push. Can you please make sure that a valid public key is sent along with data-push.

@Gayatrij for which of the snippets did you try this?

@karthik I am stuck with the same issue with c#. Were you able to fix this? Please help.

Hi,
Is it necessary to encrypt the data first and then use the decrypt function?
suppose I am using the decrypt function only to decrypt the strToPerformActionOn data, and it is throwing the exception that

byte[] encryptedBytes = getBytesForBase64String(stringToPerformActionOn);

The above line when runs it is throwing this IOException.
"invalid characters encountered in base64 data"

Hi @nihal,

Are you sending data to the PHR APP as a HIP? If yes you need to encrypt the data using the shared public and your own private key and send it along with your own public key. Please have a look at the webinar for HIPs where this has been discussed.

Thank you

Hi @mdubey,
Thanks for reaching out, but I am working on to HIU and I have already the JSON data from NDHM and which needs to be saved on our database as the transfer call works.
and so when the transfer call runs it says that health data has not valid characters.

Please let me know if anything not clear.

Thanks,
Nihal

Hi @nihal,
If you are working on HIU and having problem while decrypting the data from a HIP, you can check below steps:

  • Check if PHR App is able to show data from that HIP. If not there might be problem the way HIP is encrypting the data.
  • If PHR App is able to show the data from HIP, that means HIP is sending data in the right format. You can compare your HIU decryption logic with our sample application here.

Also please let us know the HIP you are using for the development.

Thank you

Hi @mdubey ,
So here is the thing I am currently doing, I already have a json data from the phr app which is this,

    "pageNumber": 0,
    "pageCount": 0,
    "transactionId": "c306db71-8567-4575-8ad0-7a0acd0e2e02",
    "entries": [
        {  //some value in content like this
            "content": "{\"resourceType\":\"Bundle\",\"idort\",\"creation\":\"2021-03- 
      15T16:12:43.2682813Z\"}}]}}]}",
            "media": "application/fhir+json",
            "checksum": null,
            "careContextReference": "65c28e61-9bb5-45f0-a0ac-93df6c21192",
            "link": null
        }
    ],
    "keyMaterial": {
        "cryptoAlg": "ECDH",
        "curve": "Curve25519",
        "dhPublicKey": {
            "expiry": "2021-04-26T10:27:55.4077066Z",
            "parameters": null,
            "keyValue": "Age+UBKo2WR6NlAUPk/kLMeYYHsSjUiqQ2Y95IoQOIlN"
        },
        "nonce": "PWY5zCeV2GHvHfNJnGhc+ksZ2hNEYEp+KiNVf6xEyHc="
    }
    }

and I am doing the transfer call HIU. and previously I had issue with the keys and I have resolved error after looking at the @vineet_agrawal code as he mentioned above.

And now while decrypting I am having the InvalidCipherTextException: mac check in GCM failed.

This issue is I am having facing,
I have matched the code too and every code is same but I am still facing this issue.

Thanks,
Nihal

@mdubey
Also, the encryption-decryption code I am using is this.

encryptedContent = decryptService.encrypt(decryptService.xorOfRandom(senderKeyMaterial.get("nonce").toString(), flowReq.getNonce()), flowReq.getPrivateKeyValue(),
			((LinkedHashMap) senderKeyMaterial.get("dhPublicKey")).get("keyValue").toString(), healthInfo);
                
//		decryptedContent = decryptService.decrypt(decryptService.xorOfRandom(senderKeyMaterial.get("nonce").toString(), flowReq.getNonce()), flowReq.getPrivateKeyValue(),
//			((LinkedHashMap) senderKeyMaterial.get("dhPublicKey")).get("keyValue").toString(), healthInfo);
                System.out.println("Encrypted content: "+encryptedContent);
                decryptedContent = decryptService.decrypt(decryptService.xorOfRandom(senderKeyMaterial.get("nonce").toString(), flowReq.getNonce()), flowReq.getPrivateKeyValue(),
			((LinkedHashMap) senderKeyMaterial.get("dhPublicKey")).get("keyValue").toString(), encryptedContent);

@Override
	public String encrypt(byte[] xorOfRandom, String senderPrivateKey, String receiverPublicKey, String stringToEncrypt)
	        throws Exception {
		//code added by nihal
		KeyPair senderKeyPair = generateKeyPair();
		senderPrivateKey = getBase64String(getEncodedPrivateKey(senderKeyPair.getPrivate()));
		//till here
		
		String sharedKey = doECDH(getBytesForBase64String(senderPrivateKey), getBytesForBase64String(receiverPublicKey));
		
		System.out.println("shared key :" + sharedKey);
		
		// Generating iv and HKDF-AES key
		byte[] iv = Arrays.copyOfRange(xorOfRandom, xorOfRandom.length - 12, xorOfRandom.length);
		byte[] aesKey = generateAesKey(xorOfRandom, sharedKey);
		System.out.println("HKDF AES key: " + getBase64String(aesKey));
		
		// Perform Encryption
		String encryptedData = "";
		try {
			byte[] stringBytes = stringToEncrypt.getBytes();
			
			GCMBlockCipher cipher = new GCMBlockCipher(new AESEngine());
			AEADParameters parameters = new AEADParameters(new KeyParameter(aesKey), 128, iv, null);
			
			cipher.init(true, parameters);
			byte[] plainBytes = new byte[cipher.getOutputSize(stringBytes.length)];
			int retLen = cipher.processBytes(stringBytes, 0, stringBytes.length, plainBytes, 0);
			cipher.doFinal(plainBytes, retLen);
			
			encryptedData = getBase64String(plainBytes);
		}
		catch (Exception e) {
			System.out.println(e.getLocalizedMessage());
		}
		
		System.out.println("EncryptedData: " + encryptedData);
		System.out.println("<---------------- Done ------------------->");
		
		return encryptedData;
	}
	
	@Override
	public String decrypt(byte[] xorOfRandom, String receiverPrivateKey, String senderPublicKey, String stringToDecrypt)
	        throws Exception {
		
		System.out.println("<------------------- Code edited by nihal -------------------->");
		
		KeyPair receiverKeyPair = generateKeyPair();
		receiverPrivateKey = getBase64String(getEncodedPrivateKey(receiverKeyPair.getPrivate()));
		KeyPair senderKeyPair = generateKeyPair();
		senderPublicKey = getBase64String(getEncodedPublicKey(senderKeyPair.getPublic()));
		
		System.out.println("<------------------- DECRYPTION -------------------->");
		
		String sharedKey = doECDH(getBytesForBase64String(receiverPrivateKey), getBytesForBase64String(senderPublicKey));
		
		System.out.println("Shared key: " + sharedKey);
		
		// Generating iv and HKDF-AES key
		byte[] iv = Arrays.copyOfRange(xorOfRandom, xorOfRandom.length - 12, xorOfRandom.length);
		byte[] aesKey = generateAesKey(xorOfRandom, sharedKey);
		
		System.out.println("HKDF AES key: " + getBase64String(aesKey));
		
		// Perform Decryption
		String decryptedData = "";
		try {
			byte[] encryptedBytes = getBytesForBase64String(stringToDecrypt);
			
			GCMBlockCipher cipher = new GCMBlockCipher(new AESEngine());
			AEADParameters parameters = new AEADParameters(new KeyParameter(aesKey), 128, iv, null);
			
			cipher.init(false, parameters);
			byte[] plainBytes = new byte[cipher.getOutputSize(encryptedBytes.length)];
			int retLen = cipher.processBytes(encryptedBytes, 0, encryptedBytes.length, plainBytes, 0);
			cipher.doFinal(plainBytes, retLen);
			
			decryptedData = new String(plainBytes);
		}
		catch (Exception e) {
			System.out.println(e.getLocalizedMessage());
		}
		
		return decryptedData;
	}

@nihal, Is the data from same HIP is visible on the PHR app? If that is correct you can compare your decryption logic with our sample decryption code if there are any differences.

Thank you

I have checked the data is visible on phr app. also checked that decryption logic is correct.
will there be any chance in that I am using key in wrong manner?

I am using :
Encryption ->

KeyValue (From post JSON data) : receiverPublicKey
KeyPair senderKeyPair = generateKeyPair();
senderPrivateKey = getBase64String(getEncodedPrivateKey(senderKeyPair.getPrivate()));

Decryption ->

KeyPair receiverKeyPair = generateKeyPair();
	receiverPrivateKey = getBase64String(getEncodedPrivateKey(receiverKeyPair.getPrivate()));
KeyPair senderKeyPair = generateKeyPair();
	senderPublicKey = getBase64String(getEncodedPublicKey(senderKeyPair.getPublic()));

Hi @nihal,

If the data from same HIP is visible on the PHR app, the the encryption must be working fine. There might be some differences in the decryption.

KeyPair receiverKeyPair = generateKeyPair();receiverPrivateKey = getBase64String(getEncodedPrivateKey(receiverKeyPair.getPrivate()));
KeyPair senderKeyPair = generateKeyPair();
senderPublicKey = getBase64String(getEncodedPublicKey(senderKeyPair.getPublic()));

One possible reason in your pasted code above I see that you are overriding the receiverPublicKey and senderPublicKey, that means you have lost the original keys which were used to encrypt the conentent.

Please check the decrypt code here, which uses the given keys instead of generating new one.

Thank you

For using the same keys I have only KeyValue and nonce (Not able to send data on Push Url)

Could you clear me which one is senderPublicKey, receiverPublicKey, senderPrivateKey, receiverPrivateKey.

Hi @nihal,
Plese have another look at the encryption-decryption doc here.

The HIP is sender and the HIP is the receiver.

  • The HIU generates a new keypair while requesting the data. This keypair will be used as receiverPublicKey and receiverPrivateKey.
  • When the HIP encrypts the data, it also generates a keypair. This keypair will be used as senderPublicKey and senderPrivateKey.

HIUs needs to store the private key which they use while requesting the data, which will be used while decrypting.

Let us know if there are further questions.

I have checked my payload for the HIU and found that there was no encrypted content I was passing earlier. So i corrected it.
And now I am getting NullPointerException when generating the sharedKey in decryption code.

I have checked with your code and it is same and so I am still getting the NullPointerException.

String sharedKey = doECDH(getBytesForBase64String(receiverPrivateKey), getBytesForBase64String(senderPublicKey));

You should debug your code to check what exctly coming as null. A Stacktrace would clarify, it could be because one of the JSON fields from HIP(nonce, senderPublicKey) or the previously stored receiverPublicKey.

Please check.

Thank you