List of usage examples for javax.json JsonObject getString
String getString(String name);
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
/** * Register a user./*w w w.ja va 2 s .c o m*/ * * @param request Registration request with the following fields: name, role. * @param registrar The identity of the registrar (i.e. who is performing the registration). * @return the enrollment secret. * @throws RegistrationException if registration fails. * @throws InvalidArgumentException */ public String register(RegistrationRequest request, User registrar) throws RegistrationException, InvalidArgumentException { if (cryptoSuite == null) { throw new InvalidArgumentException("Crypto primitives not set."); } if (Utils.isNullOrEmpty(request.getEnrollmentID())) { throw new InvalidArgumentException("EntrollmentID cannot be null or empty"); } if (registrar == null) { throw new InvalidArgumentException("Registrar should be a valid member"); } logger.debug(format("register url: %s, registrar: %s", url, registrar.getName())); setUpSSL(); try { String body = request.toJson(); JsonObject resp = httpPost(url + HFCA_REGISTER, body, registrar); String secret = resp.getString("secret"); if (secret == null) { throw new Exception("secret was not found in response"); } logger.debug(format("register url: %s, registrar: %s done.", url, registrar)); return secret; } catch (Exception e) { RegistrationException registrationException = new RegistrationException( format("Error while registering the user %s url: %s %s ", registrar, url, e.getMessage()), e); logger.error(registrar); throw registrationException; } }
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
/** * 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//from ww w. j a v a 2s . c o m */ 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", Util.dateToString(revokedBefore)); } if (revokedAfter != null) { factory.add("revokedAfter", Util.dateToString(revokedAfter)); } if (expireBefore != null) { factory.add("expireBefore", Util.dateToString(expireBefore)); } if (expireAfter != null) { factory.add("expireAfter", Util.dateToString(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); } }
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
/** * Re-Enroll the user with member service * * @param user User to be re-enrolled/* w w w .ja va 2 s . c o m*/ * @param req Enrollment request with the following fields: hosts, profile, csr, label * @return enrollment * @throws EnrollmentException * @throws InvalidArgumentException */ public Enrollment reenroll(User user, EnrollmentRequest req) throws EnrollmentException, InvalidArgumentException { if (cryptoSuite == null) { throw new InvalidArgumentException("Crypto primitives not set."); } if (user == null) { throw new InvalidArgumentException("reenrollment user is missing"); } if (user.getEnrollment() == null) { throw new InvalidArgumentException("reenrollment user is not a valid user object"); } logger.debug(format("re-enroll user: %s, url: %s", user.getName(), url)); try { setUpSSL(); PublicKey publicKey = cryptoSuite .bytesToCertificate(user.getEnrollment().getCert().getBytes(StandardCharsets.UTF_8)) .getPublicKey(); KeyPair keypair = new KeyPair(publicKey, user.getEnrollment().getKey()); // generate CSR String pem = cryptoSuite.generateCertificationRequest(user.getName(), keypair); // build request body req.setCSR(pem); if (caName != null && !caName.isEmpty()) { req.setCAName(caName); } String body = req.toJson(); // build authentication header JsonObject result = httpPost(url + HFCA_REENROLL, body, user); // get new cert from response Base64.Decoder b64dec = Base64.getDecoder(); String signedPem = new String(b64dec.decode(result.getString("Cert").getBytes(UTF_8))); logger.debug(format("[HFCAClient] re-enroll returned pem:[%s]", signedPem)); logger.debug(format("reenroll user %s done.", user.getName())); return new X509Enrollment(keypair, signedPem); } catch (EnrollmentException ee) { logger.error(ee.getMessage(), ee); throw ee; } catch (Exception e) { EnrollmentException ee = new EnrollmentException(format("Failed to re-enroll user %s", user), e); logger.error(e.getMessage(), e); throw ee; } }
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
/** * Return information on the Fabric Certificate Authority. * No credentials are needed for this API. * * @return {@link HFCAInfo}/*from ww w .ja v a 2 s.c om*/ * @throws InfoException * @throws InvalidArgumentException */ public HFCAInfo info() throws InfoException, InvalidArgumentException { logger.debug(format("info url:%s", url)); if (cryptoSuite == null) { throw new InvalidArgumentException("Crypto primitives not set."); } setUpSSL(); try { JsonObjectBuilder factory = Json.createObjectBuilder(); if (caName != null) { factory.add(HFCAClient.FABRIC_CA_REQPROP, caName); } JsonObject body = factory.build(); String responseBody = httpPost(url + HFCA_INFO, body.toString(), (UsernamePasswordCredentials) null); 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 info %s", url)); } JsonObject result = jsonst.getJsonObject("result"); if (result == null) { throw new InfoException( format("FabricCA info error - response did not contain a result url %s", url)); } String caName = result.getString("CAName"); String caChain = result.getString("CAChain"); String version = null; if (result.containsKey("Version")) { version = result.getString("Version"); } String issuerPublicKey = null; if (result.containsKey("IssuerPublicKey")) { issuerPublicKey = result.getString("IssuerPublicKey"); } String issuerRevocationPublicKey = null; if (result.containsKey("IssuerRevocationPublicKey")) { issuerRevocationPublicKey = result.getString("IssuerRevocationPublicKey"); } logger.info(format("CA Name: %s, Version: %s, issuerPublicKey: %s, issuerRevocationPublicKey: %s", caName, caChain, issuerPublicKey, issuerRevocationPublicKey)); return new HFCAInfo(caName, caChain, version, issuerPublicKey, issuerRevocationPublicKey); } catch (Exception e) { InfoException ee = new InfoException(format("Url:%s, Failed to get info", url), e); logger.error(e.getMessage(), e); throw ee; } }
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
/** idemixEnroll returns an Identity Mixer Enrollment, which supports anonymity and unlinkability * * @param enrollment a x509 enrollment credential * @return IdemixEnrollment//w w w . j a v a 2 s . c o m * @throws EnrollmentException * @throws InvalidArgumentException */ public Enrollment idemixEnroll(Enrollment enrollment, String mspID) throws EnrollmentException, InvalidArgumentException { if (cryptoSuite == null) { throw new InvalidArgumentException("Crypto primitives not set"); } if (enrollment == null) { throw new InvalidArgumentException("enrollment is missing"); } if (Utils.isNullOrEmpty(mspID)) { throw new InvalidArgumentException("mspID cannot be null or empty"); } if (enrollment instanceof IdemixEnrollment) { throw new InvalidArgumentException("enrollment type must be x509"); } final RAND rng = IdemixUtils.getRand(); try { setUpSSL(); // Get nonce IdemixEnrollmentRequest idemixEnrollReq = new IdemixEnrollmentRequest(); String body = idemixEnrollReq.toJson(); JsonObject result = httpPost(url + HFCA_IDEMIXCRED, body, enrollment); if (result == null) { throw new EnrollmentException("No response received for idemix enrollment request"); } String nonceString = result.getString("Nonce"); if (Utils.isNullOrEmpty(nonceString)) { throw new InvalidArgumentException( "fabric-ca-server did not return a nonce in the response from " + HFCA_IDEMIXCRED); } byte[] nonceBytes = Base64.getDecoder().decode(nonceString.getBytes()); BIG nonce = BIG.fromBytes(nonceBytes); // Get issuer public key and revocation key from the cainfo section of response JsonObject info = result.getJsonObject("CAInfo"); if (info == null) { throw new Exception( "fabric-ca-server did not return 'cainfo' in the response from " + HFCA_IDEMIXCRED); } IdemixIssuerPublicKey ipk = getIssuerPublicKey(info.getString("IssuerPublicKey")); PublicKey rpk = getRevocationPublicKey(info.getString("IssuerRevocationPublicKey")); // Create and send idemix credential request BIG sk = new BIG(IdemixUtils.randModOrder(rng)); IdemixCredRequest idemixCredRequest = new IdemixCredRequest(sk, nonce, ipk); idemixEnrollReq.setIdemixCredReq(idemixCredRequest); body = idemixEnrollReq.toJson(); result = httpPost(url + HFCA_IDEMIXCRED, body, enrollment); if (result == null) { throw new EnrollmentException("No response received for idemix enrollment request"); } // Deserialize idemix credential String credential = result.getString("Credential"); if (Utils.isNullOrEmpty(credential)) { throw new InvalidArgumentException( "fabric-ca-server did not return a 'credential' in the response from " + HFCA_IDEMIXCRED); } byte[] credBytes = Base64.getDecoder().decode(credential.getBytes(UTF_8)); Idemix.Credential credProto = Idemix.Credential.parseFrom(credBytes); IdemixCredential cred = new IdemixCredential(credProto); // Deserialize idemix cri (Credential Revocation Information) String criStr = result.getString("CRI"); if (Utils.isNullOrEmpty(criStr)) { throw new InvalidArgumentException( "fabric-ca-server did not return a 'CRI' in the response from " + HFCA_IDEMIXCRED); } byte[] criBytes = Base64.getDecoder().decode(criStr.getBytes(UTF_8)); Idemix.CredentialRevocationInformation cri = Idemix.CredentialRevocationInformation.parseFrom(criBytes); JsonObject attrs = result.getJsonObject("Attrs"); if (attrs == null) { throw new EnrollmentException( "fabric-ca-server did not return 'attrs' in the response from " + HFCA_IDEMIXCRED); } String ou = attrs.getString("OU"); if (Utils.isNullOrEmpty(ou)) { throw new InvalidArgumentException( "fabric-ca-server did not return a 'ou' attribute in the response from " + HFCA_IDEMIXCRED); } int role = attrs.getInt("Role"); // Encoded IdemixRole from Fabric-Ca // Return the idemix enrollment return new IdemixEnrollment(ipk, rpk, mspID, sk, cred, cri, ou, role); } catch (EnrollmentException ee) { logger.error(ee.getMessage(), ee); throw ee; } catch (Exception e) { EnrollmentException ee = new EnrollmentException("Failed to get Idemix credential", e); logger.error(e.getMessage(), e); throw ee; } }
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
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)); // If the status code in the response is greater or equal to the status code set in the client object then an exception will // 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);//from w w w . j av a2s .com 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"); // If the status code is greater than or equal to 400 but less than or equal to the client status code setting, // 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); } return job.build(); } 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; }
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
/** * Enroll the user with member service/*from w ww . ja v a2 s. c o m*/ * * @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 X509Enrollment(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; } }
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
private String revokeInternal(User revoker, String serial, String aki, String reason, boolean genCRL) throws RevocationException, InvalidArgumentException { if (cryptoSuite == null) { throw new InvalidArgumentException("Crypto primitives not set."); }//from ww w . jav a 2s .c om if (Utils.isNullOrEmpty(serial)) { throw new IllegalArgumentException("Serial number id required to revoke ceritificate"); } if (Utils.isNullOrEmpty(aki)) { throw new IllegalArgumentException("AKI is required to revoke certificate"); } if (revoker == null) { throw new InvalidArgumentException("revoker is not set"); } logger.debug(format("revoke revoker: %s, reason: %s, url: %s", revoker.getName(), reason, url)); try { setUpSSL(); // build request body RevocationRequest req = new RevocationRequest(caName, null, serial, aki, reason, genCRL); String body = req.toJson(); // send revoke request JsonObject resp = httpPost(url + HFCA_REVOKE, body, revoker); logger.debug("revoke done"); if (genCRL) { if (resp.isEmpty()) { throw new RevocationException("Failed to return CRL, revoke response is empty"); } if (resp.isNull("CRL")) { throw new RevocationException("Failed to return CRL"); } return resp.getString("CRL"); } return null; } catch (CertificateException e) { logger.error("Cannot validate certificate. Error is: " + e.getMessage()); throw new RevocationException("Error while revoking cert. " + e.getMessage(), e); } catch (Exception e) { logger.error(e.getMessage(), e); throw new RevocationException("Error while revoking the user. " + e.getMessage(), e); } }
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
private String revokeInternal(User revoker, Enrollment enrollment, String reason, boolean genCRL) throws RevocationException, InvalidArgumentException { if (cryptoSuite == null) { throw new InvalidArgumentException("Crypto primitives not set."); }/*from ww w .j ava 2 s .c o m*/ if (enrollment == null) { throw new InvalidArgumentException("revokee enrollment is not set"); } if (revoker == null) { throw new InvalidArgumentException("revoker is not set"); } logger.debug(format("revoke revoker: %s, reason: %s, url: %s", revoker.getName(), reason, url)); try { setUpSSL(); // get cert from to-be-revoked enrollment BufferedInputStream pem = new BufferedInputStream( new ByteArrayInputStream(enrollment.getCert().getBytes())); CertificateFactory certFactory = CertificateFactory .getInstance(Config.getConfig().getCertificateFormat()); X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(pem); // get its serial number String serial = DatatypeConverter.printHexBinary(certificate.getSerialNumber().toByteArray()); // get its aki // 2.5.29.35 : AuthorityKeyIdentifier byte[] extensionValue = certificate.getExtensionValue(Extension.authorityKeyIdentifier.getId()); ASN1OctetString akiOc = ASN1OctetString.getInstance(extensionValue); String aki = DatatypeConverter .printHexBinary(AuthorityKeyIdentifier.getInstance(akiOc.getOctets()).getKeyIdentifier()); // build request body RevocationRequest req = new RevocationRequest(caName, null, serial, aki, reason, genCRL); String body = req.toJson(); // send revoke request JsonObject resp = httpPost(url + HFCA_REVOKE, body, revoker); logger.debug("revoke done"); if (genCRL) { if (resp.isEmpty()) { throw new RevocationException("Failed to return CRL, revoke response is empty"); } if (resp.isNull("CRL")) { throw new RevocationException("Failed to return CRL"); } return resp.getString("CRL"); } return null; } catch (CertificateException e) { logger.error("Cannot validate certificate. Error is: " + e.getMessage()); throw new RevocationException("Error while revoking cert. " + e.getMessage(), e); } catch (Exception e) { logger.error(e.getMessage(), e); throw new RevocationException("Error while revoking the user. " + e.getMessage(), e); } }
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
private String revokeInternal(User revoker, String revokee, String reason, boolean genCRL) throws RevocationException, InvalidArgumentException { if (cryptoSuite == null) { throw new InvalidArgumentException("Crypto primitives not set."); }// w ww . j a v a2 s. c om logger.debug(format("revoke revoker: %s, revokee: %s, reason: %s", revoker, revokee, reason)); if (Utils.isNullOrEmpty(revokee)) { throw new InvalidArgumentException("revokee user is not set"); } if (revoker == null) { throw new InvalidArgumentException("revoker is not set"); } try { setUpSSL(); // build request body RevocationRequest req = new RevocationRequest(caName, revokee, null, null, reason, genCRL); String body = req.toJson(); // send revoke request JsonObject resp = httpPost(url + HFCA_REVOKE, body, revoker); logger.debug(format("revoke revokee: %s done.", revokee)); if (genCRL) { if (resp.isEmpty()) { throw new RevocationException("Failed to return CRL, revoke response is empty"); } if (resp.isNull("CRL")) { throw new RevocationException("Failed to return CRL"); } return resp.getString("CRL"); } return null; } catch (Exception e) { logger.error(e.getMessage(), e); throw new RevocationException("Error while revoking the user. " + e.getMessage(), e); } }