com.safelayer.rap.crypto.CryptoUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of pki-connector-restapi Show documentation
Show all versions of pki-connector-restapi Show documentation
The PKI Connector RESTAPI is a library that helps developing new PKI Connectors for TrustedX
The newest version!
package com.safelayer.rap.crypto;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.util.Random;
public class CryptoUtils {
private static final String BOUNCY_CASTLE_PROVIDER_ID = "BC";
private static final Random rnd = new SecureRandom();
public static synchronized BigInteger generatePositiveRandom() {
byte[] serialBytes = new byte[8];
rnd.nextBytes(serialBytes);
serialBytes[0] &= 0x7F;
return new BigInteger(serialBytes);
}
public static void verify(PublicKey publicKey, SignatureAlgorithm signatureAlgorithm, byte[] data, byte[] signed) throws Exception {
Signature signature = Signature.getInstance(signatureAlgorithm.getJavaAlgorithm(), BOUNCY_CASTLE_PROVIDER_ID);
signature.initVerify(publicKey);
signature.update(data);
if (!signature.verify(signed))
throw new InvalidSignatureException();
}
public static String getJavaAlgorithm(String signatureAlgorithmId) throws Exception {
return SignatureAlgorithm.valueOfId(signatureAlgorithmId).getJavaAlgorithm();
}
public static AlgorithmIdentifier getBCAlgorithm(String signatureAlgorithmId) throws Exception {
return SignatureAlgorithm.valueOfId(signatureAlgorithmId).getBcAlgorithm();
}
public static byte[] digest(byte[] data, String digestAlgorithmId) throws Exception {
MessageDigest digest = MessageDigest.getInstance(digestAlgorithmId.toLowerCase(), BOUNCY_CASTLE_PROVIDER_ID);
return digest.digest(data);
}
public static SignatureAlgorithm getSignatureAlgorithm(String signatureAlgorithmId, String digestAlgorithmId) throws InvalidAlgorithmException {
final String signAlgoIdLowerCase = signatureAlgorithmId.toLowerCase();
BaseSignatureAlgorithm signatureAlgorithm = BaseSignatureAlgorithm.unsafeValueOfId(signAlgoIdLowerCase);
if (signatureAlgorithm == null)
return SignatureAlgorithm.valueOfId(signAlgoIdLowerCase);
DigestAlgorithm digestAlgorithm = DigestAlgorithm.valueOfId(digestAlgorithmId.toLowerCase());
return SignatureAlgorithm.compose(signatureAlgorithm, digestAlgorithm);
}
}