当前位置: 首页>>代码示例>>Java>>正文


Java Base64类代码示例

本文整理汇总了Java中org.apache.commons.codec.binary.Base64的典型用法代码示例。如果您正苦于以下问题:Java Base64类的具体用法?Java Base64怎么用?Java Base64使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Base64类属于org.apache.commons.codec.binary包,在下文中一共展示了Base64类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: setStartArguments

import org.apache.commons.codec.binary.Base64; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:EnFlexIT,项目名称:AgentWorkbench,代码行数:28,代码来源:AgentClassElement4SimStart.java

示例2: encrypt

import org.apache.commons.codec.binary.Base64; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:ligoj,项目名称:plugin-sso-salt,代码行数:27,代码来源:SaltedAuthenticationResource.java

示例3: encryptAES_ECB_PKCS5Padding

import org.apache.commons.codec.binary.Base64; //导入依赖的package包/类
/**
 * 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 "";
}
 
开发者ID:HTBridge,项目名称:pivaa,代码行数:28,代码来源:Encryption.java

示例4: getSkull

import org.apache.commons.codec.binary.Base64; //导入依赖的package包/类
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;
}
 
开发者ID:edasaki,项目名称:ZentrelaCore,代码行数:20,代码来源:RHead.java

示例5: doFilter

import org.apache.commons.codec.binary.Base64; //导入依赖的package包/类
@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);
    }
}
 
开发者ID:elasticjob,项目名称:elastic-job-cloud,代码行数:21,代码来源:WwwAuthFilter.java

示例6: decrypt

import org.apache.commons.codec.binary.Base64; //导入依赖的package包/类
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;
}
 
开发者ID:DSM-DMS,项目名称:DMS,代码行数:21,代码来源:AES256.java

示例7: getSshKey

import org.apache.commons.codec.binary.Base64; //导入依赖的package包/类
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 + " ";
}
 
开发者ID:Azure,项目名称:azure-libraries-for-java,代码行数:18,代码来源:TestKubernetesCluster.java

示例8: shouldDoHMAC512SigningWithBytes

import org.apache.commons.codec.binary.Base64; //导入依赖的package包/类
@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);
}
 
开发者ID:GJWT,项目名称:javaOIDCMsg,代码行数:18,代码来源:HMACAlgorithmTest.java

示例9: shouldFailECDSA256VerificationOnInvalidJOSESignatureLength

import org.apache.commons.codec.binary.Base64; //导入依赖的package包/类
@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);
}
 
开发者ID:GJWT,项目名称:javaOIDCMsg,代码行数:17,代码来源:ECDSAAlgorithmTest.java

示例10: decode

import org.apache.commons.codec.binary.Base64; //导入依赖的package包/类
/**
 * 使用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;
}
 
开发者ID:sheefee,项目名称:simple-sso,代码行数:17,代码来源:RSAUtil.java

示例11: openJscriptStepEditor

import org.apache.commons.codec.binary.Base64; //导入依赖的package包/类
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) {
    }
}
 
开发者ID:convertigo,项目名称:convertigo-engine,代码行数:23,代码来源:StepView.java

示例12: decode64AsString

import org.apache.commons.codec.binary.Base64; //导入依赖的package包/类
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;
}
 
开发者ID:costea7,项目名称:ChronoBike,代码行数:9,代码来源:XMLUtil.java

示例13: sign

import org.apache.commons.codec.binary.Base64; //导入依赖的package包/类
@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;
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:18,代码来源:LtiOauthSigner.java

示例14: testbrokenLink

import org.apache.commons.codec.binary.Base64; //导入依赖的package包/类
@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);
}
 
开发者ID:zhaoxi1988,项目名称:sjk,代码行数:37,代码来源:ControllerTest.java

示例15: getGebruikerUitHeader

import org.apache.commons.codec.binary.Base64; //导入依赖的package包/类
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;
    }
 
开发者ID:MinBZK,项目名称:OperatieBRP,代码行数:22,代码来源:LogFilter.java


注:本文中的org.apache.commons.codec.binary.Base64类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。