one.credify.crypto.Utils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-sdk Show documentation
Show all versions of java-sdk Show documentation
CredifySDK for third parties who want to integrate with Credify ecosystem
package one.credify.crypto;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.crypto.*;
import javax.crypto.spec.PBEKeySpec;
import java.io.IOException;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
public class Utils {
public final static String BEGIN_PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----\n";
public final static String END_PUBLIC_KEY = "\n-----END PUBLIC KEY-----";
public final static String BEGIN_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----\n";
public final static String END_PRIVATE_KEY = "\n-----END PRIVATE KEY-----";
public final static String BEGIN_ENCRYPTED_PRIVATE_KEY = "-----BEGIN ENCRYPTED PRIVATE KEY-----\n";
public final static String END_ENCRYPTED_PRIVATE_KEY = "\n-----END ENCRYPTED PRIVATE KEY-----";
public static byte[] readEncryptedPrivateKey(String pem) {
String privateKeyPEM = pem;
privateKeyPEM = privateKeyPEM.replace(BEGIN_ENCRYPTED_PRIVATE_KEY, "");
privateKeyPEM = privateKeyPEM.replace(END_ENCRYPTED_PRIVATE_KEY, "");
privateKeyPEM = privateKeyPEM.replace("\n", "");
return Base64.getDecoder().decode(privateKeyPEM);
}
public static PKCS8EncodedKeySpec readPKCS8Key(String pem, String password) throws IOException, GeneralSecurityException {
EncryptedPrivateKeyInfo pkInfo = new EncryptedPrivateKeyInfo(Utils.readEncryptedPrivateKey(pem));
SecretKey secretKey = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_256")
.generateSecret(new PBEKeySpec(password.toCharArray()));
AlgorithmParameters params = pkInfo.getAlgParameters();
Cipher cipher = Cipher.getInstance(params.toString());
cipher.init(Cipher.DECRYPT_MODE, secretKey, params);
return pkInfo.getKeySpec(cipher);
}
public static byte[] hash(byte[] message) throws NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
return messageDigest.digest(message);
}
public static byte[] hashObject(Object message) throws NoSuchAlgorithmException, JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return hash((mapper.writeValueAsBytes(message)));
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy