Example usage for java.util Base64 getDecoder

List of usage examples for java.util Base64 getDecoder

Introduction

In this page you can find the example usage for java.util Base64 getDecoder.

Prototype

public static Decoder getDecoder() 

Source Link

Document

Returns a Decoder that decodes using the Basic type base64 encoding scheme.

Usage

From source file:ai.susi.server.api.aaa.LoginService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization,
        final JsonObjectWithDefault permissions) throws APIException {

    // login check for app
    if (post.get("checkLogin", false)) {
        JSONObject result = new JSONObject();
        if (authorization.getIdentity().isEmail()) {
            result.put("loggedIn", true);
            result.put("message", "You are logged in as " + authorization.getIdentity().getName());
        } else {//from   w  w  w.ja v a  2  s .  co  m
            result.put("loggedIn", false);
            result.put("message", "Not logged in");
        }
        return result;
    }

    // do logout if requested
    boolean logout = post.get("logout", false);
    boolean delete = post.get("delete", false);
    if (logout || delete) { // logout if requested

        // invalidate session
        post.getRequest().getSession().invalidate();

        // delete cookie if set
        deleteLoginCookie(response);

        if (delete) {
            ClientCredential pwcredential = new ClientCredential(authorization.getIdentity());
            delete = DAO.authentication.has(pwcredential.toString());
            if (delete)
                DAO.authentication.remove(pwcredential.toString());
        }

        JSONObject result = new JSONObject();
        result.put("message", delete ? "Account deletion successful" : "Logout successful");
        return result;
    }

    // check login type by checking which parameters are set
    boolean passwordLogin = false;
    boolean pubkeyHello = false;
    boolean pubkeyLogin = false;

    if (post.get("login", null) != null && post.get("password", null) != null
            && post.get("type", null) != null) {
        passwordLogin = true;
    } else if (post.get("login", null) != null && post.get("keyhash", null) != null) {
        pubkeyHello = true;
    } else if (post.get("sessionID", null) != null && post.get("response", null) != null) {
        pubkeyLogin = true;
    } else {
        throw new APIException(400, "Bad login parameters.");
    }

    // check if user is blocked because of too many invalid login attempts
    checkInvalidLogins(post, authorization, permissions);

    if (passwordLogin) { // do login via password

        String login = post.get("login", null);
        String password = post.get("password", null);
        String type = post.get("type", null);
        ClientCredential pwcredential = new ClientCredential(ClientCredential.Type.passwd_login, login);
        Authentication authentication = getAuthentication(post, authorization, pwcredential);
        ClientIdentity identity = authentication.getIdentity();

        // check if the password is valid
        String passwordHash;
        String salt;
        try {
            passwordHash = authentication.getString("passwordHash");
            salt = authentication.getString("salt");
        } catch (Throwable e) {
            Log.getLog().info("Invalid login try for user: " + identity.getName() + " from host: "
                    + post.getClientHost() + " : password or salt missing in database");
            throw new APIException(422, "Invalid credentials");
        }

        if (!passwordHash.equals(getHash(password, salt))) {

            // save invalid login in accounting object
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");

            Log.getLog().info("Invalid login try for user: " + identity.getName() + " via passwd from host: "
                    + post.getClientHost());
            throw new APIException(422, "Invalid credentials");
        }

        JSONObject result = new JSONObject();

        switch (type) {
        case "session": // create a browser session
            post.getRequest().getSession().setAttribute("identity", identity);
            break;
        case "cookie": // set a long living cookie
            // create random string as token
            String loginToken = createRandomString(30);

            // create cookie
            Cookie loginCookie = new Cookie("login", loginToken);
            loginCookie.setPath("/");
            loginCookie.setMaxAge(defaultCookieTime.intValue());

            // write cookie to database
            ClientCredential cookieCredential = new ClientCredential(ClientCredential.Type.cookie, loginToken);
            JSONObject user_obj = new JSONObject();
            user_obj.put("id", identity.toString());
            user_obj.put("expires_on", Instant.now().getEpochSecond() + defaultCookieTime);
            DAO.authentication.put(cookieCredential.toString(), user_obj, cookieCredential.isPersistent());

            response.addCookie(loginCookie);
            break;
        case "access-token": // create and display an access token

            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);

            break;
        default:
            throw new APIException(400, "Invalid type");
        }

        Log.getLog().info(
                "login for user: " + identity.getName() + " via passwd from host: " + post.getClientHost());

        result.put("message", "You are logged in as " + identity.getName());
        return result;
    } else if (pubkeyHello) { // first part of pubkey login: if the key hash is known, create a challenge

        String login = post.get("login", null);
        String keyHash = post.get("keyhash", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.passwd_login, login));
        ClientIdentity identity = authentication.getIdentity();

        if (!DAO.login_keys.has(identity.toString())
                || !DAO.login_keys.getJSONObject(identity.toString()).has(keyHash))
            throw new APIException(400, "Unknown key");

        String challengeString = createRandomString(30);
        String newSessionID = createRandomString(30);

        ClientCredential credential = new ClientCredential(ClientCredential.Type.pubkey_challange,
                newSessionID);
        Authentication challenge_auth = new Authentication(credential, DAO.authentication);
        challenge_auth.setIdentity(identity);
        challenge_auth.put("activated", true);

        challenge_auth.put("challenge", challengeString);
        challenge_auth.put("key", DAO.login_keys.getJSONObject(identity.toString()).getString(keyHash));
        challenge_auth.setExpireTime(60 * 10);

        JSONObject result = new JSONObject();
        result.put("challenge", challengeString);
        result.put("sessionID", newSessionID);
        result.put("message",
                "Found valid key for this user. Sign the challenge with you public key and send it back, together with the sessionID");
        return result;
    } else if (pubkeyLogin) { // second part of pubkey login: verify if the response to the challange is valid

        String sessionID = post.get("sessionID", null);
        String challangeResponse = post.get("response", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.pubkey_challange, sessionID));
        ClientIdentity identity = authentication.getIdentity();

        String challenge = authentication.getString("challenge");
        PublicKey key = IO.decodePublicKey(authentication.getString("key"), "RSA");

        Signature sig;
        boolean verified;
        try {
            sig = Signature.getInstance("SHA256withRSA");
            sig.initVerify(key);
            sig.update(challenge.getBytes());
            verified = sig.verify(Base64.getDecoder().decode(challangeResponse));
        } catch (NoSuchAlgorithmException e) {
            throw new APIException(400, "No such algorithm");
        } catch (InvalidKeyException e) {
            throw new APIException(400, "Invalid key");
        } catch (Throwable e) {
            throw new APIException(400, "Bad signature");
        }

        if (verified) {
            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            JSONObject result = new JSONObject();

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);
            return result;
        } else {
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");
            throw new APIException(400, "Bad Signature");
        }
    }
    throw new APIException(500, "Server error");
}

From source file:eu.peppol.outbound.transmission.As2MessageSender.java

SendResult send(InputStream inputStream, ParticipantId recipient, ParticipantId sender,
        PeppolDocumentTypeId peppolDocumentTypeId, SmpLookupManager.PeppolEndpointData peppolEndpointData,
        PeppolAs2SystemIdentifier as2SystemIdentifierOfSender) {

    if (peppolEndpointData.getCommonName() == null) {
        throw new IllegalArgumentException("No common name in EndPoint object. " + peppolEndpointData);
    }/*from   w w  w  .  jav a 2  s . com*/
    X509Certificate ourCertificate = keystoreManager.getOurCertificate();

    SMimeMessageFactory sMimeMessageFactory = new SMimeMessageFactory(keystoreManager.getOurPrivateKey(),
            ourCertificate);
    MimeMessage signedMimeMessage = null;
    Mic mic = null;
    try {
        MimeBodyPart mimeBodyPart = MimeMessageHelper.createMimeBodyPart(inputStream,
                new MimeType("application/xml"));
        mic = MimeMessageHelper.calculateMic(mimeBodyPart);
        log.debug("Outbound MIC is : " + mic.toString());
        signedMimeMessage = sMimeMessageFactory.createSignedMimeMessage(mimeBodyPart);
    } catch (MimeTypeParseException e) {
        throw new IllegalStateException("Problems with MIME types: " + e.getMessage(), e);
    }

    String endpointAddress = peppolEndpointData.getUrl().toExternalForm();
    HttpPost httpPost = new HttpPost(endpointAddress);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {
        signedMimeMessage.writeTo(byteArrayOutputStream);

    } catch (Exception e) {
        throw new IllegalStateException("Unable to stream S/MIME message into byte array output stream");
    }

    httpPost.addHeader(As2Header.AS2_FROM.getHttpHeaderName(), as2SystemIdentifierOfSender.toString());
    try {
        httpPost.setHeader(As2Header.AS2_TO.getHttpHeaderName(),
                PeppolAs2SystemIdentifier.valueOf(peppolEndpointData.getCommonName()).toString());
    } catch (InvalidAs2SystemIdentifierException e) {
        throw new IllegalArgumentException(
                "Unable to create valid AS2 System Identifier for receiving end point: " + peppolEndpointData);
    }

    httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_TO.getHttpHeaderName(), "not.in.use@difi.no");
    httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_OPTIONS.getHttpHeaderName(),
            As2DispositionNotificationOptions.getDefault().toString());
    httpPost.addHeader(As2Header.AS2_VERSION.getHttpHeaderName(), As2Header.VERSION);
    httpPost.addHeader(As2Header.SUBJECT.getHttpHeaderName(), "AS2 message from OXALIS");

    TransmissionId transmissionId = new TransmissionId();
    httpPost.addHeader(As2Header.MESSAGE_ID.getHttpHeaderName(), transmissionId.toString());
    httpPost.addHeader(As2Header.DATE.getHttpHeaderName(), As2DateUtil.format(new Date()));

    // Inserts the S/MIME message to be posted.
    // Make sure we pass the same content type as the SignedMimeMessage, it'll end up as content-type HTTP header
    try {
        String contentType = signedMimeMessage.getContentType();
        ContentType ct = ContentType.create(contentType);
        httpPost.setEntity(new ByteArrayEntity(byteArrayOutputStream.toByteArray(), ct));
    } catch (Exception ex) {
        throw new IllegalStateException("Unable to set request header content type : " + ex.getMessage());
    }

    CloseableHttpResponse postResponse = null; // EXECUTE !!!!
    try {
        CloseableHttpClient httpClient = createCloseableHttpClient();
        log.debug("Sending AS2 from " + sender + " to " + recipient + " at " + endpointAddress + " type "
                + peppolDocumentTypeId);
        postResponse = httpClient.execute(httpPost);
    } catch (HttpHostConnectException e) {
        throw new IllegalStateException("The Oxalis server does not seem to be running at " + endpointAddress);
    } catch (Exception e) {
        throw new IllegalStateException(
                "Unexpected error during execution of http POST to " + endpointAddress + ": " + e.getMessage(),
                e);
    }

    if (postResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        log.error("AS2 HTTP POST expected HTTP OK, but got : " + postResponse.getStatusLine().getStatusCode()
                + " from " + endpointAddress);
        throw handleFailedRequest(postResponse);
    }

    // handle normal HTTP OK response
    log.debug("AS2 transmission " + transmissionId + " to " + endpointAddress
            + " returned HTTP OK, verify MDN response");
    MimeMessage mimeMessage = handleTheHttpResponse(transmissionId, mic, postResponse, peppolEndpointData);

    // Transforms the signed MDN into a generic a As2RemWithMdnTransmissionEvidenceImpl
    MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage);
    Map<String, String> mdnFields = mdnMimeMessageInspector.getMdnFields();
    String messageDigestAsBase64 = mdnFields.get(MdnMimeMessageFactory.X_ORIGINAL_MESSAGE_DIGEST);
    if (messageDigestAsBase64 == null) {
        messageDigestAsBase64 = new String(Base64.getEncoder().encode("null".getBytes()));
    }
    String receptionTimeStampAsString = mdnFields.get(MdnMimeMessageFactory.X_PEPPOL_TIME_STAMP);
    Date receptionTimeStamp = null;
    if (receptionTimeStampAsString != null) {
        receptionTimeStamp = As2DateUtil.parseIso8601TimeStamp(receptionTimeStampAsString);
    } else {
        receptionTimeStamp = new Date();
    }

    // Converts the Oxalis DocumentTypeIdentifier into the corresponding type for peppol-evidence
    DocumentTypeIdentifier documentTypeIdentifier = new DocumentTypeIdentifier(peppolDocumentTypeId.toString());

    @NotNull
    As2RemWithMdnTransmissionEvidenceImpl evidence = as2TransmissionEvidenceFactory.createEvidence(
            EventCode.DELIVERY, TransmissionRole.C_2, mimeMessage,
            new ParticipantIdentifier(recipient.stringValue()), // peppol-evidence uses it's own types
            new ParticipantIdentifier(sender.stringValue()), // peppol-evidence uses it's own types
            documentTypeIdentifier, receptionTimeStamp, Base64.getDecoder().decode(messageDigestAsBase64),
            transmissionId);

    ByteArrayOutputStream evidenceBytes;
    try {
        evidenceBytes = new ByteArrayOutputStream();
        IOUtils.copy(evidence.getInputStream(), evidenceBytes);
    } catch (IOException e) {
        throw new IllegalStateException(
                "Unable to transform transport evidence to byte array." + e.getMessage(), e);
    }

    return new SendResult(transmissionId, evidenceBytes.toByteArray());
}

From source file:org.loklak.api.aaa.LoginService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization,
        final JSONObjectWithDefault permissions) throws APIException {

    // login check for app
    if (post.get("checkLogin", false)) {
        JSONObject result = new JSONObject();
        if (authorization.getIdentity().isEmail()) {
            result.put("loggedIn", true);
            result.put("message", "You are logged in as " + authorization.getIdentity().getName());
        } else {//from w  ww .  ja  va 2 s.co  m
            result.put("loggedIn", false);
            result.put("message", "Not logged in");
        }
        return result;
    }

    // do logout if requested
    boolean logout = post.get("logout", false);
    boolean delete = post.get("delete", false);
    if (logout || delete) { // logout if requested

        // invalidate session
        post.getRequest().getSession().invalidate();

        // delete cookie if set
        deleteLoginCookie(response);

        if (delete) {
            ClientCredential pwcredential = new ClientCredential(authorization.getIdentity());
            delete = DAO.authentication.has(pwcredential.toString());
            if (delete)
                DAO.authentication.remove(pwcredential.toString());
        }

        JSONObject result = new JSONObject();
        result.put("message", delete ? "Account deletion successful" : "Logout successful");
        return result;
    }

    // check login type by checking which parameters are set
    boolean passwordLogin = false;
    boolean pubkeyHello = false;
    boolean pubkeyLogin = false;

    if (post.get("login", null) != null && post.get("password", null) != null
            && post.get("type", null) != null) {
        passwordLogin = true;
    } else if (post.get("login", null) != null && post.get("keyhash", null) != null) {
        pubkeyHello = true;
    } else if (post.get("sessionID", null) != null && post.get("response", null) != null) {
        pubkeyLogin = true;
    } else {
        throw new APIException(400, "Bad login parameters.");
    }

    // check if user is blocked because of too many invalid login attempts
    checkInvalidLogins(post, authorization, permissions);

    if (passwordLogin) { // do login via password

        String login = post.get("login", null);
        String password = post.get("password", null);
        String type = post.get("type", null);
        ClientCredential pwcredential = new ClientCredential(ClientCredential.Type.passwd_login, login);
        Authentication authentication = getAuthentication(post, authorization, pwcredential);
        ClientIdentity identity = authentication.getIdentity();

        // check if the password is valid
        String passwordHash;
        String salt;
        try {
            passwordHash = authentication.getString("passwordHash");
            salt = authentication.getString("salt");
        } catch (Throwable e) {
            Log.getLog().info("Invalid login try for user: " + identity.getName() + " from host: "
                    + post.getClientHost() + " : password or salt missing in database");
            throw new APIException(422, "Invalid credentials");
        }

        if (!passwordHash.equals(getHash(password, salt))) {

            // save invalid login in accounting object
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");

            Log.getLog().info("Invalid login try for user: " + identity.getName() + " via passwd from host: "
                    + post.getClientHost());
            throw new APIException(422, "Invalid credentials");
        }

        JSONObject result = new JSONObject();

        switch (type) {
        case "session": // create a browser session
            post.getRequest().getSession().setAttribute("identity", identity);
            break;
        case "cookie": // set a long living cookie
            // create random string as token
            String loginToken = createRandomString(30);

            // create cookie
            Cookie loginCookie = new Cookie("login", loginToken);
            loginCookie.setPath("/");
            loginCookie.setMaxAge(defaultCookieTime.intValue());

            // write cookie to database
            ClientCredential cookieCredential = new ClientCredential(ClientCredential.Type.cookie, loginToken);
            JSONObject user_obj = new JSONObject();
            user_obj.put("id", identity.toString());
            user_obj.put("expires_on", Instant.now().getEpochSecond() + defaultCookieTime);
            DAO.authentication.put(cookieCredential.toString(), user_obj, cookieCredential.isPersistent());

            response.addCookie(loginCookie);
            break;
        case "access-token": // create and display an access token

            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);

            break;
        default:
            throw new APIException(400, "Invalid type");
        }

        Log.getLog().info(
                "login for user: " + identity.getName() + " via passwd from host: " + post.getClientHost());

        result.put("message", "You are logged in as " + identity.getName());
        return result;
    } else if (pubkeyHello) { // first part of pubkey login: if the key hash is known, create a challenge

        String login = post.get("login", null);
        String keyHash = post.get("keyhash", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.passwd_login, login));
        ClientIdentity identity = authentication.getIdentity();

        if (!DAO.login_keys.has(identity.toString())
                || !DAO.login_keys.getJSONObject(identity.toString()).has(keyHash))
            throw new APIException(400, "Unknown key");

        String challengeString = createRandomString(30);
        String newSessionID = createRandomString(30);

        ClientCredential credential = new ClientCredential(ClientCredential.Type.pubkey_challange,
                newSessionID);
        Authentication challenge_auth = new Authentication(credential, DAO.authentication);
        challenge_auth.setIdentity(identity);
        challenge_auth.put("activated", true);

        challenge_auth.put("challenge", challengeString);
        challenge_auth.put("key", DAO.login_keys.getJSONObject(identity.toString()).getString(keyHash));
        challenge_auth.setExpireTime(60 * 10);

        JSONObject result = new JSONObject();
        result.put("challenge", challengeString);
        result.put("sessionID", newSessionID);
        result.put("message",
                "Found valid key for this user. Sign the challenge with you public key and send it back, together with the sessionID");
        return result;
    } else if (pubkeyLogin) { // second part of pubkey login: verify if the response to the challange is valid

        String sessionID = post.get("sessionID", null);
        String challangeResponse = post.get("response", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.pubkey_challange, sessionID));
        ClientIdentity identity = authentication.getIdentity();

        String challenge = authentication.getString("challenge");
        PublicKey key = IO.decodePublicKey(authentication.getString("key"), "RSA");

        Signature sig;
        boolean verified;
        try {
            sig = Signature.getInstance("SHA256withRSA");
            sig.initVerify(key);
            sig.update(challenge.getBytes());
            verified = sig.verify(Base64.getDecoder().decode(challangeResponse));
        } catch (NoSuchAlgorithmException e) {
            throw new APIException(400, "No such algorithm");
        } catch (InvalidKeyException e) {
            throw new APIException(400, "Invalid key");
        } catch (Throwable e) {
            throw new APIException(400, "Bad signature");
        }

        if (verified) {
            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            JSONObject result = new JSONObject();

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);
            return result;
        } else {
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");
            throw new APIException(400, "Bad Signature");
        }
    }
    throw new APIException(500, "Server error");
}

From source file:org.openhab.binding.ihc.internal.ws.IhcClient.java

/**
 * Fetch project file from controller.//from w ww  .j a v  a 2  s. c  o  m
 *
 * @return project file.
 */
public byte[] getProjectFileFromController() throws IhcExecption {
    try {
        WSProjectInfo projectInfo = getProjectInfo();
        int numberOfSegments = getProjectNumberOfSegments();
        int segmentationSize = getProjectSegmentationSize();

        logger.debug("Number of segments: {}", numberOfSegments);
        logger.debug("Segmentation size: {}", segmentationSize);

        try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) {
            for (int i = 0; i < numberOfSegments; i++) {
                logger.debug("Downloading segment {}", i);

                WSFile data = getProjectSegment(i, projectInfo.getProjectMajorRevision(),
                        projectInfo.getProjectMinorRevision());
                byteStream.write(data.getData());
            }
            if (logger.isDebugEnabled()) {
                logger.debug("File size before base64 encoding: {} bytes", byteStream.size());
            }
            byte[] decodedBytes = Base64.getDecoder().decode(byteStream.toString());
            logger.debug("File size after base64 encoding: {} bytes", decodedBytes.length);
            try (GZIPInputStream gzis = new GZIPInputStream(new ByteArrayInputStream(decodedBytes))) {
                try (InputStreamReader in = new InputStreamReader(gzis, "ISO-8859-1")) {
                    return IOUtils.toByteArray(in, "ISO-8859-1");
                }
            }
        }
    } catch (IOException | IllegalArgumentException e) {
        throw new IhcExecption(e);
    }
}

From source file:org.wso2.carbon.siddhi.editor.core.internal.ServiceComponent.java

@GET
@Path("/workspace/exists")
@Produces("application/json")
public Response fileExists(@QueryParam("path") String path) {
    try {//from  w  w w  .j  a v a  2s.  c om
        return Response.status(Response.Status.OK)
                .entity(workspace.exists(new String(Base64.getDecoder().decode(path))))
                .type(MediaType.APPLICATION_JSON).build();
    } catch (IOException e) {
        return Response.serverError().entity("failed." + e.getMessage()).build();
    } catch (Throwable ignored) {
        return Response.serverError().entity("failed").build();
    }
}

From source file:com.cws.esolutions.security.utils.PasswordUtils.java

/**
 * Base64 decodes a given string/*from  w ww  . ja v a  2 s  . c  o m*/
 *
 * @param text - The text to base64 decode
 * @return The base64-decoded string
 * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing
 */
public static final String base64Decode(final String text) throws SecurityException {
    final String methodName = PasswordUtils.CNAME + "#base64Decode(final String text) throws SecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", text);
    }

    return new String(Base64.getDecoder().decode(text.getBytes()));
}

From source file:ai.susi.server.api.aaa.PublicKeyRegistrationService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization,
        final JsonObjectWithDefault permissions) throws APIException {

    if (post.get("register", null) == null && !post.get("create", false) && !post.get("getParameters", false)) {
        throw new APIException(400, "Accepted parameters: 'register', 'create' or 'getParameters'");
    }/*  w  ww. j a  v a 2  s .  co  m*/

    JSONObject result = new JSONObject();

    // return algorithm parameters and users for whom we are allowed to register a key
    if (post.get("getParameters", false)) {
        result.put("self", permissions.getBoolean("self", false));
        result.put("users", permissions.getJSONObject("users"));
        result.put("userRoles", permissions.getJSONObject("userRoles"));

        JSONObject algorithms = new JSONObject();

        JSONObject rsa = new JSONObject();
        JSONArray keySizes = new JSONArray();
        for (int i : allowedKeySizesRSA) {
            keySizes.put(i);
        }
        rsa.put("sizes", keySizes);
        rsa.put("defaultSize", defaultKeySizeRSA);
        algorithms.put("RSA", rsa);
        result.put("algorithms", algorithms);

        JSONArray formats = new JSONArray();
        for (String format : allowedFormats) {
            formats.put(format);
        }
        result.put("formats", formats);

        return result;
    }

    // for which id?
    String id;
    if (post.get("id", null) != null)
        id = post.get("id", null);
    else
        id = authorization.getIdentity().getName();

    // check if we are allowed register a key
    if (!id.equals(authorization.getIdentity().getName())) { // if we don't want to register the key for the current user

        // create Authentication to check if the user id is a registered user
        ClientCredential credential = new ClientCredential(ClientCredential.Type.passwd_login, id);
        Authentication authentication = new Authentication(credential, DAO.authentication);

        if (authentication.getIdentity() == null) { // check if identity is valid
            authentication.delete();
            throw new APIException(400, "Bad request"); // do not leak if user exists or not
        }

        // check if the current user is allowed to create a key for the user in question
        boolean allowed = false;
        // check if the user in question is in 'users'
        if (permissions.getJSONObject("users", null).has(id)
                && permissions.getJSONObjectWithDefault("users", null).getBoolean(id, false)) {
            allowed = true;
        } else { // check if the user role of the user in question is in 'userRoles'
            Authorization auth = new Authorization(authentication.getIdentity(), DAO.authorization,
                    DAO.userRoles);
            for (String key : permissions.getJSONObject("userRoles").keySet()) {
                if (key.equals(auth.getUserRole().getName())
                        && permissions.getJSONObject("userRoles").getBoolean(key)) {
                    allowed = true;
                }
            }
        }
        if (!allowed)
            throw new APIException(400, "Bad request"); // do not leak if user exists or not
    } else { // if we want to register a key for this user, bad are not allowed to (for example anonymous users)
        if (!permissions.getBoolean("self", false))
            throw new APIException(403, "You are not allowed to register a public key");
    }

    // set algorithm. later, we maybe want to support other algorithms as well
    String algorithm = "RSA";
    if (post.get("algorithm", null) != null) {
        algorithm = post.get("algorithm", null);
    }

    if (post.get("create", false)) { // create a new key pair on the server

        if (algorithm.equals("RSA")) {
            int keySize = 2048;
            if (post.get("key-size", null) != null) {
                int finalKeyLength = post.get("key-size", 0);
                if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == finalKeyLength)) {
                    throw new APIException(400, "Invalid key size.");
                }
                keySize = finalKeyLength;
            }

            KeyPairGenerator keyGen;
            KeyPair keyPair;
            try {
                keyGen = KeyPairGenerator.getInstance(algorithm);
                keyGen.initialize(keySize);
                keyPair = keyGen.genKeyPair();
            } catch (NoSuchAlgorithmException e) {
                throw new APIException(500, "Server error");
            }

            registerKey(authorization.getIdentity(), keyPair.getPublic());

            String pubkey_pem = null, privkey_pem = null;
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                pubkey_pem = writer.toString();
            } catch (IOException e) {
            }
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PRIVATE KEY", keyPair.getPrivate().getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                privkey_pem = writer.toString();
            } catch (IOException e) {
            }

            result.put("publickey_DER_BASE64",
                    Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()));
            result.put("privatekey_DER_BASE64",
                    Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()));
            result.put("publickey_PEM", pubkey_pem);
            result.put("privatekey_PEM", privkey_pem);
            result.put("keyhash", IO.getKeyHash(keyPair.getPublic()));
            try {
                result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(keyPair.getPublic()), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            }
            result.put("key-size", keySize);
            result.put("message",
                    "Successfully created and registered key. Make sure to copy the private key, it won't be saved on the server");

            return result;
        }
        throw new APIException(400, "Unsupported algorithm");
    } else if (post.get("register", null) != null) {

        if (algorithm.equals("RSA")) {
            String type = post.get("type", null);
            if (type == null)
                type = "DER";

            RSAPublicKey pub;
            String encodedKey;
            try {
                encodedKey = URLDecoder.decode(post.get("register", null), "UTF-8");
            } catch (Throwable e) {
                throw new APIException(500, "Server error");
            }
            Log.getLog().info("Key (" + type + "): " + encodedKey);

            if (type.equals("DER")) {
                try {
                    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(encodedKey));
                    pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec);
                } catch (Throwable e) {
                    throw new APIException(400, "Public key not readable (DER)");
                }
            } else if (type.equals("PEM")) {
                try {
                    PemReader pemReader = new PemReader(new StringReader(encodedKey));
                    PemObject pem = pemReader.readPemObject();
                    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pem.getContent());
                    pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec);
                } catch (Exception e) {
                    throw new APIException(400, "Public key not readable (PEM)");
                }
            } else {
                throw new APIException(400, "Invalid value for 'type'.");
            }

            // check key size (not really perfect yet)
            int keySize;
            int bitLength = pub.getModulus().bitLength();
            if (bitLength <= 512) {
                keySize = 512;
            } else if (bitLength <= 1024) {
                keySize = 1024;
            } else if (bitLength <= 2048) {
                keySize = 2048;
            } else if (bitLength <= 4096) {
                keySize = 4096;
            } else {
                keySize = 8192;
            }
            if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == keySize)) {
                throw new APIException(400, "Invalid key length.");
            }

            registerKey(authorization.getIdentity(), pub);

            String pubkey_pem = null;
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PUBLIC KEY", pub.getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                pubkey_pem = writer.toString();
            } catch (IOException e) {
            }

            result.put("publickey_DER_BASE64", Base64.getEncoder().encodeToString(pub.getEncoded()));
            result.put("publickey_PEM", pubkey_pem);
            result.put("keyhash", IO.getKeyHash(pub));
            try {
                result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(pub), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            }
            result.put("message", "Successfully registered key.");

            return result;
        }
        throw new APIException(400, "Unsupported algorithm");
    }

    throw new APIException(400, "Invalid parameter");
}

From source file:org.loklak.api.aaa.PublicKeyRegistrationService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization,
        final JSONObjectWithDefault permissions) throws APIException {

    if (post.get("register", null) == null && !post.get("create", false) && !post.get("getParameters", false)) {
        throw new APIException(400, "Accepted parameters: 'register', 'create' or 'getParameters'");
    }/*from   w  ww.  j av  a2  s . c  o m*/

    JSONObject result = new JSONObject();

    // return algorithm parameters and users for whom we are allowed to register a key
    if (post.get("getParameters", false)) {
        result.put("self", permissions.getBoolean("self", false));
        result.put("users", permissions.getJSONObject("users"));
        result.put("userRoles", permissions.getJSONObject("userRoles"));

        JSONObject algorithms = new JSONObject();

        JSONObject rsa = new JSONObject();
        JSONArray keySizes = new JSONArray();
        for (int i : allowedKeySizesRSA) {
            keySizes.put(i);
        }
        rsa.put("sizes", keySizes);
        rsa.put("defaultSize", defaultKeySizeRSA);
        algorithms.put("RSA", rsa);
        result.put("algorithms", algorithms);

        JSONArray formats = new JSONArray();
        for (String format : allowedFormats) {
            formats.put(format);
        }
        result.put("formats", formats);

        return result;
    }

    // for which id?
    String id;
    if (post.get("id", null) != null)
        id = post.get("id", null);
    else
        id = authorization.getIdentity().getName();

    // check if we are allowed register a key
    if (!id.equals(authorization.getIdentity().getName())) { // if we don't want to register the key for the current user

        // create Authentication to check if the user id is a registered user
        ClientCredential credential = new ClientCredential(ClientCredential.Type.passwd_login, id);
        Authentication authentication = new Authentication(credential, DAO.authentication);

        if (authentication.getIdentity() == null) { // check if identity is valid
            authentication.delete();
            throw new APIException(400, "Bad request"); // do not leak if user exists or not
        }

        // check if the current user is allowed to create a key for the user in question
        boolean allowed = false;
        // check if the user in question is in 'users'
        if (permissions.getJSONObject("users", null).has(id)
                && permissions.getJSONObjectWithDefault("users", null).getBoolean(id, false)) {
            allowed = true;
        } else { // check if the user role of the user in question is in 'userRoles'
            Authorization auth = new Authorization(authentication.getIdentity(), DAO.authorization,
                    DAO.userRoles);
            for (String key : permissions.getJSONObject("userRoles").keySet()) {
                if (key.equals(auth.getUserRole().getName())
                        && permissions.getJSONObject("userRoles").getBoolean(key)) {
                    allowed = true;
                }
            }
        }
        if (!allowed)
            throw new APIException(400, "Bad request"); // do not leak if user exists or not
    } else { // if we want to register a key for this user, bad are not allowed to (for example anonymous users)
        if (!permissions.getBoolean("self", false))
            throw new APIException(403, "You are not allowed to register a public key");
    }

    // set algorithm. later, we maybe want to support other algorithms as well
    String algorithm = "RSA";
    if (post.get("algorithm", null) != null) {
        algorithm = post.get("algorithm", null);
    }

    if (post.get("create", false)) { // create a new key pair on the server

        if (algorithm.equals("RSA")) {
            int keySize = 2048;
            if (post.get("key-size", null) != null) {
                int finalKeyLength = post.get("key-size", 0);
                if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == finalKeyLength)) {
                    throw new APIException(400, "Invalid key size.");
                }
                keySize = finalKeyLength;
            }

            KeyPairGenerator keyGen;
            KeyPair keyPair;
            try {
                keyGen = KeyPairGenerator.getInstance(algorithm);
                keyGen.initialize(keySize);
                keyPair = keyGen.genKeyPair();
            } catch (NoSuchAlgorithmException e) {
                throw new APIException(500, "Server error");
            }

            registerKey(authorization.getIdentity(), keyPair.getPublic());

            String pubkey_pem = null, privkey_pem = null;
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                pubkey_pem = writer.toString();
            } catch (IOException e) {
            }
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PRIVATE KEY", keyPair.getPrivate().getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                privkey_pem = writer.toString();
            } catch (IOException e) {
            }

            result.put("publickey_DER_BASE64",
                    Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()));
            result.put("privatekey_DER_BASE64",
                    Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()));
            result.put("publickey_PEM", pubkey_pem);
            result.put("privatekey_PEM", privkey_pem);
            result.put("keyhash", IO.getKeyHash(keyPair.getPublic()));
            try {
                result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(keyPair.getPublic()), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            }
            result.put("key-size", keySize);
            result.put("message",
                    "Successfully created and registered key. Make sure to copy the private key, it won't be saved on the server");

            return result;
        }
        throw new APIException(400, "Unsupported algorithm");
    } else if (post.get("register", null) != null) {

        if (algorithm.equals("RSA")) {
            String type = post.get("type", null);
            if (type == null)
                type = "DER";

            RSAPublicKey pub;
            String encodedKey;
            try {
                encodedKey = URLDecoder.decode(post.get("register", null), "UTF-8");
            } catch (Throwable e) {
                throw new APIException(500, "Server error");
            }
            Log.getLog().info("Key (" + type + "): " + encodedKey);

            if (type.equals("DER")) {
                try {
                    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(encodedKey));
                    pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec);
                } catch (Throwable e) {
                    throw new APIException(400, "Public key not readable (DER)");
                }
            } else if (type.equals("PEM")) {
                try {
                    PemReader pemReader = new PemReader(new StringReader(encodedKey));
                    PemObject pem = pemReader.readPemObject();
                    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pem.getContent());
                    pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec);
                } catch (Exception e) {
                    throw new APIException(400, "Public key not readable (PEM)");
                }
            } else {
                throw new APIException(400, "Invalid value for 'type'.");
            }

            // check key size (not really perfect yet)
            int keySize;
            int bitLength = pub.getModulus().bitLength();
            if (bitLength <= 512) {
                keySize = 512;
            } else if (bitLength <= 1024) {
                keySize = 1024;
            } else if (bitLength <= 2048) {
                keySize = 2048;
            } else if (bitLength <= 4096) {
                keySize = 4096;
            } else {
                keySize = 8192;
            }
            if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == keySize)) {
                throw new APIException(400, "Invalid key length.");
            }

            registerKey(authorization.getIdentity(), pub);

            String pubkey_pem = null;
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PUBLIC KEY", pub.getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                pubkey_pem = writer.toString();
            } catch (IOException e) {
            }

            result.put("publickey_DER_BASE64", Base64.getEncoder().encodeToString(pub.getEncoded()));
            result.put("publickey_PEM", pubkey_pem);
            result.put("keyhash", IO.getKeyHash(pub));
            try {
                result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(pub), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            }
            result.put("message", "Successfully registered key.");

            return result;
        }
        throw new APIException(400, "Unsupported algorithm");
    }

    throw new APIException(400, "Invalid parameter");
}

From source file:org.hyperledger.fabric.sdk.MemberServicesFabricCAImpl.java

/**
 * Enroll the user with member service/*  ww w.  j  a  va 2  s. c o  m*/
 *
 * @param req Enrollment request with the following fields: name, enrollmentSecret
 * @return enrollment
 */
public Enrollment enroll(EnrollmentRequest req) throws EnrollmentException {

    logger.debug(String.format("[MemberServicesFabricCAImpl.enroll] [%s]", req));
    if (req == null) {
        throw new RuntimeException("req is not set");
    }
    final String user = req.getEnrollmentID();
    final String secret = req.getEnrollmentSecret();
    if (StringUtil.isNullOrEmpty(user)) {
        throw new RuntimeException("req.enrollmentID is not set");
    }
    if (StringUtil.isNullOrEmpty(secret)) {
        throw new RuntimeException("req.enrollmentSecret is not set");
    }

    logger.debug("[MemberServicesFabricCAImpl.enroll] Generating keys...");

    try {
        // generate ECDSA keys: signing and encryption keys
        KeyPair signingKeyPair = cryptoPrimitives.ecdsaKeyGen();
        logger.debug("[MemberServicesFabricCAImpl.enroll] Generating keys...done!");
        //  KeyPair encryptionKeyPair = cryptoPrimitives.ecdsaKeyGen();

        PKCS10CertificationRequest csr = cryptoPrimitives.generateCertificationRequest(user, signingKeyPair);
        String pem = cryptoPrimitives.certificationRequestToPEM(csr);
        JsonObjectBuilder factory = Json.createObjectBuilder();
        factory.add("certificate_request", pem);
        JsonObject postObject = factory.build();
        StringWriter stringWriter = new StringWriter();

        JsonWriter jsonWriter = Json.createWriter(new PrintWriter(stringWriter));

        jsonWriter.writeObject(postObject);

        jsonWriter.close();

        String str = stringWriter.toString();

        logger.debug("[MemberServicesFabricCAImpl.enroll] Generating keys...done!");

        String responseBody = httpPost(url + COP_ENROLLMENBASE, str,
                new UsernamePasswordCredentials(user, secret));

        logger.debug("response" + responseBody);

        JsonReader reader = Json.createReader(new StringReader(responseBody));
        JsonObject jsonst = (JsonObject) reader.read();
        String result = jsonst.getString("result");
        boolean success = jsonst.getBoolean("success");
        logger.debug(String.format("[MemberServicesFabricCAImpl] enroll success:[%s], result:[%s]", success,
                result));

        if (!success) {
            EnrollmentException e = new EnrollmentException("COP Failed response success is false. " + result,
                    new Exception());
            logger.error(e.getMessage());
            throw e;
        }

        Base64.Decoder b64dec = Base64.getDecoder();
        String signedPem = new String(b64dec.decode(result.getBytes()));
        logger.info(String.format("[MemberServicesFabricCAImpl] enroll returned pem:[%s]", signedPem));

        Enrollment enrollment = new Enrollment();
        enrollment.setKey(signingKeyPair);
        enrollment.setPublicKey(Hex.toHexString(signingKeyPair.getPublic().getEncoded()));
        enrollment.setCert(signedPem);
        return enrollment;

    } catch (Exception e) {
        EnrollmentException ee = new EnrollmentException(String.format("Failed to enroll user %s ", user), e);
        logger.error(ee.getMessage(), ee);
        throw ee;
    }

}

From source file:com.ikanow.aleph2.analytics.spark.utils.SparkTechnologyUtils.java

/** Takes the command line args and builds the Aleph2 objects required to set up Spark within Aleph2 
 * @param args// w  w w. ja v a 2  s  .  c  o m
 * @return
 * @throws ClassNotFoundException 
 * @throws IllegalAccessException 
 * @throws InstantiationException 
 */
public static Tuple2<IAnalyticsContext, Optional<ProcessingTestSpecBean>> initializeAleph2(final String args[])
        throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    final IAnalyticsContext context = ContextUtils
            .getAnalyticsContext(new String(Base64.getDecoder().decode(args[0].getBytes())));

    final Optional<ProcessingTestSpecBean> test_spec = Optional.of(args).filter(a -> a.length > 1)
            .map(a -> BeanTemplateUtils.from(new String(Base64.getDecoder().decode(args[1].getBytes())),
                    ProcessingTestSpecBean.class).get());

    return Tuples._2T(context, test_spec);
}