import java.nio.file.Files;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
public class VinIDSignature {
//The method that signs the data using the private key that is stored in keyFile path
public String generateSign(String url, String method, String nonce, String timestamp, String keyCode, String requestBody, String keyFile) throws Exception {
String body = requestBody == null || "".equals(requestBody) ? "" : requestBody;
String data = url + ";" + method + ";" + nonce + ";" + timestamp + ";" + keyCode + ";" + body;
java.security.Signature rsa = java.security.Signature.getInstance("SHA256withRSA");
rsa.initSign(getPrivate(keyFile));
rsa.update(data.getBytes());
return new String(Base64.getEncoder().encode(rsa.sign()));
//Method to retrieve the Private Key from a file
private PrivateKey getPrivate(String filename) throws Exception {
byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(spec);