use of org.bouncycastle.asn1.ocsp.Request in project fabric-sdk-java by hyperledger.
the class HFCAClient method generateCRL.
/**
* Generate certificate revocation list.
*
* @param registrar admin user configured in CA-server
* @param revokedBefore Restrict certificates returned to revoked before this date if not null.
* @param revokedAfter Restrict certificates returned to revoked after this date if not null.
* @param expireBefore Restrict certificates returned to expired before this date if not null.
* @param expireAfter Restrict certificates returned to expired after this date if not null.
* @throws InvalidArgumentException
*/
public String generateCRL(User registrar, Date revokedBefore, Date revokedAfter, Date expireBefore, Date expireAfter) throws InvalidArgumentException, GenerateCRLException {
if (cryptoSuite == null) {
throw new InvalidArgumentException("Crypto primitives not set.");
}
if (registrar == null) {
throw new InvalidArgumentException("registrar is not set");
}
try {
setUpSSL();
// ---------------------------------------
JsonObjectBuilder factory = Json.createObjectBuilder();
if (revokedBefore != null) {
factory.add("revokedBefore", toJson(revokedBefore));
}
if (revokedAfter != null) {
factory.add("revokedAfter", toJson(revokedAfter));
}
if (expireBefore != null) {
factory.add("expireBefore", toJson(expireBefore));
}
if (expireAfter != null) {
factory.add("expireAfter", toJson(expireAfter));
}
if (caName != null) {
factory.add(HFCAClient.FABRIC_CA_REQPROP, caName);
}
JsonObject jsonObject = factory.build();
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = Json.createWriter(new PrintWriter(stringWriter));
jsonWriter.writeObject(jsonObject);
jsonWriter.close();
String body = stringWriter.toString();
// ---------------------------------------
// send revoke request
JsonObject ret = httpPost(url + HFCA_GENCRL, body, registrar);
return ret.getString("CRL");
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new GenerateCRLException(e.getMessage(), e);
}
}
use of org.bouncycastle.asn1.ocsp.Request in project fabric-sdk-java by hyperledger.
the class HFCAClient method getResult.
JsonObject getResult(HttpResponse response, String body, String type) throws HTTPException, ParseException, IOException {
int respStatusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
logger.trace(format("response status %d, HttpEntity %s ", respStatusCode, "" + entity));
String responseBody = entity != null ? EntityUtils.toString(entity) : null;
logger.trace(format("responseBody: %s ", responseBody));
// be thrown, otherwise, we continue to read the response and return any error code that is less than 'statusCode'
if (respStatusCode >= statusCode) {
HTTPException e = new HTTPException(format("%s request to %s failed request body %s. Response: %s", type, url, body, responseBody), respStatusCode);
logger.error(e.getMessage());
throw e;
}
if (responseBody == null) {
HTTPException e = new HTTPException(format("%s request to %s failed request body %s with null response body returned.", type, url, body), respStatusCode);
logger.error(e.getMessage());
throw e;
}
logger.debug("Status: " + respStatusCode);
JsonReader reader = Json.createReader(new StringReader(responseBody));
JsonObject jobj = (JsonObject) reader.read();
JsonObjectBuilder job = Json.createObjectBuilder();
job.add("statusCode", respStatusCode);
JsonArray errors = jobj.getJsonArray("errors");
// then encountered an error and we return back the status code, and log the error rather than throwing an exception.
if (respStatusCode < statusCode && respStatusCode >= 400) {
if (errors != null && !errors.isEmpty()) {
JsonObject jo = errors.getJsonObject(0);
String errorMsg = format("[HTTP Status Code: %d] - %s request to %s failed request body %s error message: [Error Code %d] - %s", respStatusCode, type, url, body, jo.getInt("code"), jo.getString("message"));
logger.error(errorMsg);
}
JsonObject result = job.build();
return result;
}
if (errors != null && !errors.isEmpty()) {
JsonObject jo = errors.getJsonObject(0);
HTTPException e = new HTTPException(format("%s request to %s failed request body %s error message: [Error Code %d] - %s", type, url, body, jo.getInt("code"), jo.getString("message")), respStatusCode);
throw e;
}
boolean success = jobj.getBoolean("success");
if (!success) {
HTTPException e = new HTTPException(format("%s request to %s failed request body %s Body of response did not contain success", type, url, body), respStatusCode);
logger.error(e.getMessage());
throw e;
}
JsonObject result = jobj.getJsonObject("result");
if (result == null) {
HTTPException e = new HTTPException(format("%s request to %s failed request body %s " + "Body of response did not contain result", type, url, body), respStatusCode);
logger.error(e.getMessage());
throw e;
}
JsonArray messages = jobj.getJsonArray("messages");
if (messages != null && !messages.isEmpty()) {
JsonObject jo = messages.getJsonObject(0);
String message = format("%s request to %s failed request body %s response message: [Error Code %d] - %s", type, url, body, jo.getInt("code"), jo.getString("message"));
logger.info(message);
}
// Construct JSON object that contains the result and HTTP status code
for (Entry<String, JsonValue> entry : result.entrySet()) {
job.add(entry.getKey(), entry.getValue());
}
job.add("statusCode", respStatusCode);
result = job.build();
logger.debug(format("%s %s, body:%s result: %s", type, url, body, "" + result));
return result;
}
use of org.bouncycastle.asn1.ocsp.Request in project fabric-sdk-java by hyperledger.
the class HFCAClient method enroll.
/**
* Enroll the user with member service
*
* @param user Identity name to enroll
* @param secret Secret returned via registration
* @param req Enrollment request with the following fields: hosts, profile, csr, label, keypair
* @return enrollment
* @throws EnrollmentException
* @throws InvalidArgumentException
*/
public Enrollment enroll(String user, String secret, EnrollmentRequest req) throws EnrollmentException, InvalidArgumentException {
logger.debug(format("url:%s enroll user: %s", url, user));
if (Utils.isNullOrEmpty(user)) {
throw new InvalidArgumentException("enrollment user is not set");
}
if (Utils.isNullOrEmpty(secret)) {
throw new InvalidArgumentException("enrollment secret is not set");
}
if (cryptoSuite == null) {
throw new InvalidArgumentException("Crypto primitives not set.");
}
setUpSSL();
try {
String pem = req.getCsr();
KeyPair keypair = req.getKeyPair();
if (null != pem && keypair == null) {
throw new InvalidArgumentException("If certificate signing request is supplied the key pair needs to be supplied too.");
}
if (keypair == null) {
logger.debug("[HFCAClient.enroll] Generating keys...");
// generate ECDSA keys: signing and encryption keys
keypair = cryptoSuite.keyGen();
logger.debug("[HFCAClient.enroll] Generating keys...done!");
}
if (pem == null) {
String csr = cryptoSuite.generateCertificationRequest(user, keypair);
req.setCSR(csr);
}
if (caName != null && !caName.isEmpty()) {
req.setCAName(caName);
}
String body = req.toJson();
String responseBody = httpPost(url + HFCA_ENROLL, body, new UsernamePasswordCredentials(user, secret));
logger.debug("response:" + responseBody);
JsonReader reader = Json.createReader(new StringReader(responseBody));
JsonObject jsonst = (JsonObject) reader.read();
boolean success = jsonst.getBoolean("success");
logger.debug(format("[HFCAClient] enroll success:[%s]", success));
if (!success) {
throw new EnrollmentException(format("FabricCA failed enrollment for user %s response success is false.", user));
}
JsonObject result = jsonst.getJsonObject("result");
if (result == null) {
throw new EnrollmentException(format("FabricCA failed enrollment for user %s - response did not contain a result", user));
}
Base64.Decoder b64dec = Base64.getDecoder();
String signedPem = new String(b64dec.decode(result.getString("Cert").getBytes(UTF_8)));
logger.debug(format("[HFCAClient] enroll returned pem:[%s]", signedPem));
JsonArray messages = jsonst.getJsonArray("messages");
if (messages != null && !messages.isEmpty()) {
JsonObject jo = messages.getJsonObject(0);
String message = format("Enroll request response message [code %d]: %s", jo.getInt("code"), jo.getString("message"));
logger.info(message);
}
logger.debug("Enrollment done.");
return new HFCAEnrollment(keypair, signedPem);
} catch (EnrollmentException ee) {
logger.error(format("url:%s, user:%s error:%s", url, user, ee.getMessage()), ee);
throw ee;
} catch (Exception e) {
EnrollmentException ee = new EnrollmentException(format("Url:%s, Failed to enroll user %s ", url, user), e);
logger.error(e.getMessage(), e);
throw ee;
}
}
use of org.bouncycastle.asn1.ocsp.Request in project jruby-openssl by jruby.
the class X509Request method initialize.
@JRubyMethod(name = "initialize", rest = true, visibility = Visibility.PRIVATE)
public IRubyObject initialize(final ThreadContext context, final IRubyObject[] args) {
final Ruby runtime = context.runtime;
if (Arity.checkArgumentCount(runtime, args, 0, 1) == 0)
return this;
try {
request = new PKCS10Request(StringHelper.readX509PEM(context, args[0]));
} catch (RuntimeException e) {
debugStackTrace(runtime, e);
throw newRequestError(runtime, "invalid certificate request data", e);
}
final String algorithm;
final byte[] encoded;
try {
final PublicKey pkey = request.generatePublicKey();
algorithm = pkey.getAlgorithm();
encoded = pkey.getEncoded();
} catch (IOException e) {
throw newRequestError(runtime, e);
} catch (GeneralSecurityException e) {
throw newRequestError(runtime, e);
}
final RubyString enc = RubyString.newString(runtime, encoded);
if ("RSA".equalsIgnoreCase(algorithm)) {
this.public_key = newPKeyImplInstance(context, "RSA", enc);
} else if ("DSA".equalsIgnoreCase(algorithm)) {
this.public_key = newPKeyImplInstance(context, "DSA", enc);
} else {
throw runtime.newNotImplementedError("public key algorithm: " + algorithm);
}
this.subject = newName(context, request.getSubject());
final Attribute[] attrs = request.getAttributes();
try {
// final RubyModule _ASN1 = _ASN1(runtime);
if (attrs != null) {
for (final Attribute attr : attrs) {
final ASN1ObjectIdentifier type = attr.getAttrType();
final ASN1Set values = attr.getAttrValues();
attributes.add(newAttribute(context, type, values));
}
}
} catch (IOException e) {
throw newRequestError(runtime, e);
}
return this;
}
use of org.bouncycastle.asn1.ocsp.Request in project jruby-openssl by jruby.
the class MiscPEMGenerator method createPemObject.
private PemObject createPemObject(Object o) throws IOException {
String type;
byte[] encoding;
if (o instanceof PemObject) {
return (PemObject) o;
}
if (o instanceof PemObjectGenerator) {
return ((PemObjectGenerator) o).generate();
}
if (o instanceof X509CertificateHolder) {
type = "CERTIFICATE";
encoding = ((X509CertificateHolder) o).getEncoded();
} else if (o instanceof X509CRLHolder) {
type = "X509 CRL";
encoding = ((X509CRLHolder) o).getEncoded();
} else if (o instanceof PrivateKeyInfo) {
PrivateKeyInfo info = (PrivateKeyInfo) o;
ASN1ObjectIdentifier algOID = info.getPrivateKeyAlgorithm().getAlgorithm();
if (algOID.equals(PKCSObjectIdentifiers.rsaEncryption)) {
type = "RSA PRIVATE KEY";
encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
} else if (algOID.equals(dsaOids[0]) || algOID.equals(dsaOids[1])) {
type = "DSA PRIVATE KEY";
DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new ASN1Integer(BigInteger.ZERO));
v.add(new ASN1Integer(p.getP()));
v.add(new ASN1Integer(p.getQ()));
v.add(new ASN1Integer(p.getG()));
BigInteger x = ASN1Integer.getInstance(info.parsePrivateKey()).getValue();
BigInteger y = p.getG().modPow(x, p.getP());
v.add(new ASN1Integer(y));
v.add(new ASN1Integer(x));
encoding = new DERSequence(v).getEncoded();
} else if (algOID.equals(X9ObjectIdentifiers.id_ecPublicKey)) {
type = "EC PRIVATE KEY";
encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
} else {
throw new IOException("Cannot identify private key");
}
} else if (o instanceof SubjectPublicKeyInfo) {
type = "PUBLIC KEY";
encoding = ((SubjectPublicKeyInfo) o).getEncoded();
} else if (o instanceof X509AttributeCertificateHolder) {
type = "ATTRIBUTE CERTIFICATE";
encoding = ((X509AttributeCertificateHolder) o).getEncoded();
} else if (o instanceof PKCS10CertificationRequest) {
type = "CERTIFICATE REQUEST";
encoding = ((PKCS10CertificationRequest) o).getEncoded();
} else if (o instanceof ContentInfo) {
type = "PKCS7";
encoding = ((ContentInfo) o).getEncoded();
} else //
if (// 1.47 compatibility
o instanceof java.security.cert.X509Certificate) {
type = "CERTIFICATE";
try {
encoding = ((java.security.cert.X509Certificate) o).getEncoded();
} catch (CertificateEncodingException e) {
throw new PemGenerationException("Cannot encode object: " + e.toString());
}
} else if (// 1.47 compatibility
o instanceof java.security.cert.X509CRL) {
type = "X509 CRL";
try {
encoding = ((java.security.cert.X509CRL) o).getEncoded();
} catch (CRLException e) {
throw new PemGenerationException("Cannot encode object: " + e.toString());
}
} else if (// 1.47 compatibility
o instanceof java.security.KeyPair) {
return createPemObject(((java.security.KeyPair) o).getPrivate());
} else if (// 1.47 compatibility
o instanceof java.security.PrivateKey) {
PrivateKeyInfo info = new PrivateKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(((java.security.Key) o).getEncoded()));
if (o instanceof java.security.interfaces.RSAPrivateKey) {
type = "RSA PRIVATE KEY";
encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
} else if (o instanceof java.security.interfaces.DSAPrivateKey) {
type = "DSA PRIVATE KEY";
DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DERInteger(0));
v.add(new DERInteger(p.getP()));
v.add(new DERInteger(p.getQ()));
v.add(new DERInteger(p.getG()));
BigInteger x = ((java.security.interfaces.DSAPrivateKey) o).getX();
BigInteger y = p.getG().modPow(x, p.getP());
v.add(new DERInteger(y));
v.add(new DERInteger(x));
encoding = new DERSequence(v).getEncoded();
} else if (((java.security.PrivateKey) o).getAlgorithm().equals("ECDSA")) {
type = "EC PRIVATE KEY";
encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
} else {
throw new IOException("Cannot identify private key");
}
} else if (// 1.47 compatibility
o instanceof java.security.PublicKey) {
type = "PUBLIC KEY";
encoding = ((java.security.PublicKey) o).getEncoded();
} else if (// 1.47 compatibility
o instanceof X509AttributeCertificate) {
type = "ATTRIBUTE CERTIFICATE";
encoding = ((X509AttributeCertificate) o).getEncoded();
} else //
//
//
{
throw new PemGenerationException("unknown object passed - can't encode.");
}
if (// NEW STUFF (NOT IN OLD)
encryptor != null) {
String dekAlgName = Strings.toUpperCase(encryptor.getAlgorithm());
// Note: For backward compatibility
if (dekAlgName.equals("DESEDE")) {
dekAlgName = "DES-EDE3-CBC";
}
byte[] iv = encryptor.getIV();
byte[] encData = encryptor.encrypt(encoding);
List<PemHeader> headers = new ArrayList<PemHeader>(2);
headers.add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
headers.add(new PemHeader("DEK-Info", dekAlgName + "," + getHexEncoded(iv)));
return new PemObject(type, headers, encData);
}
return new PemObject(type, encoding);
}
Aggregations