use of org.bouncycastle.asn1.ocsp.Request in project athenz by yahoo.
the class ZTSClient method getAWSTemporaryCredentials.
public AWSTemporaryCredentials getAWSTemporaryCredentials(String domainName, String roleName, boolean ignoreCache) {
try {
roleName = URLEncoder.encode(roleName, "UTF-8");
} catch (UnsupportedEncodingException ex) {
LOG.error("Unable to encode {} - error {}", roleName, ex.getMessage());
}
// first lookup in our cache to see if it can be satisfied
// only if we're not asked to ignore the cache
AWSTemporaryCredentials awsCred = null;
String cacheKey = getRoleTokenCacheKey(domainName, roleName, null);
if (cacheKey != null && !ignoreCache) {
awsCred = lookupAwsCredInCache(cacheKey, null, null);
if (awsCred != null) {
return awsCred;
}
if (enablePrefetch && prefetchAutoEnable) {
if (prefetchAwsCred(domainName, roleName, null, null)) {
awsCred = lookupAwsCredInCache(cacheKey, null, null);
}
if (awsCred != null) {
return awsCred;
}
LOG.error("GetAWSTemporaryCredentials: cache prefetch and lookup error");
}
}
// if no hit then we need to request a new token from ZTS
updateServicePrincipal();
try {
awsCred = ztsClient.getAWSTemporaryCredentials(domainName, roleName);
} catch (ResourceException ex) {
throw new ZTSClientException(ex.getCode(), ex.getData());
} catch (Exception ex) {
throw new ZTSClientException(ZTSClientException.BAD_REQUEST, ex.getMessage());
}
if (awsCred != null) {
if (cacheKey == null) {
cacheKey = getRoleTokenCacheKey(domainName, roleName, null);
}
if (cacheKey != null) {
AWS_CREDS_CACHE.put(cacheKey, awsCred);
}
}
return awsCred;
}
use of org.bouncycastle.asn1.ocsp.Request in project athenz by yahoo.
the class InstanceClientRegister method main.
public static void main(String[] args) throws MalformedURLException, IOException {
// parse our command line to retrieve required input
CommandLine cmd = parseCommandLine(args);
String domainName = cmd.getOptionValue("domain").toLowerCase();
String serviceName = cmd.getOptionValue("service").toLowerCase();
String provider = cmd.getOptionValue("provider").toLowerCase();
String instance = cmd.getOptionValue("instance");
String dnsSuffix = cmd.getOptionValue("dnssuffix");
String providerKeyPath = cmd.getOptionValue("providerkey");
String providerKeyId = cmd.getOptionValue("providerkeyid");
String instanceKeyPath = cmd.getOptionValue("instancekey");
String ztsUrl = cmd.getOptionValue("ztsurl");
// get our configured private key
PrivateKey providerKey = Crypto.loadPrivateKey(new File(providerKeyPath));
// first we are going to generate our attestation data
// which we are going to use jwt. ZTS Server will send
// this object to the specified provider for validation
String compactJws = Jwts.builder().setSubject(domainName + "." + serviceName).setIssuer(provider).setAudience("zts").setId(instance).setExpiration(new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES))).setHeaderParam("keyId", providerKeyId).signWith(SignatureAlgorithm.RS256, providerKey).compact();
System.out.println("JWS: \n" + compactJws + "\n");
// now we need to generate our CSR so we can get
// a TLS certificate for our instance
PrivateKey instanceKey = Crypto.loadPrivateKey(new File(instanceKeyPath));
String csr = generateCSR(domainName, serviceName, instance, dnsSuffix, instanceKey);
if (csr == null) {
System.err.println("Unable to generate CSR for instance");
System.exit(1);
}
System.out.println("CSR: \n" + csr + "\n");
// now let's generate our instance register object that will be sent
// to the ZTS Server
InstanceRegisterInformation info = new InstanceRegisterInformation().setAttestationData(compactJws).setDomain(domainName).setService(serviceName).setProvider(provider).setToken(true).setCsr(csr);
// now contact zts server to request identity for instance
InstanceIdentity identity = null;
Map<String, List<String>> responseHeaders = new HashMap<>();
try (ZTSClient ztsClient = new ZTSClient(ztsUrl)) {
identity = ztsClient.postInstanceRegisterInformation(info, responseHeaders);
} catch (ZTSClientException ex) {
System.out.println("Unable to register instance: " + ex.getMessage());
System.exit(2);
}
System.out.println("Identity TLS Certificate: \n" + identity.getX509Certificate());
Map<String, String> attrs = identity.getAttributes();
if (attrs != null) {
System.out.println("Provider Attributes:");
for (String key : attrs.keySet()) {
System.out.println("\t" + key + ": " + attrs.get(key));
}
}
}
use of org.bouncycastle.asn1.ocsp.Request in project pdfbox by apache.
the class TSAClient method getTimeStampToken.
/**
* @param messageImprint imprint of message contents
* @return the encoded time stamp token
* @throws IOException if there was an error with the connection or data from the TSA server,
* or if the time stamp response could not be validated
*/
public byte[] getTimeStampToken(byte[] messageImprint) throws IOException {
digest.reset();
byte[] hash = digest.digest(messageImprint);
// 32-bit cryptographic nonce
SecureRandom random = new SecureRandom();
int nonce = random.nextInt();
// generate TSA request
TimeStampRequestGenerator tsaGenerator = new TimeStampRequestGenerator();
tsaGenerator.setCertReq(true);
ASN1ObjectIdentifier oid = getHashObjectIdentifier(digest.getAlgorithm());
TimeStampRequest request = tsaGenerator.generate(oid, hash, BigInteger.valueOf(nonce));
// get TSA response
byte[] tsaResponse = getTSAResponse(request.getEncoded());
TimeStampResponse response;
try {
response = new TimeStampResponse(tsaResponse);
response.validate(request);
} catch (TSPException e) {
throw new IOException(e);
}
TimeStampToken token = response.getTimeStampToken();
if (token == null) {
throw new IOException("Response does not have a time stamp token");
}
return token.getEncoded();
}
use of org.bouncycastle.asn1.ocsp.Request in project pdfbox by apache.
the class OcspHelper method verifyRespStatus.
/**
* Helper method to verify response status.
*
* @param resp OCSP response
* @throws OCSPException if the response status is not ok
*/
public void verifyRespStatus(OCSPResp resp) throws OCSPException {
String statusInfo = "";
if (resp != null) {
int status = resp.getStatus();
switch(status) {
case OCSPResponseStatus.INTERNAL_ERROR:
statusInfo = "INTERNAL_ERROR";
System.err.println("An internal error occurred in the OCSP Server!");
break;
case OCSPResponseStatus.MALFORMED_REQUEST:
statusInfo = "MALFORMED_REQUEST";
System.err.println("Your request did not fit the RFC 2560 syntax!");
break;
case OCSPResponseStatus.SIG_REQUIRED:
statusInfo = "SIG_REQUIRED";
System.err.println("Your request was not signed!");
break;
case OCSPResponseStatus.TRY_LATER:
statusInfo = "TRY_LATER";
System.err.println("The server was too busy to answer you!");
break;
case OCSPResponseStatus.UNAUTHORIZED:
statusInfo = "UNAUTHORIZED";
System.err.println("The server could not authenticate you!");
break;
case OCSPResponseStatus.SUCCESSFUL:
break;
default:
statusInfo = "UNKNOWN";
System.err.println("Unknown OCSPResponse status code! " + status);
}
}
if (resp == null || resp.getStatus() != OCSPResponseStatus.SUCCESSFUL) {
throw new OCSPException(statusInfo + "OCSP response unsuccessful! ");
}
}
use of org.bouncycastle.asn1.ocsp.Request in project keystore-explorer by kaikramer.
the class Pkcs10Util method generateCsr.
/**
* Create a PKCS #10 certificate signing request (CSR) using the supplied
* certificate, private key and signature algorithm.
*
* @param cert
* The certificate
* @param privateKey
* The private key
* @param signatureType
* Signature
* @param challenge
* Challenge, optional, pass null if not required
* @param unstructuredName
* An optional company name, pass null if not required
* @param useExtensions
* Use extensions from cert for extensionRequest attribute?
* @throws CryptoException
* If there was a problem generating the CSR
* @return The CSR
*/
public static PKCS10CertificationRequest generateCsr(X509Certificate cert, PrivateKey privateKey, SignatureType signatureType, String challenge, String unstructuredName, boolean useExtensions, Provider provider) throws CryptoException {
try {
JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(cert.getSubjectX500Principal(), cert.getPublicKey());
// add challenge attribute
if (challenge != null) {
// PKCS#9 2.0: SHOULD use UTF8String encoding
csrBuilder.addAttribute(pkcs_9_at_challengePassword, new DERUTF8String(challenge));
}
if (unstructuredName != null) {
csrBuilder.addAttribute(pkcs_9_at_unstructuredName, new DERUTF8String(unstructuredName));
}
if (useExtensions) {
// add extensionRequest attribute with all extensions from the certificate
Certificate certificate = Certificate.getInstance(cert.getEncoded());
Extensions extensions = certificate.getTBSCertificate().getExtensions();
if (extensions != null) {
csrBuilder.addAttribute(pkcs_9_at_extensionRequest, extensions.toASN1Primitive());
}
}
// fall back to bouncy castle provider if given provider does not support the requested algorithm
if (provider != null && provider.getService("Signature", signatureType.jce()) == null) {
provider = new BouncyCastleProvider();
}
ContentSigner contentSigner = null;
if (provider == null) {
contentSigner = new JcaContentSignerBuilder(signatureType.jce()).build(privateKey);
} else {
contentSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider(provider).build(privateKey);
}
PKCS10CertificationRequest csr = csrBuilder.build(contentSigner);
if (!verifyCsr(csr)) {
throw new CryptoException(res.getString("NoVerifyGenPkcs10Csr.exception.message"));
}
return csr;
} catch (CertificateEncodingException e) {
throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
} catch (OperatorCreationException e) {
throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
}
}
Aggregations