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:org.wso2.sample.identity.oauth2.IDTokenDecrypterServlet.java

/**
 * Decrypt the id token using the private key.
 *
 * @param JWE              id token to be decrypted
 * @param privateKeyString client private key as a string
 * @return decrypted id token as an EncryptedJWT object
 * @throws NoSuchAlgorithmException//from w w  w  .  j  a va  2 s . co  m
 * @throws InvalidKeySpecException
 * @throws ParseException
 * @throws JOSEException
 * @throws IllegalArgumentException
 */
private EncryptedJWT decryptJWE(String JWE, String privateKeyString) throws NoSuchAlgorithmException,
        InvalidKeySpecException, ParseException, JOSEException, IllegalArgumentException {

    KeyFactory kf = KeyFactory.getInstance("RSA");
    // Remove EOF characters from key string and generate key object.
    privateKeyString = privateKeyString.replace("\n", "").replace("\r", "");
    PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyString));
    PrivateKey privateKey = kf.generatePrivate(keySpecPKCS8);

    EncryptedJWT jwt = EncryptedJWT.parse(JWE);

    // Create a decrypter with the specified private RSA key.
    RSADecrypter decrypter = new RSADecrypter((RSAPrivateKey) privateKey);

    jwt.decrypt(decrypter);

    return jwt;
}

From source file:com.thoughtworks.go.server.util.EncryptionHelperTest.java

@Test
void shouldEncryptAndDecryptChunkUsingAESandRSA() throws Exception {
    String chunk = StringUtils.repeat("Encryption is awesome!", 150);

    File privateKeyFile = new File(
            getClass().getClassLoader().getResource("rsa/subordinate-private.pem").getFile());
    File publicKeyFile = new File(
            getClass().getClassLoader().getResource("rsa/subordinate-public.pem").getFile());

    SecretKey secretKey = EncryptionHelper.generateAESKey();

    String aesEncryptedData = EncryptionHelper.encryptUsingAES(secretKey, chunk);
    String rsaEncryptedAESKey = EncryptionHelper.encryptUsingRSA(
            Base64.getEncoder().encodeToString(secretKey.getEncoded()),
            FileUtils.readFileToString(publicKeyFile, "utf8"));

    String secretKeyContent = EncryptionHelper.decryptUsingRSA(rsaEncryptedAESKey,
            FileUtils.readFileToString(privateKeyFile, "utf8"));
    byte[] decryptedKey = Base64.getDecoder().decode(secretKeyContent);
    secretKey = new SecretKeySpec(decryptedKey, 0, decryptedKey.length, "AES");

    String decryptedData = EncryptionHelper.decryptUsingAES(secretKey, aesEncryptedData);

    assertThat(chunk, is(decryptedData));
}

From source file:org.wso2.carbon.apimgt.impl.reportgen.ReportGenerator.java

private String getMetaCount(String origCount) {
    String count = origCount;//from   w w  w  .  j a va  2  s  .c  o m
    Cipher cipher;

    try {
        cipher = Cipher.getInstance(MGW_ALGO);
        SecretKeySpec key = new SecretKeySpec(Base64.getDecoder().decode(MGW_KEY), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] bytes = cipher.doFinal(origCount.getBytes());
        count = new String(Base64.getEncoder().encode(bytes));
    } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | BadPaddingException
            | IllegalBlockSizeException e) {
        log.info("Couldn't generate the value for Summary report meta field.", e);
    }

    return count;
}

From source file:ddf.catalog.transformer.output.rtf.BaseTestConfiguration.java

Attribute createMediaAttribute() throws IOException {
    Attribute mockAttribute = mock(Attribute.class);
    byte[] image = Base64.getDecoder().decode(getReferenceImageString());
    when(mockAttribute.getValue()).thenReturn(image);

    return mockAttribute;
}

From source file:com.github.horrorho.inflatabledonkey.cloud.escrow.EscrowedKeys.java

static ServiceKeySet escrowedKeys(NSDictionary record, ServiceKeySet backupBagPassword) {
    String metadataBase64 = PLists.getAs(record, "metadata", NSString.class).getContent();
    byte[] metadata = Base64.getDecoder().decode(metadataBase64);

    byte[] data = ProtectedRecord.unlockData(metadata, backupBagPassword::key);

    return DERUtils.parse(data, KeySet::new).flatMap(ServiceKeySetBuilder::build)
            .orElseThrow(() -> new IllegalArgumentException("failed to create escrowed key set"));
}

From source file:com.tenduke.example.scribeoauth.oauth2.IdTokenOauth20Service.java

/**
 * Gets Id token using the result obtained from a {@link #getAccessToken(org.scribe.model.Token, org.scribe.model.Verifier)}
 * call made earlier.// w  ww  . j  av a 2  s  . c  o m
 * @return Id token (Open Id scope) read from access token response that was cached in call to
 *         {@link #getAccessToken(org.scribe.model.Token, org.scribe.model.Verifier)}.
 */
public JSONObject getIdToken() {
    //
    if (accessTokenResponse == null) {
        //
        throw new IllegalStateException(
                "Access token request not made yet, can't extract OpenId scope Id token");
    }
    //
    JSONObject retValue = null;
    //
    JSONObject atResponse = new JSONObject(accessTokenResponse);
    String idToken = atResponse.getString("id_token");
    byte[] idContent = null;
    if (idToken != null && idToken.indexOf(".") > 0) {
        //
        String[] jwtParts = idToken.split("\\.");
        String jwtBody = jwtParts[1];
        idContent = Base64.getDecoder().decode(jwtBody);
    }
    //
    if (idContent != null) {
        //
        try {
            //
            retValue = new JSONObject(new String(idContent, "UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            //
            // yes, bad style here. "Real" applications should not suppress exceptions like this
        }
    }
    //
    return retValue;
}

From source file:io.gomint.server.network.packet.PacketLogin.java

private void decodeBase64JSON(String data) throws ParseException {
    try {//from   www . j av a2 s .  c o m
        // Get validation key
        Key key = getPublicKey(Base64.getDecoder().decode(this.validationKey));
        if (key == null) {
            return;
        }

        // Check JWT
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(data).getBody();

        // Only certification authory is allowed to set new validation keys
        Boolean certificateAuthority = (Boolean) claims.get("certificateAuthority");
        if (certificateAuthority != null && certificateAuthority) {
            this.validationKey = (String) claims.get("identityPublicKey");

            // We have to blindy trust this auth when its the first (they send the root cert in 0.15.4+)
            if (this.firstCertAuth && this.validationKey.equals(MOJANG_PUBLIC)) {
                this.firstCertAuth = false;
                return;
            }
        }

        // Invalid duration frame ?
        if (claims.getExpiration().getTime() - claims.getIssuedAt().getTime() != TimeUnit.DAYS.toMillis(1)) {
            System.out.println("Certification lifetime is not 1 day.");
            this.valid = false;
        }

        // Invalid Issuer ?
        if (!"RealmsAuthorization".equals(claims.getIssuer())) {
            System.out.println("Certification issuer is wrong.");
            this.valid = false;
        }

        // Check for extra data
        Map<String, Object> extraData = (Map<String, Object>) claims.get("extraData");
        if (extraData != null) {
            // For a valid user we need a XUID (xbox live id)
            String xboxId = (String) extraData.get("XUID");
            if (xboxId == null) {
                System.out.println("Did not find any xbox live id");
                this.valid = false;
            } else {
                this.xboxId = Long.parseLong(xboxId);
            }

            this.userName = (String) extraData.get("displayName");
            this.uuid = UUID.fromString((String) extraData.get("identity"));
        }
    } catch (Exception e) {
        // This normally comes when the user is not logged in into xbox live since the payload only sends
        // the self signed cert without a certifaction authory
        this.valid = false;

        // Be able to "parse" the payload
        String[] tempBase64 = data.split("\\.");

        String payload = new String(Base64.getDecoder().decode(tempBase64[1]));
        JSONObject chainData = (JSONObject) new JSONParser().parse(payload);
        if (chainData.containsKey("extraData")) {
            JSONObject extraData = (JSONObject) chainData.get("extraData");
            this.userName = (String) extraData.get("displayName");
            this.uuid = UUID.fromString((String) extraData.get("identity"));
        }
    }
}

From source file:com.bosch.iot.things.tutorial.ui.ProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;//from  w ww.  ja  v a2  s.  c  o  m
    }

    try {
        long time = System.currentTimeMillis();
        CloseableHttpClient c = getHttpClient();

        String targetUrl = URL_PREFIX + req.getPathInfo()
                + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "");
        BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl);

        String user = "";
        if (auth.toUpperCase().startsWith("BASIC ")) {
            String userpassDecoded = new String(Base64.getDecoder().decode(auth.substring("BASIC ".length())));
            user = userpassDecoded.substring(0, userpassDecoded.indexOf(':'));
            String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
            targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null));
        }

        targetReq.addHeader("x-cr-api-token", req.getHeader("x-cr-api-token"));
        CloseableHttpResponse targetResp = c.execute(targetHost, targetReq);

        System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> "
                + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine());

        resp.setStatus(targetResp.getStatusLine().getStatusCode());
        targetResp.getEntity().writeTo(resp.getOutputStream());
    } catch (IOException | AuthenticationException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.egov.mrs.domain.entity.RegistrationCertificate.java

public static InputStream decodePhoto(final String encodedString) throws IOException {

    final OutputStream os = new ByteArrayOutputStream();
    os.write(0xFF);//from w  w w  .j a  v  a  2  s . c  o m
    os.write(216);
    final byte[] orginalFileData = Base64.getDecoder().decode(encodedString);
    final byte[] fileData = new byte[orginalFileData.length + 2];
    fileData[0] = (byte) 0xFF;
    fileData[1] = (byte) 216;
    int j = 2;

    for (int i = 0; i < orginalFileData.length - 1; i++)
        fileData[j++] = orginalFileData[i];

    return new ByteArrayInputStream(fileData);

}

From source file:org.flowable.cmmn.engine.impl.history.async.json.transformer.VariableCreatedHistoryJsonTransformer.java

@Override
public void transformJson(HistoryJobEntity job, ObjectNode historicalData, CommandContext commandContext) {
    HistoricVariableService historicVariableService = CommandContextUtil.getHistoricVariableService();
    HistoricVariableInstanceEntity historicVariableInstanceEntity = historicVariableService
            .createHistoricVariableInstance();
    historicVariableInstanceEntity.setId(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_ID));
    historicVariableInstanceEntity//from   www .j a va 2 s .  com
            .setScopeId(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_SCOPE_ID));
    historicVariableInstanceEntity
            .setSubScopeId(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_SUB_SCOPE_ID));
    historicVariableInstanceEntity
            .setScopeType(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_SCOPE_TYPE));
    historicVariableInstanceEntity
            .setTaskId(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_TASK_ID));
    historicVariableInstanceEntity
            .setExecutionId(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_EXECUTION_ID));
    historicVariableInstanceEntity.setProcessInstanceId(
            getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_PROCESS_INSTANCE_ID));
    historicVariableInstanceEntity
            .setRevision(getIntegerFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_REVISION));
    historicVariableInstanceEntity
            .setName(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_NAME));

    VariableTypes variableTypes = CommandContextUtil.getCmmnEngineConfiguration().getVariableTypes();
    VariableType variableType = variableTypes
            .getVariableType(getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_VARIABLE_TYPE));

    historicVariableInstanceEntity.setVariableType(variableType);

    historicVariableInstanceEntity.setTextValue(
            getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_VARIABLE_TEXT_VALUE));
    historicVariableInstanceEntity.setTextValue2(
            getStringFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_VARIABLE_TEXT_VALUE2));
    historicVariableInstanceEntity.setDoubleValue(
            getDoubleFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_VARIABLE_DOUBLE_VALUE));
    historicVariableInstanceEntity
            .setLongValue(getLongFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_VARIABLE_LONG_VALUE));

    String variableBytes = getStringFromJson(historicalData,
            CmmnAsyncHistoryConstants.FIELD_VARIABLE_BYTES_VALUE);
    if (StringUtils.isNotEmpty(variableBytes)) {
        historicVariableInstanceEntity.setBytes(Base64.getDecoder().decode(variableBytes));
    }

    Date time = getDateFromJson(historicalData, CmmnAsyncHistoryConstants.FIELD_CREATE_TIME);
    historicVariableInstanceEntity.setCreateTime(time);
    historicVariableInstanceEntity.setLastUpdatedTime(time);

    historicVariableService.insertHistoricVariableInstance(historicVariableInstanceEntity);
}