All Downloads are FREE. Search and download functionalities are using the official Maven repository.

id.unum.utils.CryptoLibUtil Maven / Gradle / Ivy

The newest version!
package id.unum.utils;

import id.unum.crossPlatformInterfaces.CryptoLibJvm;
import id.unum.crossPlatformInterfaces.Encoding;
import id.unum.protos.crypto.v1.EncryptedData;
import id.unum.protos.crypto.v1.KeyPair;
import id.unum.protos.crypto.v1.PublicKeyInfo;

import java.nio.charset.StandardCharsets;

public class CryptoLibUtil {

    private static CryptoLibUtil instance;

    private final CryptoLibJvm cryptoLibJvm;

    private CryptoLibUtil() {
        cryptoLibJvm = new CryptoLibJvm();
    }

    public static CryptoLibUtil getInstance() {
        if (instance == null) {
            instance = new CryptoLibUtil();
        }

        return instance;
    }

    public KeyPair generateRsaKey(Encoding encoding) {
        return cryptoLibJvm.generateRsaKey(encoding);
    }

    public KeyPair generateEccKey(Encoding encoding) {
        return cryptoLibJvm.generateEcKey(encoding);
    }

    public byte[] decryptBytes(KeyPair keyPair, EncryptedData encryptedData) {
        byte[] iv = cryptoLibJvm.decryptData(encryptedData.getKey().getIv(), keyPair);
        byte[] algorithm = cryptoLibJvm.decryptData(encryptedData.getKey().getAlgorithm(), keyPair);
        byte[] key = cryptoLibJvm.decryptData(encryptedData.getKey().getKey(), keyPair);
        if (iv != null && algorithm != null && key != null) {
            return cryptoLibJvm.decryptWithOptions(encryptedData.getData(), iv, new String(algorithm, StandardCharsets.UTF_8), key);
        } else {
            return null;
        }
    }

    public boolean doVerify(String signature, byte[] bytes, PublicKeyInfo publicKey, String encoding) {
        return cryptoLibJvm.verifyDataWithProvidedKey(publicKey, bytes, signature);
    }

    public String encrypt(byte[] data, KeyPair keyPair) {
        return cryptoLibJvm.encryptData(data, keyPair);
    }

    public EncryptedData encryptWithOptions(byte[] data, byte[] iv, String algorithm, byte[] key, String did, String pemKey) {
        return cryptoLibJvm.encryptDataWithOptions(data, iv, algorithm, key, did, pemKey);
    }

    public String sign(byte[] bytes, String privateKey, String encoding) {
        // building KeyPair object to appease the crypto lib
        KeyPair keyPair = KeyPair.newBuilder().setPrivateKey(privateKey).build();
        return cryptoLibJvm.signData(bytes, keyPair);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy