use of java.security.cert.CertificateException in project walle by Meituan-Dianping.
the class V2SchemeVerifier method parseSigner.
/**
* Parses the provided signer block and populates the {@code result}.
*
* <p>This verifies signatures over {@code signed-data} contained in this block but does not
* verify the integrity of the rest of the APK. Rather, this method adds to the
* {@code contentDigestsToVerify}.
*/
private static void parseSigner(ByteBuffer signerBlock, CertificateFactory certFactory, Result.SignerInfo result, Set<ContentDigestAlgorithm> contentDigestsToVerify) throws IOException {
ByteBuffer signedData = getLengthPrefixedSlice(signerBlock);
byte[] signedDataBytes = new byte[signedData.remaining()];
signedData.get(signedDataBytes);
signedData.flip();
result.signedData = signedDataBytes;
ByteBuffer signatures = getLengthPrefixedSlice(signerBlock);
byte[] publicKeyBytes = readLengthPrefixedByteArray(signerBlock);
// Parse the signatures block and identify supported signatures
int signatureCount = 0;
List<SupportedSignature> supportedSignatures = new ArrayList<>(1);
while (signatures.hasRemaining()) {
signatureCount++;
try {
ByteBuffer signature = getLengthPrefixedSlice(signatures);
int sigAlgorithmId = signature.getInt();
byte[] sigBytes = readLengthPrefixedByteArray(signature);
result.signatures.add(new Result.SignerInfo.Signature(sigAlgorithmId, sigBytes));
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.findById(sigAlgorithmId);
if (signatureAlgorithm == null) {
result.addWarning(Issue.V2_SIG_UNKNOWN_SIG_ALGORITHM, sigAlgorithmId);
continue;
}
supportedSignatures.add(new SupportedSignature(signatureAlgorithm, sigBytes));
} catch (IOException | BufferUnderflowException e) {
result.addError(Issue.V2_SIG_MALFORMED_SIGNATURE, signatureCount);
return;
}
}
if (result.signatures.isEmpty()) {
result.addError(Issue.V2_SIG_NO_SIGNATURES);
return;
}
// Verify signatures over signed-data block using the public key
List<SupportedSignature> signaturesToVerify = getSignaturesToVerify(supportedSignatures);
if (signaturesToVerify.isEmpty()) {
result.addError(Issue.V2_SIG_NO_SUPPORTED_SIGNATURES);
return;
}
for (SupportedSignature signature : signaturesToVerify) {
SignatureAlgorithm signatureAlgorithm = signature.algorithm;
String jcaSignatureAlgorithm = signatureAlgorithm.getJcaSignatureAlgorithmAndParams().getFirst();
AlgorithmParameterSpec jcaSignatureAlgorithmParams = signatureAlgorithm.getJcaSignatureAlgorithmAndParams().getSecond();
String keyAlgorithm = signatureAlgorithm.getJcaKeyAlgorithm();
PublicKey publicKey;
try {
publicKey = KeyFactory.getInstance(keyAlgorithm).generatePublic(new X509EncodedKeySpec(publicKeyBytes));
} catch (Exception e) {
result.addError(Issue.V2_SIG_MALFORMED_PUBLIC_KEY, e);
return;
}
try {
Signature sig = Signature.getInstance(jcaSignatureAlgorithm);
sig.initVerify(publicKey);
if (jcaSignatureAlgorithmParams != null) {
sig.setParameter(jcaSignatureAlgorithmParams);
}
signedData.position(0);
sig.update(signedData);
byte[] sigBytes = signature.signature;
if (!sig.verify(sigBytes)) {
result.addError(Issue.V2_SIG_DID_NOT_VERIFY, signatureAlgorithm);
return;
}
result.verifiedSignatures.put(signatureAlgorithm, sigBytes);
contentDigestsToVerify.add(signatureAlgorithm.getContentDigestAlgorithm());
} catch (Exception e) {
result.addError(Issue.V2_SIG_VERIFY_EXCEPTION, signatureAlgorithm, e);
return;
}
}
// At least one signature over signedData has verified. We can now parse signed-data.
signedData.position(0);
ByteBuffer digests = getLengthPrefixedSlice(signedData);
ByteBuffer certificates = getLengthPrefixedSlice(signedData);
ByteBuffer additionalAttributes = getLengthPrefixedSlice(signedData);
// Parse the certificates block
int certificateIndex = -1;
while (certificates.hasRemaining()) {
certificateIndex++;
byte[] encodedCert = readLengthPrefixedByteArray(certificates);
X509Certificate certificate;
try {
certificate = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(encodedCert));
} catch (CertificateException e) {
result.addError(Issue.V2_SIG_MALFORMED_CERTIFICATE, certificateIndex, certificateIndex + 1, e);
return;
}
// Wrap the cert so that the result's getEncoded returns exactly the original encoded
// form. Without this, getEncoded may return a different form from what was stored in
// the signature. This is becase some X509Certificate(Factory) implementations re-encode
// certificates.
certificate = new GuaranteedEncodedFormX509Certificate(certificate, encodedCert);
result.certs.add(certificate);
}
if (result.certs.isEmpty()) {
result.addError(Issue.V2_SIG_NO_CERTIFICATES);
return;
}
X509Certificate mainCertificate = result.certs.get(0);
byte[] certificatePublicKeyBytes = mainCertificate.getPublicKey().getEncoded();
if (!Arrays.equals(publicKeyBytes, certificatePublicKeyBytes)) {
result.addError(Issue.V2_SIG_PUBLIC_KEY_MISMATCH_BETWEEN_CERTIFICATE_AND_SIGNATURES_RECORD, toHex(certificatePublicKeyBytes), toHex(publicKeyBytes));
return;
}
// Parse the digests block
int digestCount = 0;
while (digests.hasRemaining()) {
digestCount++;
try {
ByteBuffer digest = getLengthPrefixedSlice(digests);
int sigAlgorithmId = digest.getInt();
byte[] digestBytes = readLengthPrefixedByteArray(digest);
result.contentDigests.add(new Result.SignerInfo.ContentDigest(sigAlgorithmId, digestBytes));
} catch (IOException | BufferUnderflowException e) {
result.addError(Issue.V2_SIG_MALFORMED_DIGEST, digestCount);
return;
}
}
List<Integer> sigAlgsFromSignaturesRecord = new ArrayList<>(result.signatures.size());
for (Result.SignerInfo.Signature signature : result.signatures) {
sigAlgsFromSignaturesRecord.add(signature.getAlgorithmId());
}
List<Integer> sigAlgsFromDigestsRecord = new ArrayList<>(result.contentDigests.size());
for (Result.SignerInfo.ContentDigest digest : result.contentDigests) {
sigAlgsFromDigestsRecord.add(digest.getSignatureAlgorithmId());
}
if (!sigAlgsFromSignaturesRecord.equals(sigAlgsFromDigestsRecord)) {
result.addError(Issue.V2_SIG_SIG_ALG_MISMATCH_BETWEEN_SIGNATURES_AND_DIGESTS_RECORDS, sigAlgsFromSignaturesRecord, sigAlgsFromDigestsRecord);
return;
}
// Parse the additional attributes block.
int additionalAttributeCount = 0;
while (additionalAttributes.hasRemaining()) {
additionalAttributeCount++;
try {
ByteBuffer attribute = getLengthPrefixedSlice(additionalAttributes);
int id = attribute.getInt();
byte[] value = readLengthPrefixedByteArray(attribute);
result.additionalAttributes.add(new Result.SignerInfo.AdditionalAttribute(id, value));
result.addWarning(Issue.V2_SIG_UNKNOWN_ADDITIONAL_ATTRIBUTE, id);
} catch (IOException | BufferUnderflowException e) {
result.addError(Issue.V2_SIG_MALFORMED_ADDITIONAL_ATTRIBUTE, additionalAttributeCount);
return;
}
}
}
use of java.security.cert.CertificateException in project OpenAttestation by OpenAttestation.
the class Pkcs12 method save.
/**
* Saves the keystore to the resource passed in to the constructor.
*
* @throws IOException if there was an error writing the keystore to the resource
* @throws KeyStoreException if the keystore has not been initialized, or if the integrity check algorithm is not available, or if any certificates in the keystore could not be loaded
*/
public void save() throws IOException, KeyStoreException {
try {
OutputStream out = keystoreResource.getOutputStream();
//,
keystore.store(out, keystorePassword.toCharArray());
out.close();
} catch (NoSuchAlgorithmException e) {
// if the algorithm used to check the integrity of the keystore cannot be found
throw new KeyStoreException(e);
} catch (CertificateException e) {
// if any certificates in the keystore could not be loaded
throw new KeyStoreException(e);
}
}
use of java.security.cert.CertificateException in project OpenAttestation by OpenAttestation.
the class RsaUtil method createX509CertificateWithIssuer.
/**
* Creates an X.509 certificate on the given subject's public key and
* distinguished name, using the given issuer private key and issuer name
* (used as the source of issuer's name on the newly created certificate).
*
* @param subjectPublicKey
* @param dn actually this is just the Common Name portion of the
* Distinguished Name; the OU, O, and C are added automatically. XXX: this
* may change in a future version.
* @param alternativeName a string like "ip:1.2.3.4" or "dns:server.com"
* @param days the certificate will be valid
* @param issuerPrivateKey
* @param issuerName
* @return
* @throws GeneralSecurityException
* @throws IOException
*/
public static X509Certificate createX509CertificateWithIssuer(PublicKey subjectPublicKey, String dn, String alternativeName, int days, PrivateKey issuerPrivateKey, CertificateIssuerName issuerName) throws IOException, CryptographyException {
// X509
X509CertInfo info = new X509CertInfo();
Date from = new Date();
Date to = new Date(from.getTime() + days * 86400000l);
CertificateValidity interval = new CertificateValidity(from, to);
BigInteger sn = new BigInteger(64, new SecureRandom());
// the constructor X500Name(dn) was throwing an exception; replaced "Intel" with "Trusted Data Center" to avoid confusion about the owner of the certificate... this is not an "Intel certificate", it's generated at the customer site.
X500Name subjectName = new X500Name(dn, "Mt Wilson", "Trusted Data Center", "US");
AlgorithmId algorithm = null;
try {
// CertificateException, IOException
info.set(X509CertInfo.VALIDITY, interval);
// CertificateException, IOException
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
// CertificateException, IOException
info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(subjectName));
// CertificateException, IOException
info.set(X509CertInfo.ISSUER, issuerName);
// CertificateException, IOException
info.set(X509CertInfo.KEY, new CertificateX509Key(subjectPublicKey));
// CertificateException, IOException
info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
if (alternativeName != null) {
if (alternativeName.startsWith("ip:")) {
// InetAddress ipAddress = new InetAddress.getByName(alternativeName.substring(3));
// IPAddressName ipAddressName = new IPAddressName(ipAddress.getAddress());
IPAddressName ipAddressName = new IPAddressName(alternativeName.substring(3));
GeneralNames generalNames = new GeneralNames();
generalNames.add(new GeneralName(ipAddressName));
SubjectAlternativeNameExtension san = new SubjectAlternativeNameExtension(generalNames);
CertificateExtensions ext = new CertificateExtensions();
ext.set(san.getExtensionId().toString(), san);
info.set(X509CertInfo.EXTENSIONS, ext);
// ObjectIdentifier("2.5.29.17") , false, "ipaddress".getBytes()
}
if (alternativeName.startsWith("dns:")) {
DNSName dnsName = new DNSName(alternativeName.substring(4));
GeneralNames generalNames = new GeneralNames();
generalNames.add(new GeneralName(dnsName));
SubjectAlternativeNameExtension san = new SubjectAlternativeNameExtension(generalNames);
CertificateExtensions ext = new CertificateExtensions();
ext.set(san.getExtensionId().toString(), san);
info.set(X509CertInfo.EXTENSIONS, ext);
}
}
// md5WithRSAEncryption_oid
algorithm = new AlgorithmId(AlgorithmId.sha256WithRSAEncryption_oid);
info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algorithm));
} catch (CertificateException e) {
throw new CryptographyException("Cannot generate certificate", e);
}
try {
// Sign the cert to identify the algorithm that's used.
X509CertImpl cert = new X509CertImpl(info);
// if this isn't SHA256withRSA need to hard code it
System.out.println("Algorithm name: " + algorithm.getName());
// NoSuchAlgorithMException, InvalidKeyException, NoSuchProviderException, , SignatureException
cert.sign(issuerPrivateKey, algorithm.getName());
// Update the algorith, and resign.
algorithm = (AlgorithmId) cert.get(X509CertImpl.SIG_ALG);
info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algorithm);
cert = new X509CertImpl(info);
// NoSuchAlgorithMException, InvalidKeyException, NoSuchProviderException, SignatureException
cert.sign(issuerPrivateKey, algorithm.getName());
return cert;
} catch (CertificateException e) {
throw new CryptographyException("Cannot sign certificate", e);
} catch (NoSuchAlgorithmException e) {
throw new CryptographyException("Cannot sign certificate", e);
} catch (InvalidKeyException e) {
throw new CryptographyException("Cannot sign certificate", e);
} catch (NoSuchProviderException e) {
throw new CryptographyException("Cannot sign certificate", e);
} catch (SignatureException e) {
throw new CryptographyException("Cannot sign certificate", e);
}
}
use of java.security.cert.CertificateException in project OpenAttestation by OpenAttestation.
the class SimpleKeystore method addTrustedCertificate.
/**
* Saves a trusted SSL certificate into the keystore. In production
* you need to prompt the user to verify the fingerprint of the certificate
* ebfore you add it, in order to prevent man-in-the-middle attacks.
* The trusted purpose (SSL, etc) is added to the certificate's alias.
*
* If a different certificate already exists under the alias, it is replaced.
*
* @throws MalformedURLException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
*/
public void addTrustedCertificate(X509Certificate cert, String alias, String purpose) throws KeyManagementException {
try {
List<String> aliases = Collections.list(keystore.aliases());
String trustedAlias = purpose == null ? alias : String.format("%s (%s)", alias, purpose);
if (aliases.contains(trustedAlias)) {
// is it the same certificate? if so, we can ignore this request
X509Certificate existing = getX509Certificate(trustedAlias);
if (existing.equals(cert)) {
// certificate is already in keystore with same alias
return;
}
// a different certificate is already in the keystore with the same alias. we replace it:
keystore.deleteEntry(trustedAlias);
}
keystore.setCertificateEntry(trustedAlias, cert);
} catch (NoSuchAlgorithmException e) {
throw new KeyManagementException("Cannot add trusted certificate", e);
} catch (KeyStoreException e) {
throw new KeyManagementException("Cannot add trusted certificate", e);
} catch (CertificateException e) {
throw new KeyManagementException("Cannot add trusted certificate", e);
} catch (UnrecoverableEntryException e) {
throw new KeyManagementException("Cannot add trusted certificate", e);
}
}
use of java.security.cert.CertificateException in project OpenAttestation by OpenAttestation.
the class SslUtil method createX509TrustManagerWithCertificates.
public static X509TrustManager createX509TrustManagerWithCertificates(X509Certificate[] certificates) throws KeyManagementException {
try {
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(createTrustedSslKeystore(certificates));
TrustManager[] tms = tmf.getTrustManagers();
for (TrustManager tm : tms) {
if (tm instanceof X509TrustManager) {
return (X509TrustManager) tm;
}
}
} catch (NoSuchAlgorithmException e) {
throw new KeyManagementException("Cannot create X509TrustManager", e);
} catch (IOException e) {
throw new KeyManagementException("Cannot create X509TrustManager", e);
} catch (CertificateException e) {
throw new KeyManagementException("Cannot create X509TrustManager", e);
} catch (UnrecoverableEntryException e) {
throw new KeyManagementException("Cannot create X509TrustManager", e);
} catch (KeyStoreException e) {
throw new KeyManagementException("Cannot create X509TrustManager", e);
}
throw new IllegalArgumentException("TrustManagerFactory did not return an X509TrustManager instance");
}
Aggregations