id.unum.utils.CryptoUtils Maven / Gradle / Ivy
The newest version!
package id.unum.utils;
import com.google.protobuf.Timestamp;
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.KeyPairSet;
import id.unum.protos.crypto.v1.PublicKeyInfo;
import id.unum.protos.proof.v1.Proof;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
public class CryptoUtils {
/**
* Helper to call crypto lib generate keys
*/
public static KeyPairSet generateKeyPairSet(Encoding encoding) {
KeyPair signingKeyPair = generateEccKeyPair(encoding);
KeyPair encryptionKeyPair = generateRsaKeyPair(encoding);
KeyPairSet keyPairSet = KeyPairSet.newBuilder()
.setSigning(signingKeyPair)
.setEncryption(encryptionKeyPair)
.build();
return keyPairSet;
}
public static KeyPair generateEccKeyPair(Encoding encoding) {
return CryptoLibUtil.getInstance().generateEccKey(encoding);
}
public static KeyPair generateRsaKeyPair(Encoding encoding) {
return CryptoLibUtil.getInstance().generateRsaKey(encoding);
}
public static byte[] decrypt(KeyPair keyPair, EncryptedData encryptedData) {
return CryptoLibUtil.getInstance().decryptBytes(keyPair, encryptedData);
}
public static boolean doVerify(String signature, byte[] bytes, PublicKeyInfo publicKey, String encoding) {
return CryptoLibUtil.getInstance().doVerify(signature, bytes, publicKey, encoding);
}
public static EncryptedData encrypt(String did, PublicKeyInfo publicKeyInfo, byte[] data) throws NoSuchAlgorithmException {
byte[] iv = new byte[16];
SecureRandom.getInstanceStrong().nextBytes(iv);
byte[] key = new byte[32];
SecureRandom.getInstanceStrong().nextBytes(key);
String algorithm = "aes-256-cbc";
return CryptoLibUtil.getInstance().encryptWithOptions(data, iv, algorithm, key, did, publicKeyInfo.getPublicKey());
}
/**
* Helper to call crypto lib sign
*/
public static Proof createProof(byte[] data, String privateKey, String method, String encoding) {
String signature = CryptoLibUtil.getInstance().sign(data, privateKey, encoding);
Proof proof = Proof.newBuilder()
.setProofPurpose("AssertionMethod")
.setCreated(Timestamp.newBuilder().setSeconds(Instant.now().getEpochSecond()).build())
.setSignatureValue(signature)
.setType("secp256r1Signature2020")
.setVerificationMethod(method)
.build();
return proof;
}
// CryptoLib TODO
public static String sign (byte[] data, String privateKey, String encoding) {
return "signature";
}
}