org.apache.commons.codec.binary.Base64 # encodeBase64URLSafeString ( ) 源码实例Demo

下面列出了 org.apache.commons.codec.binary.Base64 # encodeBase64URLSafeString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: AthenaServing   文件: RSAUtils.java

public static Map<String, String> createKeys(int keySize) {
	// 为RSA算法创建一个KeyPairGenerator对象
	KeyPairGenerator kpg;
	try {
		kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
	} catch (NoSuchAlgorithmException e) {
		throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
	}

	// 初始化KeyPairGenerator对象,密钥长度
	kpg.initialize(keySize);
	// 生成密匙对
	KeyPair keyPair = kpg.generateKeyPair();
	// 得到公钥
	Key publicKey = keyPair.getPublic();
	String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());
	// 得到私钥
	Key privateKey = keyPair.getPrivate();
	String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded());
	Map<String, String> keyPairMap = new HashMap<String, String>();
	keyPairMap.put("publicKey", publicKeyStr);
	keyPairMap.put("privateKey", privateKeyStr);

	return keyPairMap;
}
 

private void verifyAttestationSignature(Tags tags, RegistrationRecord record)
		throws NoSuchAlgorithmException, IOException, Exception {
	byte[] certBytes = tags.getTags().get(TagsEnum.TAG_ATTESTATION_CERT.id).value;
	record.attestCert = Base64.encodeBase64URLSafeString(certBytes);

	Tag krd = tags.getTags().get(TagsEnum.TAG_UAFV1_KRD.id);
	Tag signature = tags.getTags().get(TagsEnum.TAG_SIGNATURE.id);

	byte[] signedBytes = new byte[krd.value.length + 4];
	System.arraycopy(UnsignedUtil.encodeInt(krd.id), 0, signedBytes, 0, 2);
	System.arraycopy(UnsignedUtil.encodeInt(krd.length), 0, signedBytes, 2,
			2);
	System.arraycopy(krd.value, 0, signedBytes, 4, krd.value.length);

	record.attestDataToSign = Base64.encodeBase64URLSafeString(signedBytes);
	record.attestSignature = Base64
			.encodeBase64URLSafeString(signature.value);
	record.attestVerifiedStatus = "FAILED_VALIDATION_ATTEMPT";

	if (certificateValidator.validate(certBytes, signedBytes,
			signature.value)) {
		record.attestVerifiedStatus = "VALID";
	} else {
		record.attestVerifiedStatus = "NOT_VERIFIED";
	}
}
 
源代码3 项目: nifi   文件: OtpService.java

/**
 * Hashes the specified authentication token. The resulting value will be used as the one time use token.
 *
 * @param authenticationToken   the authentication token
 * @return                      the one time use token
 */
private String hash(final OtpAuthenticationToken authenticationToken) {
    try {
        // input is the user identity and timestamp
        final String input = authenticationToken.getName() + "-" + System.nanoTime();

        // create the secret using secure random
        final SecureRandom secureRandom = new SecureRandom();
        final byte[] randomBytes = new byte[32];
        secureRandom.nextBytes(randomBytes);
        final SecretKeySpec secret = new SecretKeySpec(randomBytes, HMAC_SHA256); // 256 bit

        // hash the input
        final Mac hmacSha256 = Mac.getInstance(HMAC_SHA256);
        hmacSha256.init(secret);
        final byte[] output = hmacSha256.doFinal(input.getBytes(StandardCharsets.UTF_8));

        // return the result as a base 64 string
        return Base64.encodeBase64URLSafeString(output);
    } catch (final NoSuchAlgorithmException | InvalidKeyException e) {
        final String errorMessage = "There was an error generating the OTP";
        logger.error(errorMessage, e);
        throw new IllegalStateException("Unable to generate single use token.");
    }
}
 
源代码4 项目: ECFileCache   文件: ECFileCache.java

/**
 * Create file cache key
 *
 * @param size file size
 * @return fileCacheId. uniq file cache key
 * @throws java.security.InvalidParameterException
 */
public String createFileCacheKey(Integer size) throws ECFileCacheException {

  int clusterSize = monitor.get().getKeyedPool().size();

  String cacheKey = UUID.randomUUID().toString().replace("-", "");
  int offset = genDeviceOffset(clusterSize);

  FileCacheKey fileCacheKey = new FileCacheKey(cacheKey,
      ECodec.VERSION,
      (short) clusterSize,
      (short) offset);

  if (size != null) {
    fileCacheKey.setFileSize(size);
  }

  byte[] bytes = SerializationHelper.toBytes(fileCacheKey);
  return Base64.encodeBase64URLSafeString(bytes);
}
 
源代码5 项目: bootshiro   文件: RsaUtil.java

public static String rsaEncode(String data, String publicKey) {

        try {

            //将字符串形式解析成类
            KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
            RSAPublicKey rsaPublicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);

            Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);

            return Base64.encodeBase64URLSafeString(cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)));

        } catch (Exception e) {
           logger.warn(e.getMessage());
           return null;
        }
    }
 
源代码6 项目: littleca   文件: SimpleTokenManager.java

public   Map<String,String>  vafy(String token) throws SecurityException  {
		if(null==token||"".equals(token)) {
			throw new SecurityException("token格式非法");
		}
		String[] split = token.split("\\.");
		if(split.length>2) {
			throw new SecurityException("token格式非法");
		}
		String sign=split[1];
		byte[] srcData=Base64.decodeBase64(split[0]);
		String data=new String(srcData);
		String sign2 = Base64.encodeBase64URLSafeString(hmac.hmac(srcData));
		if(!sign2.equals(sign)){
			throw new SecurityException("token签名非法");
		}
		Map<String, String> stringToMap = stringToMap(data);
		if(!stringToMap.containsKey("end")){
			return stringToMap;
		}
		Long end=Long.parseLong(stringToMap.get("end"));
		if(System.currentTimeMillis()>end){
			throw new SecurityException("token过期");
		}
		return stringToMap;
	
}
 

public String encryptText(final String text) {
    if (text == null || text.isEmpty()) {
        return text;
    }

    try {
        final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        final SecretKeySpec keySpec = new SecretKeySpec(this.keyIvPair.getKeyBytes(), "AES");

        cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(this.keyIvPair.getIvBytes()));

        final byte[] encryptedBytes = cipher.doFinal(text.getBytes());

        final byte[] ivcipher = concat(this.keyIvPair.getIvBytes(), encryptedBytes);
        final byte[] hmac = generateHMAC(this.authenticationKey, ivcipher);

        return Base64.encodeBase64URLSafeString(concat(ivcipher, hmac));
    } catch (Exception e) {
        s_logger.error("Unexpected exception ", e);
        return null;
    }
}
 
源代码8 项目: java-tutorial   文件: TokenUtil.java

public static String testGetToken(String tokenType) throws Exception {
	String policy = null;
	if (TokenTypeEN.UPLOAD.name().equals(tokenType)) {
		policy = initUploadPolicy();
	} else if (TokenTypeEN.DOWNLOAD.name().equals(tokenType)) {
		policy = initDownladPolicy();
	} else if (TokenTypeEN.MODIFY.name().equals(tokenType)) {
		policy = initModifyPolicy();
	}
	String policyBase64 = Base64.encodeBase64URLSafeString(policy.getBytes());
	String accessKeyBase64 = Base64.encodeBase64URLSafeString(ACCESS_KEY.getBytes());

	System.out.println(String.format("============== %s ==============", tokenType));
	System.out.println("policy:" + policy);
	System.out.println("policyBase64:" + policyBase64);
	System.out.println("accessKeyBase64:" + accessKeyBase64);

	String token = getToken(policy.getBytes(), ACCESS_KEY.getBytes(), SECRET_KEY.getBytes(), tokenType);
	System.out.println("Token:" + token);
	return token;
}
 

@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 jwt = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature;
    Algorithm algorithm = Algorithm.ECDSA256((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_256, "EC"));
    algorithm.verify(JWT.decode(jwt));
}
 
源代码10 项目: java-jwt   文件: ECDSAAlgorithmTest.java

@Test
public void shouldFailECDSA384VerificationOnInvalidJOSESignature() throws Exception {
    exception.expect(SignatureVerificationException.class);
    exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA384withECDSA");

    byte[] bytes = new byte[96];
    new SecureRandom().nextBytes(bytes);
    String signature = Base64.encodeBase64URLSafeString(bytes);
    String jwt = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature;
    Algorithm algorithm = Algorithm.ECDSA384((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_384, "EC"));
    algorithm.verify(JWT.decode(jwt));
}
 
源代码11 项目: redtorch   文件: CommonUtils.java

public static String uuidToBase64(String str) {
	UUID uuid = UUID.fromString(str);
	ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
	bb.putLong(uuid.getMostSignificantBits());
	bb.putLong(uuid.getLeastSignificantBits());
	return Base64.encodeBase64URLSafeString(bb.array());
}
 
源代码12 项目: light   文件: HashUtil.java

public static String generateUUID() {
    UUID id = UUID.randomUUID();
    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(id.getMostSignificantBits());
    bb.putLong(id.getLeastSignificantBits());
    Base64 base64 = new Base64();
    return base64.encodeBase64URLSafeString(bb.array());
}
 
源代码13 项目: projectforge-webapp   文件: NumberHelper.java

/**
 * Generates secure random bytes of the given length and return base 64 encoded bytes as url safe String. This is not the length of the
 * resulting string!
 * @param numberOfBytes
 * @return
 */
public static String getSecureRandomUrlSaveString(final int numberOfBytes)
{
  final SecureRandom random = new SecureRandom();
  final byte[] bytes = new byte[numberOfBytes];
  random.nextBytes(bytes);
  return Base64.encodeBase64URLSafeString(bytes);
}
 
源代码14 项目: nifi   文件: JwtServiceTest.java

private static String generateHMAC(String hmacSecret, String body) throws NoSuchAlgorithmException,
        InvalidKeyException {
    Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
    SecretKeySpec secret_key = new SecretKeySpec(hmacSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
    hmacSHA256.init(secret_key);
    return Base64.encodeBase64URLSafeString(hmacSHA256.doFinal(body.getBytes(StandardCharsets.UTF_8)));
}
 

private ExtensionInterfaceBean getTestBean(String instanceId,
        String subscriptionId, String organizationId) throws Exception {
    instanceAccess = Mockito.mock(InstanceAccess.class);

    serverInfo = getServerInfoMock(3);

    String encodedInstId = Base64.encodeBase64URLSafeString(
            instanceId.getBytes(StandardCharsets.UTF_8));
    String encodedSubId = Base64.encodeBase64URLSafeString(
            subscriptionId.getBytes(StandardCharsets.UTF_8));
    String encodedOrgId = Base64.encodeBase64URLSafeString(
            organizationId.getBytes(StandardCharsets.UTF_8));

    Mockito.when(instanceAccess.getAccessInfo(instanceID, subscriptionID,
            organizationID)).thenReturn("Access info from IaaS");
    Mockito.<List<? extends ServerInformation>> when(instanceAccess
            .getServerDetails(instanceID, subscriptionID, organizationID))
            .thenReturn(serverInfo);

    ExtensionInterfaceBean bean = new ExtensionInterfaceBean();
    bean.setInstanceId(encodedInstId);
    bean.setSubscriptionId(encodedSubId);
    bean.setOrganizationId(encodedOrgId);
    bean.setInstanceAccess(instanceAccess);

    return bean;
}
 
源代码16 项目: spring-boot-cookbook   文件: UrlUtil.java

public static String enCryptAndEncode(String content) {
    try {
        byte[] sourceBytes = enCryptAndEncode(content, KEY);
        return Base64.encodeBase64URLSafeString(sourceBytes);
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        return content;
    }
}
 
源代码17 项目: opencron   文件: Encodes.java

/**
 * Base64编码, URL安全(将Base64中的URL非法字符'+'和'/'转为'-'和'_', 见RFC3548).
 */
public static String encodeUrlSafeBase64(byte[] input) {
    return Base64.encodeBase64URLSafeString(input);
}
 
源代码18 项目: JobX   文件: DigestUtils.java

/**
 * Base64编码, URL安全(将Base64中的URL非法字符'+'和'/'转为'-'和'_', 见RFC3548).
 */
public static String encodeUrlSafeBase64(byte[] input) {
    return Base64.encodeBase64URLSafeString(input);
}
 
源代码19 项目: PacketProxy   文件: JWTBase64.java

@Override
protected String createPayload(String input) throws Exception {
	return Base64.encodeBase64URLSafeString(input.getBytes());
}
 
源代码20 项目: io   文件: DcCoreUtils.java

/**
 * Base64urlのエンコードを行う.
 * 厳密にはRFC4648参照。(といいたいが、少し表現があいまい。) ---------------------------------------------------
 * http://tools.ietf.org/html/rfc4648 --------------------------------------------------- 5. Base 64 Encoding with
 * URL and Filename Safe Alphabet The Base 64 encoding with an URL and filename safe alphabet has been used in [12].
 * URLとファイル名で安全なアルファベットのベース64符号化は[12]で 使われました。 An alternative alphabet has been suggested that would use "~" as the
 * 63rd character. Since the "~" character has special meaning in some file system environments, the encoding
 * described in this section is recommended instead. The remaining unreserved URI character is ".", but some file
 * system environments do not permit multiple "." in a filename, thus making the "." character unattractive as well.
 * 63番目のアルファベットの代わりの文字として"~"を使うのが示唆され ました。"~"文字があるファイルシステム環境で特別な意味を持つので、 この章で記述された符号化はその代わりとして勧められます。残りの予
 * 約なしのURI文字は"."ですが、あるファイルシステム環境で複数の"." は許されず、"."文字も魅力的でありません。 The pad character "=" is typically percent-encoded
 * when used in an URI [9], but if the data length is known implicitly, this can be avoided by skipping the padding;
 * see section 3.2. URI[9]で使われるとき、穴埋め文字"="は一般にパーセント符号化さ れますが、もしデータ長が暗黙のうちにわかるなら、穴埋めをスキップす
 * ることによってこれを避けれます;3.2章を見て下さい。 This encoding may be referred to as "base64url". This encoding should not be regarded
 * as the same as the "base64" encoding and should not be referred to as only "base64". Unless clarified otherwise,
 * "base64" refers to the base 64 in the previous section. この符号化は"base64url"と述べられるかもしれません。この符号化は
 * "base64"符号化と同じと見なされるべきではなくて、単純に「ベース6 4」と述べるべきではありません。他に明示されない限り、"base64"が 前章のベース64を意味します。 This encoding is
 * technically identical to the previous one, except for the 62:nd and 63:rd alphabet character, as indicated in
 * Table 2. この符号化は、62番目と63番目のアルファベット文字が表2で示さ れたものである以外は、技術的に前のものとまったく同じです。 Table 2: The "URL and Filename safe" Base
 * 64 Alphabet 表2:「URLとファイル名で安全な」ベース64アルファベット Value Encoding Value Encoding Value Encoding Value Encoding 0 A 17 R
 * 34 i 51 z 1 B 18 S 35 j 52 0 2 C 19 T 36 k 53 1 3 D 20 U 37 l 54 2 4 E 21 V 38 m 55 3 5 F 22 W 39 n 56 4 6 G 23 X
 * 40 o 57 5 7 H 24 Y 41 p 58 6 8 I 25 Z 42 q 59 7 9 J 26 a 43 r 60 8 10 K 27 b 44 s 61 9 11 L 28 c 45 t 62 -
 * (minus) 12 M 29 d 46 u 63 _ 13 N 30 e 47 v (underline) 14 O 31 f 48 w 15 P 32 g 49 x 16 Q 33 h 50 y (pad) =
 * @param in エンコードしたいbyte列
 * @return エンコードされたあとの文字列
 */
public static String encodeBase64Url(final byte[] in) {
    return Base64.encodeBase64URLSafeString(in);
}