下面列出了 org.apache.commons.codec.binary.Base64 # encodeBase64URLSafe ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private String getLogFileBasename() {
ArrayList<String> basenameElements = new ArrayList<String>();
basenameElements.add(Integer.toString(mGeneration));
if (mKafkaPartitions.length > 1) {
String kafkaPartitions = mKafkaPartitions[0] + "-" +
mKafkaPartitions[mKafkaPartitions.length - 1];
basenameElements.add(kafkaPartitions);
StringBuilder sb = new StringBuilder();
for (long offset : mOffsets) {
sb.append(offset);
}
try {
byte[] md5Bytes = messageDigest.digest(sb.toString().getBytes("UTF-8"));
byte[] encodedBytes = Base64.encodeBase64URLSafe(md5Bytes);
basenameElements.add(new String(encodedBytes));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
} else {
basenameElements.add(Integer.toString(mKafkaPartitions[0]));
basenameElements.add(String.format("%020d", mOffsets[0]));
}
return StringUtils.join(basenameElements, "_");
}
public static void main(String[] args) throws UnsupportedEncodingException {
String url =
"https://www.baidu.com/s?wd=Base64&rsv_spt=1&rsv_iqid=0xa9188d560005131f&issp=1&f=3&rsv_bp=0&rsv_idx=2&ie=utf-8&tn=baiduhome_pg&rsv_enter=1&rsv_sug3=1&rsv_sug1=1&rsv_sug7=001&rsv_sug2=1&rsp=0&rsv_sug9=es_2_1&rsv_sug4=2153&rsv_sug=9";
// byte[] encoded = Base64.encodeBase64(url.getBytes("UTF8")); // 标准的Base64编码
byte[] encoded = Base64.encodeBase64URLSafe(url.getBytes("UTF8")); // URL安全的Base64编码
byte[] decoded = Base64.decodeBase64(encoded);
System.out.println("url:" + url);
System.out.println("encoded:" + new String(encoded));
System.out.println("decoded:" + new String(decoded));
}
/**
* 使用公钥加密操作
*
* @param data 需要加密的数据
* @param key 密钥的二进制形式
* @return 加密后的数据 Base64URL形式
*/
public String encryptURLByPublicKey(String data, byte[] key) {
byte[] result = null;
try {
result = this.encryptByPublicKey(data.getBytes(getConfiguration().getCharset()), key);
return new String(Base64.encodeBase64URLSafe(result), getConfiguration().getCharset());
} catch (UnsupportedEncodingException e) {
throw new CryptographyException(ExceptionInfo.UNSUPPORTED_ENCODING_EXCEPTION_INFO + getConfiguration().getCharset(), e);
}
}
/**
* 使用私钥加密操作
*
* @param data 需要加密的数据
* @param key 私钥的二进制形式
* @return 加密后的数据 Base64URL形式
*/
public String encryptURLByPrivateKey(String data, byte[] key) {
byte[] result = null;
try {
result = this.encryptByPrivateKey(data.getBytes(getConfiguration().getCharset()), key);
return new String(Base64.encodeBase64URLSafe(result), getConfiguration().getCharset());
} catch (UnsupportedEncodingException e) {
throw new CryptographyException(ExceptionInfo.UNSUPPORTED_ENCODING_EXCEPTION_INFO + getConfiguration().getCharset(), e);
}
}
/**
* 加密操作
*
* @param data 需要加密的数据
* @param key 密钥的二进制形式
* @return 加密后的数据 Base64URL形式
*/
public String encryptURL(String data, byte[] key) {
byte[] result = null;
try {
result = this.encrypt(data.getBytes(getConfiguration().getCharset()), key);
return new String(Base64.encodeBase64URLSafe(result), getConfiguration().getCharset());
} catch (UnsupportedEncodingException e) {
throw new CryptographyException(ExceptionInfo.UNSUPPORTED_ENCODING_EXCEPTION_INFO + getConfiguration().getCharset(), e);
}
}
/**
* 加密操作
*
* @param data 需要加密的数据
* @param key 密钥的二进制形式
* @return 加密后的数据 Base64URL形式
*/
public String encryptURL(String data, byte[] key) {
try {
byte[] result = this.encrypt(data.getBytes(getConfiguration().getCharset()), key);
return new String(Base64.encodeBase64URLSafe(result), getConfiguration().getCharset());
} catch (UnsupportedEncodingException e) {
throw new CryptographyException(ExceptionInfo.UNSUPPORTED_ENCODING_EXCEPTION_INFO + getConfiguration().getCharset(), e);
}
}
/**
* Generate an opaque pagination token from the supplied PageMetadata.
*
* @param pageMetadata page metadata of the page for which the token should be generated
* @return opaque pagination token
*/
static String tokenize(PageMetadata<?, ?> pageMetadata) {
try {
Gson g = getGsonWithKeyAdapter(pageMetadata.pageRequestParameters);
return new String(Base64.encodeBase64URLSafe(g.toJson(new PaginationToken
(pageMetadata)).getBytes("UTF-8")),
Charset.forName("UTF-8"));
} catch (UnsupportedEncodingException e) {
//all JVMs should support UTF-8
throw new RuntimeException(e);
}
}
/**
* Encodes a byte array to Base64. URL safe.
* @param str the byte array
* @return an encoded string
*/
public static String base64encURL(byte[] str) {
if (str == null) {
return "";
}
return new String(Base64.encodeBase64URLSafe(str));
}
public SignatureStructImpl(byte[] payload, PrivateKey privateKey) throws IdentifierException {
this.payload = payload;
keyAlg = privateKey.getAlgorithm();
if ("RSA".equals(keyAlg)) {
hashAlg = "SHA256";
header = Util.encodeString("{\"alg\":\"RS256\"}");
} else if ("DSA".equals(keyAlg)) {
hashAlg = "SHA1";
header = Util.encodeString("{\"alg\":\"DS160\"}");
} else if ("EC".equals(keyAlg)){
hashAlg = "SM3";
header = Util.encodeString("{\"alg\":\"SM2SM3\"}");
}else {
throw new IllegalArgumentException("未知算法: " + keyAlg);
}
based64_Header = Base64.encodeBase64URLSafe(header);
based64_Payload = Base64.encodeBase64URLSafe(payload);
try {
if("EC".equals(keyAlg)){
SM2Tool sm2Tool = new SM2Tool();
byte[] bDot = new byte[]{(byte)'.'};
byte[] signData = Util.join(based64_Header,bDot,based64_Payload);
String data = new String(signData);
String id = "1234567812345678";
BigInteger prvKey = ((BCECPrivateKey) privateKey).getD();
ECPoint pubkey = sm2Tool.G.multiply(prvKey).normalize();
cn.ac.caict.iiiiot.id.client.security.gm.SM2Tool.Signature sign = sm2Tool.sign(data, id, new SM2KeyPair(pubkey,prvKey));
//signature转为byte[]
byte[] bR = sign.r.toByteArray();
byte[] bS = sign.s.toByteArray();
signature = BaseConvertor.signatureFormat(bR,bS);
//将byte[]用Base64编码
based64_Signature = Base64.encodeBase64URLSafe(signature);
} else {
Signature sig = Signature.getInstance(hashAlg + "with" + keyAlg);
sig.initSign(privateKey);
sig.update(based64_Header);
sig.update((byte) '.');
sig.update(based64_Payload);
signature = sig.sign();
based64_Signature = Base64.encodeBase64URLSafe(signature);
}
} catch (Exception e) {
throw new IdentifierException(ExceptionCommon.EXCEPTIONCODE_SECURITY_ALERT, "构建签名数据失败");
}
}
/**
* Base64编码, URL安全(将Base64中的URL非法字符'+'和'/'转为'-'和'_', 见RFC3548).
*/
public static byte[] encodeUrlSafeBase64(byte[] input) {
return Base64.encodeBase64URLSafe(input);
}
public Result viewableDownload(
String derivitiveURN,
String dirName
)
throws IOException,
URISyntaxException
{
String urn;
String base64urn;
if( Base64.isBase64(derivitiveURN) )
{
urn = new String( Base64.decodeBase64( derivitiveURN ) );
base64urn = derivitiveURN;
}
else
{
urn = derivitiveURN;
base64urn = new String( Base64.encodeBase64URLSafe( derivitiveURN.getBytes() ));
}
ResultViewerService result = _service.viewableQuery( urn );
if( result.isError() )
{
return result;
}
List<String> files = new LinkedList<String>();
result.listDerivativeFiles( files );
Iterator<String> itr = files.iterator();
while( itr.hasNext() )
{
String fileName = itr.next();
Result dr = _service.viewableDownload( base64urn, dirName, fileName );
if( dr.isError() )
{
System.out.println( dr.toString() );
}
else
{
System.out.println( dirName + "/" + fileName );;
}
}
return result;
}
public static byte[] encodeWithBase64(byte[] input, MdTypeEn type) throws Exception {
return Base64.encodeBase64URLSafe(encode(input, type));
}
public static byte[] encodeWithBase64(byte[] input, ShaTypeEn type) throws Exception {
return Base64.encodeBase64URLSafe(encode(input, type));
}
public static String encoded(String data) throws UnsupportedEncodingException {
byte[] b = Base64.encodeBase64URLSafe(data.getBytes(ENCODING));
return new String(b, ENCODING);
}
@Override
public String buildIDToken(OAuthAuthzReqMessageContext request, OAuth2AuthorizeRespDTO tokenRespDTO)
throws IdentityOAuth2Exception {
String issuer = OAuth2Util.getIDTokenIssuer();
long lifetimeInMillis = Integer.parseInt(config.getOpenIDConnectIDTokenExpiration()) * 1000;
long curTimeInMillis = Calendar.getInstance().getTimeInMillis();
// setting subject
String subject = request.getAuthorizationReqDTO().getUser().getAuthenticatedSubjectIdentifier();
String nonceValue = request.getAuthorizationReqDTO().getNonce();
// Get access token issued time
long accessTokenIssuedTime = getAccessTokenIssuedTime(tokenRespDTO.getAccessToken(), request) / 1000;
String atHash = null;
String responseType = request.getAuthorizationReqDTO().getResponseType();
//at_hash is generated on access token. Hence the check on response type to be id_token token or code
if (!JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName()) &&
!OAuthConstants.ID_TOKEN.equalsIgnoreCase(responseType) &&
!OAuthConstants.NONE.equalsIgnoreCase(responseType)) {
String digAlg = mapDigestAlgorithm(signatureAlgorithm);
MessageDigest md;
try {
md = MessageDigest.getInstance(digAlg);
} catch (NoSuchAlgorithmException e) {
throw new IdentityOAuth2Exception("Invalid Algorithm : " + digAlg);
}
md.update(tokenRespDTO.getAccessToken().getBytes(Charsets.UTF_8));
byte[] digest = md.digest();
int leftHalfBytes = 16;
if (SHA384.equals(digAlg)) {
leftHalfBytes = 24;
} else if (SHA512.equals(digAlg)) {
leftHalfBytes = 32;
}
byte[] leftmost = new byte[leftHalfBytes];
for (int i = 0; i < leftHalfBytes; i++) {
leftmost[i] = digest[i];
}
atHash = new String(Base64.encodeBase64URLSafe(leftmost), Charsets.UTF_8);
}
if (log.isDebugEnabled()) {
StringBuilder stringBuilder = (new StringBuilder())
.append("Using issuer ").append(issuer).append("\n")
.append("Subject ").append(subject).append("\n")
.append("ID Token life time ").append(lifetimeInMillis / 1000).append("\n")
.append("Current time ").append(curTimeInMillis / 1000).append("\n")
.append("Nonce Value ").append(nonceValue).append("\n")
.append("Signature Algorithm ").append(signatureAlgorithm).append("\n");
if (log.isDebugEnabled()) {
log.debug(stringBuilder.toString());
}
}
JWTClaimsSet jwtClaimsSet = new JWTClaimsSet();
jwtClaimsSet.setIssuer(issuer);
jwtClaimsSet.setSubject(subject);
jwtClaimsSet.setAudience(Arrays.asList(request.getAuthorizationReqDTO().getConsumerKey()));
jwtClaimsSet.setClaim("azp", request.getAuthorizationReqDTO().getConsumerKey());
jwtClaimsSet.setExpirationTime(new Date(curTimeInMillis + lifetimeInMillis));
jwtClaimsSet.setIssueTime(new Date(curTimeInMillis));
jwtClaimsSet.setClaim("auth_time", accessTokenIssuedTime);
if(atHash != null){
jwtClaimsSet.setClaim("at_hash", atHash);
}
if (nonceValue != null) {
jwtClaimsSet.setClaim("nonce", nonceValue);
}
request.addProperty(OAuthConstants.ACCESS_TOKEN, tokenRespDTO.getAccessToken());
CustomClaimsCallbackHandler claimsCallBackHandler =
OAuthServerConfiguration.getInstance().getOpenIDConnectCustomClaimsCallbackHandler();
claimsCallBackHandler.handleCustomClaims(jwtClaimsSet, request);
if (JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName())) {
return new PlainJWT(jwtClaimsSet).serialize();
}
return signJWT(jwtClaimsSet, request);
}
/**
* Utility function to encrypt a plainText with a baseKey
*
* @author Nidhish
* @param plainText - valid plain text
* @param baseKey - valid base key
* @return Encrypted string value
* @throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
*/
public static String encrypt(String plainText, final String baseKey) throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
SecretKey secretKey = getSecretKey(baseKey);
byte[] plainTextByte = plainText.getBytes();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, getIvParameterSpec());
byte[] encryptedByte = cipher.doFinal(plainTextByte);
return new String(Base64.encodeBase64URLSafe(encryptedByte));
}
/**
* Encrypt the binary data using the default passphrase.
* For encrypting, the data will first be padded to a safe number of
* bytes with randomized data.
*
* @param unencrypted The binary data to encrypt
*
* @return the encrypted string Base64-encoded.
*
* @see Encryptor#pad(byte[], int)
*/
public static String encrypt(final byte[] unencrypted)
{
return new String(
Base64.encodeBase64URLSafe(Encryptor.encryptRaw(unencrypted)), LicensingCharsets.UTF_8
);
}
/**
* Encrypt the binary data. For encrypting, the
* data will first be padded to a safe number of
* bytes with randomized data.
*
* @param unencrypted The binary data to encrypt
* @param passphrase The passphrase to encrypt the data with
*
* @return the encrypted string Base64-encoded.
*
* @see Encryptor#pad(byte[], int)
*/
public static String encrypt(final byte[] unencrypted, final char[] passphrase)
{
return new String(
Base64.encodeBase64URLSafe(Encryptor.encryptRaw(
unencrypted, passphrase
)),
LicensingCharsets.UTF_8
);
}