use of org.bouncycastle.operator.OperatorCreationException in project signer by demoiselle.
the class TimeStampOperator method validate.
/**
* Validate a time stamp
*
* @param content if it is assigned, the parameter hash must to be null
* @param timeStamp timestamp to be validated
* @param hash if it is assigned, the parameter content must to be null
* @throws CertificateCoreException validate exception
*/
@SuppressWarnings("unchecked")
public void validate(byte[] content, byte[] timeStamp, byte[] hash) throws CertificateCoreException {
try {
TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(timeStamp));
CMSSignedData s = timeStampToken.toCMSSignedData();
int verified = 0;
Store<?> certStore = s.getCertificates();
SignerInformationStore signers = s.getSignerInfos();
Collection<SignerInformation> c = signers.getSigners();
Iterator<SignerInformation> it = c.iterator();
while (it.hasNext()) {
SignerInformation signer = it.next();
Collection<?> certCollection = certStore.getMatches(signer.getSID());
Iterator<?> certIt = certCollection.iterator();
X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) {
verified++;
}
cert.getExtension(new ASN1ObjectIdentifier("2.5.29.31")).getExtnValue();
}
logger.info(timeStampMessagesBundle.getString("info.signature.verified", verified));
// Valida o hash incluso no carimbo de tempo com hash do arquivo carimbado
byte[] calculatedHash = null;
if (content != null) {
Digest digest = DigestFactory.getInstance().factoryDefault();
digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
calculatedHash = digest.digest(content);
} else {
calculatedHash = hash;
}
if (Arrays.equals(calculatedHash, timeStampToken.getTimeStampInfo().getMessageImprintDigest())) {
logger.info(timeStampMessagesBundle.getString("info.timestamp.hash.ok"));
} else {
throw new CertificateCoreException(timeStampMessagesBundle.getString("info.timestamp.hash.nok"));
}
} catch (TSPException | IOException | CMSException | OperatorCreationException | CertificateException ex) {
throw new CertificateCoreException(ex.getMessage());
}
}
use of org.bouncycastle.operator.OperatorCreationException in project javaee7-samples by javaee-samples.
the class SecureServletTest method createSelfSignedCertificate.
// Private methods
// TODO: may move these to utility class
private static X509Certificate createSelfSignedCertificate(KeyPair keys) {
try {
Provider provider = new BouncyCastleProvider();
Security.addProvider(provider);
return new JcaX509CertificateConverter().setProvider(provider).getCertificate(new X509v3CertificateBuilder(new X500Name("CN=lfoo, OU=bar, O=kaz, L=zak, ST=lak, C=UK"), ONE, Date.from(now()), Date.from(now().plus(1, DAYS)), new X500Name("CN=lfoo, OU=bar, O=kaz, L=zak, ST=lak, C=UK"), SubjectPublicKeyInfo.getInstance(keys.getPublic().getEncoded())).build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider(provider).build(keys.getPrivate())));
} catch (CertificateException | OperatorCreationException e) {
throw new IllegalStateException(e);
}
}
use of org.bouncycastle.operator.OperatorCreationException in project gitblit by gitblit.
the class X509Utils method revoke.
/**
* Revoke a certificate.
*
* @param cert
* @param reason
* @param caRevocationList
* @param caPrivateKey
* @param x509log
* @return true if the certificate has been revoked
*/
public static boolean revoke(X509Certificate cert, RevocationReason reason, File caRevocationList, PrivateKey caPrivateKey, X509Log x509log) {
try {
X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(cert).getName());
X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuerDN, new Date());
if (caRevocationList.exists()) {
byte[] data = FileUtils.readContent(caRevocationList);
X509CRLHolder crl = new X509CRLHolder(data);
crlBuilder.addCRL(crl);
}
crlBuilder.addCRLEntry(cert.getSerialNumber(), new Date(), reason.ordinal());
// build and sign CRL with CA private key
ContentSigner signer = new JcaContentSignerBuilder("SHA1WithRSA").setProvider(BC).build(caPrivateKey);
X509CRLHolder crl = crlBuilder.build(signer);
File tmpFile = new File(caRevocationList.getParentFile(), Long.toHexString(System.currentTimeMillis()) + ".tmp");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(tmpFile);
fos.write(crl.getEncoded());
fos.flush();
fos.close();
if (caRevocationList.exists()) {
caRevocationList.delete();
}
tmpFile.renameTo(caRevocationList);
} finally {
if (fos != null) {
fos.close();
}
if (tmpFile.exists()) {
tmpFile.delete();
}
}
x509log.log(MessageFormat.format("Revoked certificate {0,number,0} reason: {1} [{2}]", cert.getSerialNumber(), reason.toString(), cert.getSubjectDN().getName()));
return true;
} catch (IOException | OperatorCreationException | CertificateEncodingException e) {
logger.error(MessageFormat.format("Failed to revoke certificate {0,number,0} [{1}] in {2}", cert.getSerialNumber(), cert.getSubjectDN().getName(), caRevocationList));
}
return false;
}
use of org.bouncycastle.operator.OperatorCreationException in project cloudstack by apache.
the class SAML2AuthManagerImpl method initSP.
protected boolean initSP() {
KeystoreVO keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR);
if (keyStoreVO == null) {
try {
KeyPair keyPair = CertUtils.generateRandomKeyPair(4096);
_ksDao.save(SAMLPluginConstants.SAMLSP_KEYPAIR, SAMLUtils.encodePrivateKey(keyPair.getPrivate()), SAMLUtils.encodePublicKey(keyPair.getPublic()), "samlsp-keypair");
keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR);
s_logger.info("No SAML keystore found, created and saved a new Service Provider keypair");
} catch (final NoSuchProviderException | NoSuchAlgorithmException e) {
s_logger.error("Unable to create and save SAML keypair, due to: ", e);
}
}
String spId = SAMLServiceProviderID.value();
String spSsoUrl = SAMLServiceProviderSingleSignOnURL.value();
String spSloUrl = SAMLServiceProviderSingleLogOutURL.value();
String spOrgName = SAMLServiceProviderOrgName.value();
String spOrgUrl = SAMLServiceProviderOrgUrl.value();
String spContactPersonName = SAMLServiceProviderContactPersonName.value();
String spContactPersonEmail = SAMLServiceProviderContactEmail.value();
KeyPair spKeyPair = null;
X509Certificate spX509Key = null;
if (keyStoreVO != null) {
final PrivateKey privateKey = SAMLUtils.decodePrivateKey(keyStoreVO.getCertificate());
final PublicKey publicKey = SAMLUtils.decodePublicKey(keyStoreVO.getKey());
if (privateKey != null && publicKey != null) {
spKeyPair = new KeyPair(publicKey, privateKey);
KeystoreVO x509VO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_X509CERT);
if (x509VO == null) {
try {
spX509Key = SAMLUtils.generateRandomX509Certificate(spKeyPair);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(spX509Key);
out.flush();
_ksDao.save(SAMLPluginConstants.SAMLSP_X509CERT, Base64.encodeBase64String(bos.toByteArray()), "", "samlsp-x509cert");
bos.close();
} catch (final NoSuchAlgorithmException | NoSuchProviderException | CertificateException | SignatureException | InvalidKeyException | IOException | OperatorCreationException e) {
s_logger.error("SAML plugin won't be able to use X509 signed authentication", e);
}
} else {
try {
ByteArrayInputStream bi = new ByteArrayInputStream(Base64.decodeBase64(x509VO.getCertificate()));
ObjectInputStream si = new ObjectInputStream(bi);
spX509Key = (X509Certificate) si.readObject();
bi.close();
} catch (IOException | ClassNotFoundException ignored) {
s_logger.error("SAML Plugin won't be able to use X509 signed authentication. Failed to load X509 Certificate from Database.");
}
}
}
}
if (spKeyPair != null && spX509Key != null && spId != null && spSsoUrl != null && spSloUrl != null && spOrgName != null && spOrgUrl != null && spContactPersonName != null && spContactPersonEmail != null) {
_spMetadata.setEntityId(spId);
_spMetadata.setOrganizationName(spOrgName);
_spMetadata.setOrganizationUrl(spOrgUrl);
_spMetadata.setContactPersonName(spContactPersonName);
_spMetadata.setContactPersonEmail(spContactPersonEmail);
_spMetadata.setSsoUrl(spSsoUrl);
_spMetadata.setSloUrl(spSloUrl);
_spMetadata.setKeyPair(spKeyPair);
_spMetadata.setSigningCertificate(spX509Key);
_spMetadata.setEncryptionCertificate(spX509Key);
return true;
}
return false;
}
use of org.bouncycastle.operator.OperatorCreationException in project zeppelin by apache.
the class PEMImporter method loadKeyStore.
public static KeyStore loadKeyStore(File certificateChainFile, File privateKeyFile, String keyPassword) throws IOException, GeneralSecurityException {
PrivateKey key;
try {
key = createPrivateKey(privateKeyFile, keyPassword);
} catch (OperatorCreationException | IOException | GeneralSecurityException | PKCSException e) {
throw new GeneralSecurityException("Private Key issues", e);
}
List<X509Certificate> certificateChain = readCertificateChain(certificateChainFile);
if (certificateChain.isEmpty()) {
throw new CertificateException("Certificate file does not contain any certificates: " + certificateChainFile);
}
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, null);
keyStore.setKeyEntry("key", key, keyPassword.toCharArray(), certificateChain.stream().toArray(Certificate[]::new));
return keyStore;
}
Aggregations