當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。