Java 类org.apache.commons.codec.binary.Base64 实例源码

项目:plugin-sso-salt    文件:SaltedAuthenticationResource.java   
/**
 * Encrypt the message with the given key.
 * 
 * @param message
 *            Ciphered message.
 * @param secretKey
 *            The secret key.
 * @return the original message.
 */
protected String encrypt(final String message, final String secretKey) throws Exception { // NOSONAR
    // SSO digest algorithm used for password. This
    final MessageDigest md = MessageDigest.getInstance(getDigest());
    final byte[] digestOfPassword = md.digest(secretKey.getBytes(StandardCharsets.UTF_8));
    final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);

    // Cipher implementation.
    final String algo = get("sso.crypt", DEFAULT_IMPL);

    final SecretKey key = new SecretKeySpec(keyBytes, algo);
    final Cipher cipher = Cipher.getInstance(algo);
    cipher.init(Cipher.ENCRYPT_MODE, key);
    final byte[] plainTextBytes = message.getBytes(StandardCharsets.UTF_8);
    final byte[] buf = cipher.doFinal(plainTextBytes);
    final byte[] base64Bytes = Base64.encodeBase64(buf);
    return new String(base64Bytes, StandardCharsets.UTF_8);
}
项目:pivaa    文件:Encryption.java   
/**
 * Encrypt DATA
 * @param value
 * @return
 */
public static String encryptAES_ECB_PKCS5Padding(String value) {
    try {
        byte[] key = {
                1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1
        };
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

        byte[] encrypted = cipher.doFinal(value.getBytes());

        Base64 b64 = new Base64();
        System.out.println("encrypted string: " + new String(b64.encodeBase64(encrypted)));

        return new String(b64.encodeBase64(encrypted));
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return "";
}
项目:AgentWorkbench    文件:AgentClassElement4SimStart.java   
/**
 * This method can be used in order to save the start arguments of the current agent.
 * Internally these arguments will be kept as Base64 encoded Strings in order to 
 * store this configuration also in the SimulationSetup
 *  
 * @param startArguments the startInstances to set for the agent start up
 * @see agentgui.core.project.setup.SimulationSetup
 */
public void setStartArguments(String[] startArguments) {

    if (startArguments.length==0) {
        this.startArguments = null;
        return;
    }
    String[] startArgumentsEncoded = new String[startArguments.length];
    String encodedArgument = null;
    try {
        for (int i = 0; i < startArguments.length; i++) {
            encodedArgument = new String(Base64.encodeBase64(startArguments[i].getBytes("UTF8")));
            startArgumentsEncoded[i] = encodedArgument;
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    this.startArguments = startArgumentsEncoded;
}
项目:ZentrelaCore    文件:RHead.java   
public static ItemStack getSkull(String url) {
    ItemStack head = new ItemStack(Material.SKULL_ITEM, 1, (short) 3);
    if (url.isEmpty())
        return head;
    SkullMeta headMeta = (SkullMeta) head.getItemMeta();
    GameProfile profile = new GameProfile(UUID.randomUUID(), null);
    byte[] encodedData = Base64.encodeBase64(String.format("{textures:{SKIN:{url:\"%s\"}}}", url).getBytes());
    profile.getProperties().put("textures", new Property("textures", new String(encodedData)));
    Field profileField = null;
    try {
        profileField = headMeta.getClass().getDeclaredField("profile");
        profileField.setAccessible(true);
        profileField.set(headMeta, profile);
    } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e1) {
        e1.printStackTrace();
    }
    head.setItemMeta(headMeta);
    return head;
}
项目:elastic-job-cloud    文件:WwwAuthFilter.java   
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    String authorization = httpRequest.getHeader("authorization");
    if (null != authorization && authorization.length() > AUTH_PREFIX.length()) {
        authorization = authorization.substring(AUTH_PREFIX.length(), authorization.length());
        if ((rootUsername + ":" + rootPassword).equals(new String(Base64.decodeBase64(authorization)))) {
            authenticateSuccess(httpResponse, false);
            chain.doFilter(httpRequest, httpResponse);
        } else if ((guestUsername + ":" + guestPassword).equals(new String(Base64.decodeBase64(authorization)))) {
            authenticateSuccess(httpResponse, true);
            chain.doFilter(httpRequest, httpResponse);
        } else {
            needAuthenticate(httpResponse);
        }
    } else {
        needAuthenticate(httpResponse);
    }
}
项目:DMS    文件:AES256.java   
public static String decrypt(String str) {
    if (str == null) return null;
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec,
                new IvParameterSpec(ips.getBytes("UTF-8")));

        byte[] byteStr = Base64.decodeBase64(str.getBytes());
        String Str = new String(cipher.doFinal(byteStr), "UTF-8");

        return Str;
    } catch (NoSuchAlgorithmException | NoSuchPaddingException
            | InvalidKeyException | InvalidAlgorithmParameterException
            | IllegalBlockSizeException | BadPaddingException
            | UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return null;
}
项目:azure-libraries-for-java    文件:TestKubernetesCluster.java   
private String getSshKey() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(2048);
    KeyPair keyPair=keyPairGenerator.generateKeyPair();
    RSAPublicKey publicKey=(RSAPublicKey)keyPair.getPublic();
    ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(byteOs);
    dos.writeInt("ssh-rsa".getBytes().length);
    dos.write("ssh-rsa".getBytes());
    dos.writeInt(publicKey.getPublicExponent().toByteArray().length);
    dos.write(publicKey.getPublicExponent().toByteArray());
    dos.writeInt(publicKey.getModulus().toByteArray().length);
    dos.write(publicKey.getModulus().toByteArray());
    String publicKeyEncoded = new String(
        Base64.encodeBase64(byteOs.toByteArray()));
    return "ssh-rsa " + publicKeyEncoded + " ";
}
项目:javaOIDCMsg    文件:HMACAlgorithmTest.java   
@Test
public void shouldDoHMAC512SigningWithBytes() throws Exception {
    Algorithm algorithm = Algorithm.HMAC512("secret".getBytes(StandardCharsets.UTF_8));

    String jwtContent = String.format("%s.%s", HS512Header, auth0IssPayload);
    byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8);
    byte[] signatureBytes = algorithm.sign(contentBytes);
    String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes);
    String token = String.format("%s.%s", jwtContent, jwtSignature);
    String expectedSignature = "OXWyxmf-VcVo8viOiTFfLaEy6mrQqLEos5R82Xsx8mtFxQadJAQ1aVniIWN8qT2GNE_pMQPcdzk4x7Cqxsp1dw";

    assertThat(signatureBytes, is(notNullValue()));
    assertThat(jwtSignature, is(expectedSignature));
    JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
    DecodedJWT decoded = jwt.decode(token);
    algorithm.verify(decoded, EncodeType.Base64);
}
项目:javaOIDCMsg    文件:ECDSAAlgorithmTest.java   
@Test
public void shouldFailECDSA256VerificationOnInvalidJOSESignatureLength() throws Exception {
    exception.expect(SignatureVerificationException.class);
    exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA256withECDSA");
    exception.expectCause(isA(SignatureException.class));
    exception.expectCause(hasMessage(is("Invalid JOSE signature format.")));

    byte[] bytes = new byte[63];
    new SecureRandom().nextBytes(bytes);
    String signature = Base64.encodeBase64URLSafeString(bytes);
    String token  = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature;
    Algorithm algorithm = Algorithm.ECDSA256((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_256, "EC"));
    JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
    DecodedJWT decoded = jwt.decode(token);
    algorithm.verify(decoded, EncodeType.Base64);
}
项目:simple-sso    文件:RSAUtil.java   
/**
 * 使用RSA解密字符串
 * 
 * @param src
 * @return
 */
public static String decode(String src) {
    try {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, PRIVATE_KEY);
        return new String(cipher.doFinal(Base64.decodeBase64(src)));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
项目:convertigo-engine    文件:StepView.java   
private void openJscriptStepEditor() {
    Project project = dbo.getProject();
    try {
        // Create private folder if it does not exist
        FileUtils.createFolderIfNotExist(project.getDirPath(), "_private");

        String fileName = FileUtils.createTmpFileWithUTF8Data(
            project.getDirPath(),
            "_private" + "/" + Base64.encodeBase64URLSafeString(DigestUtils.sha1(dbo.getQName())) + " " + dbo.getName() + "." + JSCRIPT_STEP_EDITOR,
            ((SimpleStep) dbo).getExpression()
        );

        studio.createResponse(
            new OpenEditableEditorActionResponse(
                project.getQName() + "/" + "_private" + "/" +  fileName,
                JSCRIPT_STEP_EDITOR
            ).toXml(studio.getDocument(), getObject().getQName())
        );
    }
    catch (Exception e) {
    }
}
项目:ChronoBike    文件:XMLUtil.java   
public static String decode64AsString(String cs)
{
    Base64 base64 = new Base64();
    byte[] arrBytes = cs.getBytes();
    byte[] tOut = base64.decode(arrBytes);
    String csOut = new String(tOut);
    return csOut;
}
项目:lams    文件:LtiOauthSigner.java   
@Override
public HttpRequest sign(HttpRequest request, String key, String secret) throws LtiSigningException {
    CommonsHttpOAuthConsumer signer = new CommonsHttpOAuthConsumer(key, secret);
    try {
        String body = getRequestBody(request);
        String bodyHash = new String(Base64.encodeBase64(md.digest(body.getBytes())));

        HttpParameters params = new HttpParameters();
        params.put("oauth_body_hash", URLEncoder.encode(bodyHash, "UTF-8"));
        signer.setAdditionalParameters(params);

        signer.sign(request);
    } catch (OAuthMessageSignerException|OAuthExpectationFailedException|OAuthCommunicationException|IOException e) {
        throw new LtiSigningException("Exception encountered while singing Lti request...", e);
    }
    return request;
}
项目:sjk    文件:ControllerTest.java   
@Test
public void testbrokenLink() throws IOException, URISyntaxException {

    JSONObject object = new JSONObject();
    object.put("key", "sprSCKKWf8xUeXxEo6Bv0lE1sSjWRDkO");
    object.put("marketName", "eoemarket");
    object.put("count", 1);
    JSONArray data = new JSONArray();
    JSONObject o = new JSONObject();
    o.put("id", -1);
    o.put("link", "http://testsssssss");
    o.put("statusCode", 404);
    data.add(o);
    object.put("data", data);

    String test = "eyJjb3VudCI6IDEwLCAibWFya2V0TmFtZSI6ICJBcHBDaGluYSIsICJkYXRhIjogW3sibGluayI6ICJodHRwOi8vd3d3LmFwcGNoaW5hLmNvbS9hcHAvY29tLmdvb2dsZS5hbmRyb2lkLmFwcHMubWFwcyIsICJpZCI6IDEsICJzdGF0dXNDb2RlIjogNDA0fSwgeyJsaW5rIjogImh0dHA6Ly93d3cuYXBwY2hpbmEuY29tL2FwcC9jb20ud2VhdGhlci5XZWF0aGVyIiwgImlkIjogMiwgInN0YXR1c0NvZGUiOiA0MDR9LCB7ImxpbmsiOiAiaHR0cDovL3d3dy5hcHBjaGluYS5jb20vYXBwL2NvbS5zdHlsZW0ud2FsbHBhcGVycyIsICJpZCI6IDQsICJzdGF0dXNDb2RlIjogNDA0fSwgeyJsaW5rIjogImh0dHA6Ly93d3cuYXBwY2hpbmEuY29tL2FwcC9jb20uc2hhemFtLmVuY29yZS5hbmRyb2lkIiwgImlkIjogNSwgInN0YXR1c0NvZGUiOiA0MDR9LCB7ImxpbmsiOiAiaHR0cDovL3d3dy5hcHBjaGluYS5jb20vYXBwL2NvbS5yaW5nZHJvaWQiLCAiaWQiOiA2LCAic3RhdHVzQ29kZSI6IDQwNH0sIHsibGluayI6ICJodHRwOi8vd3d3LmFwcGNoaW5hLmNvbS9hcHAvY29tLnAxLmNob21wc21zIiwgImlkIjogNywgInN0YXR1c0NvZGUiOiA0MDR9LCB7ImxpbmsiOiAiaHR0cDovL3d3dy5hcHBjaGluYS5jb20vYXBwL2NvbS5oYW5kY2VudC5uZXh0c21zIiwgImlkIjogOCwgInN0YXR1c0NvZGUiOiA0MDR9LCB7ImxpbmsiOiAiaHR0cDovL3d3dy5hcHBjaGluYS5jb20vYXBwL2NvbS5mYWNlYm9vay5rYXRhbmEiLCAiaWQiOiA5LCAic3RhdHVzQ29kZSI6IDQwNH0sIHsibGluayI6ICJodHRwOi8vd3d3LmFwcGNoaW5hLmNvbS9hcHAvY29tLmNvZGUuaS5tdXNpYyIsICJpZCI6IDEwLCAic3RhdHVzQ29kZSI6IDQwNH0sIHsibGluayI6ICJodHRwOi8vd3d3LmFwcGNoaW5hLmNvbS9hcHAvY29tLmJpZ2d1LnNob3BzYXZ2eSIsICJpZCI6IDExLCAic3RhdHVzQ29kZSI6IDQwNH1dLCAia2V5IjogImpqRzhMa0MzTUh5RjlYY3NWS2g2Rkh4bXRMQ05ZdE14In0=";
    Reader input = new StringReader(object.toJSONString());
    byte[] binaryData = IOUtils.toByteArray(input, "UTF-8");
    String encodeBase64 = Base64.encodeBase64String(binaryData);
    System.out.println(encodeBase64);

    String url = "http://localhost:9080/sjk-market-admin/market/brokenLink.d";
    url = "http://app.sjk.ijinshan.com/market/brokenLink.d";
    URIBuilder builder = new URIBuilder(url);
    builder.setParameter("c", test);
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(builder.build());
    HttpResponse response = httpclient.execute(httpPost);
    logger.debug("URI: {} , {}", url, response.getStatusLine());

    HttpEntity entity = response.getEntity();
    InputStream is = entity.getContent();
    // be convinient to debug
    String rspJSON = IOUtils.toString(is, "UTF-8");
    System.out.println(rspJSON);
}
项目:OperatieBRP    文件:LogFilter.java   
private String getGebruikerUitHeader(final String autorisatieString) {

        // Sla de eerste vijf tekens over, deze zijn altijd BASIC.
        if (autorisatieString == null || !autorisatieString.toUpperCase().startsWith("BASIC")) {
            return null;
        }

        String gebruikersnaam;

        try {
            final String decodedString = new String(Base64.decodeBase64(autorisatieString.substring(BEGIN_INDEX_GEBRUIKERSNAAM)), "UTF-8");
            final String[] gebruikerWachtwoordcombi = decodedString.split(":");
            gebruikersnaam = gebruikerWachtwoordcombi[0];
        } catch (final UnsupportedEncodingException exception) {
            LOG.info(BeheerMelding.BEHEER_ONVERWACHTE_FOUT, exception.getMessage());
            LOG.info(exception.getMessage(), exception);
            gebruikersnaam = null;
        }

        return gebruikersnaam;
    }
项目:ysoserial-plus    文件:Wicket1.java   
public DiskFileItem getObject(String command) throws Exception {

        String[] parts = command.split(";");

        if (parts.length != 3) {
            throw new IllegalArgumentException("Bad command format.");
        }

        if ("copyAndDelete".equals(parts[0])) {
            return copyAndDelete(parts[1], parts[2]);
        }
        else if ("write".equals(parts[0])) {
            return write(parts[1], parts[2].getBytes("US-ASCII"));
        }
        else if ("writeB64".equals(parts[0]) ) {
            return write(parts[1], Base64.decodeBase64(parts[2]));
        }
        else if ("writeOld".equals(parts[0]) ) {
            return writeOldJRE(parts[1], parts[2].getBytes("US-ASCII"));
        }
        else if ("writeOldB64".equals(parts[0]) ) {
            return writeOldJRE(parts[1], Base64.decodeBase64(parts[2]));
        }
        throw new IllegalArgumentException("Unsupported command " + command + " " + Arrays.toString(parts));
    }
项目:groupsio-api-java    文件:BaseResource.java   
/**
 * Get a valid {@link HttpClient} to use, with a valid token.
 * 
 * @param login
 * @return
 */
private CloseableHttpClient getHttpClient(final Boolean login, final HttpUriRequest request)
{
    final HttpClientBuilder builder = HttpClientBuilder.create();
    String key;
    // if (apiClient.getApiToken() == null || apiClient.getApiToken())
    if (login)
    {
        key = apiClient.getApiKey();
    }
    else
    {
        key = apiClient.getApiToken();
    }
    key += ":";
    final byte[] credentials = Base64.encodeBase64(key.getBytes(StandardCharsets.UTF_8));
    final BasicHeader authHeader = new BasicHeader("Authorization", "Basic " + new String(credentials, StandardCharsets.UTF_8));
    request.addHeader(authHeader);
    return builder.build();
}
项目:aaden-pay    文件:BaofooPayAdaptor.java   
private Map<String, String> buildQuery(ThirdPayRecord tr) {
    Map<String, String> map = new HashMap<String, String>();

    TransContent<TransReqBF0040002> transContent = new TransContent<TransReqBF0040002>(data_type);
    List<TransReqBF0040002> trans_reqDatas = new ArrayList<TransReqBF0040002>();
    TransReqBF0040002 transReqData = new TransReqBF0040002();
    transReqData.setTrans_no(tr.getSerialnumber());
    trans_reqDatas.add(transReqData);
    transContent.setTrans_reqDatas(trans_reqDatas);

    String bean2XmlString = transContent.obj2Str(transContent);
    logger.info("宝付代付请求原始报文: " + bean2XmlString);
    String origData = new String(Base64.encodeBase64(bean2XmlString.getBytes()));
    String encryptData = BaofooRsaCodingUtil.encryptByPriPfxFile(origData, prx_key, key_password);

    map.put("member_id", this.member_id);
    map.put("terminal_id", this.terminal_id);
    map.put("data_type", data_type);
    map.put("data_content", encryptData);
    map.put("version", "4.0.0");

    return map;
}
项目:bireme    文件:DebeziumPipeLine.java   
@Override
protected String decodeToBit(String data, int precision) {
  switch (data) {
    case "true":
      return "1";
    case "false":
      return "0";
  }

  StringBuilder sb = new StringBuilder();
  String oneByte;
  String result;
  byte[] decoded = Base64.decodeBase64(data);

  ArrayUtils.reverse(decoded);

  for (byte b : decoded) {
    oneByte = String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0');
    sb.append(oneByte);
  }
  result = sb.toString();

  return result.substring(result.length() - precision);
}
项目:cyberduck    文件:IRODSAttributesFinderFeature.java   
@Override
public PathAttributes find(final Path file) throws BackgroundException {
    try {
        final IRODSFileSystemAO fs = session.getClient();
        final IRODSFile f = fs.getIRODSFileFactory().instanceIRODSFile(file.getAbsolute());
        if(!f.exists()) {
            throw new NotfoundException(file.getAbsolute());
        }
        final PathAttributes attributes = new PathAttributes();
        final ObjStat stats = fs.getObjStat(f.getAbsolutePath());
        attributes.setModificationDate(stats.getModifiedAt().getTime());
        attributes.setCreationDate(stats.getCreatedAt().getTime());
        attributes.setSize(stats.getObjSize());
        attributes.setChecksum(Checksum.parse(Hex.encodeHexString(Base64.decodeBase64(stats.getChecksum()))));
        attributes.setOwner(stats.getOwnerName());
        attributes.setGroup(stats.getOwnerZone());
        return attributes;
    }
    catch(JargonException e) {
        throw new IRODSExceptionMappingService().map("Failure to read attributes of {0}", e, file);
    }
}
项目:javaOIDCMsg    文件:ECDSAAlgorithmTest.java   
@Test
public void shouldSignAndVerifyWithECDSA512() throws Exception {
    ECDSAAlgorithm algorithm512 = (ECDSAAlgorithm) Algorithm.ECDSA512((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC"));
    String content512 = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJhdXRoMCJ9";

    for (int i = 0; i < 10; i++) {
        byte[] signature = algorithm512.sign(content512.getBytes());
        String signature512 = Base64.encodeBase64URLSafeString((signature));

        String token  = content512 + "." + signature512;
        JWT jwt = JWT.require(algorithm512).withIssuer("auth0").build();
        DecodedJWT decoded = jwt.decode(token);
        algorithm512.verify(decoded, EncodeType.Base64);
    }
}
项目:personium-core    文件:EntityTypeUtils.java   
/**
 * EntityTypeのPOST(Basic認証).
 * @param cellName セル名
 * @param accountName Basic認証で使用するAccount名
 * @param password Basic認証で使用するパスワード
 * @param boxName box名
 * @param odataSvcPath Odataserviceコレクション名
 * @param name EntityType名
 * @param code 期待するレスポンスコード
 * @return レスポンスコート
 */
public static TResponse createWithBasic(final String cellName,
        final String accountName,
        final String password,
        final String boxName,
        final String odataSvcPath,
        final String name,
        final int code) {
    String credentials = Base64.encodeBase64String((accountName + ":" + password).getBytes());

    TResponse tresponse = Http.request("box/entitySet-post.txt")
            .with("cellPath", cellName)
            .with("boxPath", boxName)
            .with("odataSvcPath", odataSvcPath)
            .with("token", "Basic " + credentials)
            .with("accept", "application/xml")
            .with("Name", name)
            .returns()
            .statusCode(code);
    return tresponse;
}
项目:javaOIDCMsg    文件:RSAAlgorithmTest.java   
@Test
public void shouldThrowWhenThePublicKeyIsInvalid() throws Exception {
    exception.expect(AlgorithmMismatchException.class);
    exception.expectMessage("The provided Algorithm doesn't match the one defined in the JWT's Header.");

    CryptoHelper crypto = mock(CryptoHelper.class);
    when(crypto.verifySignatureFor(anyString(), any(PublicKey.class), any(byte[].class), any(byte[].class)))
            .thenThrow(InvalidKeyException.class);

    RSAPublicKey publicKey = mock(RSAPublicKey.class);
    RSAPrivateKey privateKey = mock(RSAPrivateKey.class);
    RSAKeyProvider provider = RSAAlgorithm.providerForKeys(publicKey, privateKey);
    Algorithm algorithm = new RSAAlgorithm(crypto, "some-alg", "some-algorithm", provider);
    String token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.dxXF3MdsyW-AuvwJpaQtrZ33fAde9xWxpLIg9cO2tMLH2GSRNuLAe61KsJusZhqZB9Iy7DvflcmRz-9OZndm6cj_ThGeJH2LLc90K83UEvvRPo8l85RrQb8PcanxCgIs2RcZOLygERizB3pr5icGkzR7R2y6zgNCjKJ5_NJ6EiZsGN6_nc2PRK_DbyY-Wn0QDxIxKoA5YgQJ9qafe7IN980pXvQv2Z62c3XR8dYuaXBqhthBj-AbaFHEpZapN-V-TmuLNzR2MCB6Xr7BYMuCaqWf_XU8og4XNe8f_8w9Wv5vvgqMM1KhqVpG5VdMJv4o_L4NoCROHhtUQSLRh2M9cA";
    JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
    DecodedJWT decoded = jwt.decode(token);
    algorithm.verify(decoded, EncodeType.Base64);
}
项目:automatic-mower    文件:PasswordDecrypt.java   
/**
 * Descrypt a password using a random key
 * @param key
 * @param secureRandom
 * @param encrypted
 * @return descrypted password
 */
public String decrypt(String key, String secureRandom, String encrypted) {
    try {
        SettingInterface defaultSettingLoader = SettingLoaderFactory.getSettingLoader("default");
        IvParameterSpec ivParam = new IvParameterSpec(secureRandom.getBytes(defaultSettingLoader.getEncoding()));
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(defaultSettingLoader.getEncoding()), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParam);

        byte[] passsword = cipher.doFinal(Base64.decodeBase64(encrypted));

        return new String(passsword);
    } catch (Exception ex) {
        throw new MowerException(WRONG_PASSWORD);
    }
}
项目:convertigo-engine    文件:WriteBase64Step.java   
protected void writeFile(String filePath, NodeList nodeList) throws EngineException {
    if (nodeList == null) {
        throw new EngineException("Unable to write to xml file: element is Null");
    }

    String fullPathName = getAbsoluteFilePath(filePath);
    ComputedFilePath = fullPathName;
    synchronized (Engine.theApp.filePropertyManager.getMutex(fullPathName)) {
        try {
            for (Node node : XMLUtils.toNodeArray(nodeList)) {
                try {
                    String content = node instanceof Element ? ((Element) node).getTextContent() : node.getNodeValue();
                    if (content != null && content.length() > 0) {
                        byte[] bytes = Base64.decodeBase64(content);
                        if (bytes != null && bytes.length > 0) {
                            FileUtils.writeByteArrayToFile(new File(fullPathName), bytes);
                            return;
                        }
                    }
                } catch (Exception e) {
                    Engine.logBeans.info("(WriteBase64Step) Failed to decode and write base64 content : " + e.getClass().getCanonicalName());
                }
            }
        } finally {
            Engine.theApp.filePropertyManager.releaseMutex(fullPathName);
        }
    }
}
项目:magic-beanstalk    文件:AwsEcrAuthData.java   
private void initializeAwsAuthorizationData(String region) throws SdkClientException {
  final Regions awsRegion = Regions.fromName(region);
  AmazonECR ecr = AmazonECRClientBuilder.standard().withRegion(awsRegion).build();

  GetAuthorizationTokenResult authTokenResult = ecr.getAuthorizationToken(
      new GetAuthorizationTokenRequest()
  );
  AuthorizationData authData = authTokenResult.getAuthorizationData().get(0);

  String[] userAuthData = StringUtils.newStringUtf8(Base64.decodeBase64(
      authData.getAuthorizationToken())
  ).split(":");
  registryUsername = userAuthData[0];
  registryPassword = userAuthData[1];
  registryUrl = authData.getProxyEndpoint();
}
项目:Equella    文件:SoapSession.java   
public SoapSession(URL institutionUrl, String username, String password) throws Exception
{
    this.institutionUrl = institutionUrl;
    encoder = new Base64(-1);

    CookieHandler.setDefault(new BasicCookieHandler());
    final URL endpointUrl = new URL(institutionUrl, "services/SoapService51");

    System.setProperty("axis.socketFactory", "com.dytech.edge.importexport.TleDefaultSocketFactory");
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SLF4JLog");
    System.setProperty("org.apache.commons.logging.LogFactory", "org.apache.commons.logging.impl.SLF4JLogFactory");

    final CustomSoapService51Locator locator = new CustomSoapService51Locator();

    client = locator.getSoapService51Endpoint(endpointUrl);

    final PropBagEx userXml = new PropBagEx(client.login(username, password));
    userId = userXml.getNode("uuid");
    loggedIn = true;

    final Map<String, List<String>> fakeHeaders = new HashMap<String, List<String>>();
    fakeHeaders.put("Set-Cookie", locator.getCookiesForUrl(endpointUrl));
    CookieHandler.getDefault().put(endpointUrl.toURI(), fakeHeaders);

    new KeepAlive().start();
}
项目:hadoop-oss    文件:KMSPREClientProvider.java   
private static KeyPairVersion parseJSONKeyPairVersion(Map valueMap) {
  KeyPairVersion keyVersion = null;
  if (!valueMap.isEmpty()) {
    byte[] pkMaterial = (valueMap.containsKey(KMSRESTConstants.PUBLIC_MATERIAL_FIELD))
        ? Base64.decodeBase64((String) valueMap.get(KMSRESTConstants.PUBLIC_MATERIAL_FIELD))
        : null;
    byte[] skMaterial = (valueMap.containsKey(KMSRESTConstants.SECRET_MATERIAL_FIELD))
        ? Base64.decodeBase64((String) valueMap.get(KMSRESTConstants.SECRET_MATERIAL_FIELD))
        : null;
    String versionName = (String)valueMap.get(KMSRESTConstants.VERSION_NAME_FIELD);
    String keyName = (String)valueMap.get(KMSRESTConstants.NAME_FIELD);
    keyVersion = new KMSKeyPairVersion(keyName, versionName,
        new KeyPairMaterial(pkMaterial, skMaterial));
  }
  return keyVersion;
}
项目:javaOIDCMsg    文件:ECDSABouncyCastleProviderTests.java   
@Test
public void shouldDoECDSA512SigningWithBothKeys() throws Exception {
    Algorithm algorithm = Algorithm.ECDSA512((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC"));
    String jwtContent = String.format("%s.%s", ES512Header, auth0IssPayload);
    byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8);
    byte[] signatureBytes = algorithm.sign(contentBytes);
    String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes);
    String token = String.format("%s.%s", jwtContent, jwtSignature);

    assertThat(signatureBytes, is(notNullValue()));
    JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
    DecodedJWT decoded = jwt.decode(token);
    algorithm.verify(decoded, EncodeType.Base64);
}
项目:xproject    文件:Base64Utils.java   
/**
 * 使用Base64对已加密数据进行解密
 * 
 * @param encodedText
 * @return
 */
public static String decode(byte[] bytes) {
    Base64 base64 = new Base64();
    bytes = base64.decode(bytes);
    String s = new String(bytes);
    return s;
}
项目:autorest.java    文件:QueriesImpl.java   
/**
 * Get null as byte array (no query parameters in uri).
 *
 * @throws IllegalArgumentException thrown if parameters fail the validation
 * @return the {@link ServiceResponse} object if successful.
 */
public Observable<ServiceResponse<Void>> byteNullWithServiceResponseAsync() {
    final byte[] byteQuery = new byte[0];
    String byteQueryConverted = Base64.encodeBase64String(byteQuery);
    return service.byteNull(byteQueryConverted)
        .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
            @Override
            public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                try {
                    ServiceResponse<Void> clientResponse = byteNullDelegate(response);
                    return Observable.just(clientResponse);
                } catch (Throwable t) {
                    return Observable.error(t);
                }
            }
        });
}
项目:javaOIDCMsg    文件:ECDSAAlgorithmTest.java   
@Test
public void shouldDoECDSA256SigningWithProvidedPrivateKey() throws Exception {
    ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class);
    PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC");
    PublicKey publicKey = readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC");
    when(provider.getPrivateKey()).thenReturn((ECPrivateKey) privateKey);
    when(provider.getPublicKeyById(null)).thenReturn((ECPublicKey) publicKey);
    Algorithm algorithm = Algorithm.ECDSA256(provider);
    String jwtContent = String.format("%s.%s", ES256Header, auth0IssPayload);
    byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8);
    byte[] signatureBytes = algorithm.sign(contentBytes);
    String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes);
    String token  = String.format("%s.%s", jwtContent, jwtSignature);

    assertThat(signatureBytes, is(notNullValue()));
    JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
    DecodedJWT decoded = jwt.decode(token);
    algorithm.verify(decoded, EncodeType.Base64);
}
项目:javaOIDCMsg    文件:ECDSABouncyCastleProviderTests.java   
@Test
public void shouldDoECDSA512Signing() throws Exception {
    Algorithm algorithmSign = Algorithm.ECDSA512((ECKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC"));
    Algorithm algorithmVerify = Algorithm.ECDSA512((ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"));
    String jwtContent = String.format("%s.%s", ES512Header, auth0IssPayload);
    byte[] contentBytes = jwtContent.getBytes(StandardCharsets.UTF_8);
    byte[] signatureBytes = algorithmSign.sign(contentBytes);
    String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes);
    String token = String.format("%s.%s", jwtContent, jwtSignature);

    assertThat(signatureBytes, is(notNullValue()));
    JWT jwt = JWT.require(algorithmVerify).withIssuer("auth0").build();
    DecodedJWT decoded = jwt.decode(token);
    algorithmVerify.verify(decoded, EncodeType.Base64);
}
项目:hadoop    文件:SecureShuffleUtils.java   
/**
 * verify that base64Hash is same as HMacHash(msg)  
 * @param base64Hash (Base64 encoded hash)
 * @param msg
 * @throws IOException if not the same
 */
public static void verifyReply(String base64Hash, String msg, SecretKey key)
throws IOException {
  byte[] hash = Base64.decodeBase64(base64Hash.getBytes(Charsets.UTF_8));

  boolean res = verifyHash(hash, msg.getBytes(Charsets.UTF_8), key);

  if(res != true) {
    throw new IOException("Verification of the hashReply failed");
  }
}
项目:Sound.je    文件:UUIDConverter.java   
/**
 * Turns a UUID in string format to a Base64 encoded version
 *
 * @param uuidString String representation of the uuid
 * @return base64 encoded version of the uuid
 * @throws IllegalArgumentException String must be a valid uuid
 * @throws NullPointerException     String cannot be null
 */
public static String toBase64(final String uuidString) {
    if (uuidString == null) throw new NullPointerException("String cannot be null");
    if (!isUUID(uuidString)) throw new IllegalArgumentException("string must be a valid uuid");

    final UUID uuid = UUID.fromString(uuidString);
    final ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    return Base64.encodeBase64URLSafeString(bb.array());
}
项目:javaOIDCMsg    文件:RSAAlgorithmTest.java   
@Test
public void shouldFailRSA512VerificationWithInvalidPublicKey() throws Exception {
    exception.expect(SignatureVerificationException.class);
    exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA512withRSA");
    String token = "eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.mvL5LoMyIrWYjk5umEXZTmbyIrkbbcVPUkvdGZbu0qFBxGOf0nXP5PZBvPcOu084lvpwVox5n3VaD4iqzW-PsJyvKFgi5TnwmsbKchAp7JexQEsQOnTSGcfRqeUUiBZqRQdYsho71oAB3T4FnalDdFEpM-fztcZY9XqKyayqZLreTeBjqJm4jfOWH7KfGBHgZExQhe96NLq1UA9eUyQwdOA1Z0SgXe4Ja5PxZ6Fm37KnVDtDlNnY4JAAGFo6y74aGNnp_BKgpaVJCGFu1f1S5xCQ1HSvs8ZSdVWs5NgawW3wRd0kRt_GJ_Y3mIwiF4qUyHWGtsSHu_qjVdCTtbFyow";
    Algorithm algorithm = Algorithm.RSA512((RSAKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE, "RSA"));
    JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
    DecodedJWT decoded = jwt.decode(token);
    algorithm.verify(decoded, EncodeType.Base64);
}
项目:x-rsa    文件:XRsa.java   
public String privateDecrypt(String data){
    try{
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), publicKey.getModulus().bitLength()), CHARSET);
    }catch(Exception e){
        throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
    }
}
项目:database-transform-tool    文件:HttpUtil.java   
/**
 * @param url 请求URL
 * @param method 请求URL
 * @param param json参数(post|put)
 * @return
 */
public static String urlRequest(String url,String method,String param,String auth){
    String result = null;
    try {
        HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
        connection.setConnectTimeout(60*1000);
        connection.setRequestMethod(method.toUpperCase());
        if(auth!=null&&!"".equals(auth)){
            String authorization = "Basic "+new String(Base64.encodeBase64(auth.getBytes()));
            connection.setRequestProperty("Authorization", authorization);
        }
        if(param!=null&&!"".equals(param)){
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.connect();
            DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
            dos.write(param.getBytes(Consts.UTF_8));
            dos.flush();
            dos.close();
        }else{
            connection.connect();
        }
        if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){
            InputStream in = connection.getInputStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int len = 0;
            while((len=in.read(buff, 0, buff.length))>0){
                out.write(buff, 0, len);
            }
            byte[] data = out.toByteArray();
            in.close();
            result = data!=null&&data.length>0?new String(data, Consts.UTF_8):null;
        }else{
            result = "{\"status\":"+connection.getResponseCode()+",\"msg\":\""+connection.getResponseMessage()+"\"}";
        }
        connection.disconnect();
    }catch (Exception e) {
        logger.error("--http request error !",e);
    }
    return result;
}
项目:Notebook    文件:PBECoder.java   
public static void main(String[] args) {

        String str = "hello world";
        String password = "abcd1234";

        byte[] salt = "12345678".getBytes();// 8 byte
//      byte[] salt = new SecureRandom().getSeed(8);
        System.out.println(Base64.encodeBase64String(salt));
        byte[] encriptDatas = encript(str.getBytes(), password, salt);

        byte[] decrptDatas = decrypt(encriptDatas, password, salt);
        System.out.println(new String(decrptDatas));
    }
项目:javaOIDCMsg    文件:ECDSABouncyCastleProviderTests.java   
@Test
public void shouldPassECDSA256VerificationWithJOSESignature() throws Exception {
    String token = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.4iVk3-Y0v4RT4_9IaQlp-8dZ_4fsTzIylgrPTDLrEvTHBTyVS3tgPbr2_IZfLETtiKRqCg0aQ5sh9eIsTTwB1g";
    ECKey key = (ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC");
    Algorithm algorithm = Algorithm.ECDSA256(key);
    JWT jwt = JWT.require(algorithm).withIssuer("auth0").build();
    DecodedJWT decoded = jwt.decode(token);
    algorithm.verify(decoded, EncodeType.Base64);
}