List of usage examples for org.apache.commons.codec.binary Base64 encodeBase64URLSafe
public static byte[] encodeBase64URLSafe(final byte[] binaryData)
From source file:org.cloudfoundry.identity.uaa.provider.oauth.XOAuthAuthenticationManagerIT.java
@Test public void verify_hmac_256_signature() throws Exception { String key = "key"; String data = "data"; SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(secretKey);/*from www . java 2 s . c o m*/ byte[] hmacData = mac.doFinal(data.getBytes("UTF-8")); assertThat(new String(Base64.encodeBase64URLSafe(hmacData)), equalTo(xoAuthAuthenticationManager.hmacSignAndEncode(data, key))); }
From source file:org.emmanet.util.Encrypter.java
public String encrypt(String str) { try {/*from w ww . j a v a2 s . c o m*/ // Encode the string into bytes using utf-8 byte[] utf8 = str.getBytes("UTF8"); // Encrypt byte[] enc = ecipher.doFinal(utf8); // Encode bytes to base64 to get a string // return new sun.misc.BASE64Encoder().encode(enc); byte[] encodedBytes = Base64.encodeBase64URLSafe(enc); System.out.println("NEW COMMONS CODEC ENCRYPTED STRING IS :: " + new String(encodedBytes) + " AND STRING WAS :: " + str); return new String(encodedBytes); } catch (BadPaddingException ex) { Logger.getLogger(Encrypter.class.getName()).log(Level.SEVERE, null, ex); } catch (IllegalBlockSizeException e) { } catch (UnsupportedEncodingException e) { } catch (java.io.IOException e) { } return null; }
From source file:org.mitre.jwt.model.Jwt.java
/** * The signature base of a JWT is the header in Base64, a period ".", and the claims in Base64. *//* w ww . jav a2 s .co m*/ public String getSignatureBase() { JsonObject h = header.getAsJsonObject(); JsonObject c = claims.getAsJsonObject(); String h64 = new String(Base64.encodeBase64URLSafe(h.toString().getBytes())); String c64 = new String(Base64.encodeBase64URLSafe(c.toString().getBytes())); return h64 + "." + c64; }
From source file:org.mitre.jwt.signer.impl.HmacSigner.java
@Override public String generateSignature(String signatureBase) throws NoSuchAlgorithmException { initializeMac();//w ww. j a v a 2 s . co m if (passphrase == null) { throw new IllegalArgumentException("Passphrase cannot be null"); } try { mac.init(new SecretKeySpec(getPassphrase().getBytes(), mac.getAlgorithm())); mac.update(signatureBase.getBytes("UTF-8")); } catch (GeneralSecurityException e) { logger.error(e); } catch (UnsupportedEncodingException e) { logger.error(e); } byte[] sigBytes = mac.doFinal(); String sig = new String(Base64.encodeBase64URLSafe(sigBytes)); // strip off any padding sig = sig.replace("=", ""); return sig; }
From source file:org.mitre.jwt.signer.impl.RsaSigner.java
@Override public String generateSignature(String signatureBase) throws NoSuchAlgorithmException { String sig = null;/*from w w w. j av a 2 s . c om*/ initializeSigner(); try { signer.initSign(privateKey); signer.update(signatureBase.getBytes("UTF-8")); byte[] sigBytes = signer.sign(); sig = (new String(Base64.encodeBase64URLSafe(sigBytes))).replace("=", ""); } catch (GeneralSecurityException e) { logger.error(e); } catch (UnsupportedEncodingException e) { logger.error(e); } return sig; }
From source file:org.mitre.openid.connect.client.AbstractOIDCAuthenticationFilter.java
/** * Returns the signature text for the byte array of data * //w w w.j a v a 2 s. c o m * @param signer * The algorithm to sign with * @param privateKey * The private key to sign with * @param data * The data to be signed * @return The signature text */ public static String sign(Signature signer, PrivateKey privateKey, byte[] data) { String signature; try { signer.initSign(privateKey); signer.update(data); byte[] sigBytes = signer.sign(); signature = (new String(Base64.encodeBase64URLSafe(sigBytes))).replace("=", ""); } catch (GeneralSecurityException generalSecurityException) { // generalSecurityException.printStackTrace(); throw new IllegalStateException(generalSecurityException); } return signature; }
From source file:org.teatrove.teaapps.contexts.EncodingContext.java
/** * Encode the given integer array into Base64 format. * // w w w .j a v a 2 s . co m * @param input The array of integers to encode * * @return The Base64 encoded data * * @throws IOException if an error occurs encoding the array stream * * @see #decodeIntArray(String) */ public String encodeIntArray(int[] input) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); int length = input.length; dos.writeInt(length); for (int i = 0; i < length; i++) { dos.writeInt(input[i]); } return new String(Base64.encodeBase64URLSafe(bos.toByteArray())); }
From source file:org.wso2.carbon.identity.oauth2.util.OAuth2Util.java
public static boolean doPKCEValidation(String referenceCodeChallenge, String codeVerifier, String challenge_method, OAuthAppDO oAuthAppDO) throws IdentityOAuth2Exception { //ByPass PKCE validation if PKCE Support is disabled if (!isPKCESupportEnabled()) { return true; }//from w w w . j a va 2s.com if (oAuthAppDO != null && oAuthAppDO.isPkceMandatory() || referenceCodeChallenge != null) { //As per RFC 7636 Fallback to 'plain' if no code_challenge_method parameter is sent if (challenge_method == null || challenge_method.trim().length() == 0) { challenge_method = "plain"; } //if app with no PKCE code verifier arrives if ((codeVerifier == null || codeVerifier.trim().length() == 0)) { //if pkce is mandatory, throw error if (oAuthAppDO.isPkceMandatory()) { throw new IdentityOAuth2Exception( "No PKCE code verifier found.PKCE is mandatory for this " + "oAuth 2.0 application."); } else { //PKCE is optional, see if the authz code was requested with a PKCE challenge if (referenceCodeChallenge == null || referenceCodeChallenge.trim().length() == 0) { //since no PKCE challenge was provided return true; } else { throw new IdentityOAuth2Exception("Empty PKCE code_verifier sent. This authorization code " + "requires a PKCE verification to obtain an access token."); } } } //verify that the code verifier is upto spec as per RFC 7636 if (!validatePKCECodeVerifier(codeVerifier)) { throw new IdentityOAuth2Exception("Code verifier used is not up to RFC 7636 specifications."); } if (OAuthConstants.OAUTH_PKCE_PLAIN_CHALLENGE.equals(challenge_method)) { //if the current application explicitly doesn't support plain, throw exception if (!oAuthAppDO.isPkceSupportPlain()) { throw new IdentityOAuth2Exception( "This application does not allow 'plain' transformation algorithm."); } if (!referenceCodeChallenge.equals(codeVerifier)) { return false; } } else if (OAuthConstants.OAUTH_PKCE_S256_CHALLENGE.equals(challenge_method)) { try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte[] hash = messageDigest.digest(codeVerifier.getBytes(StandardCharsets.US_ASCII)); //Trim the base64 string to remove trailing CR LF characters. String referencePKCECodeChallenge = new String(Base64.encodeBase64URLSafe(hash), StandardCharsets.UTF_8).trim(); if (!referencePKCECodeChallenge.equals(referenceCodeChallenge)) { return false; } } catch (NoSuchAlgorithmException e) { if (log.isDebugEnabled()) { log.debug("Failed to create SHA256 Message Digest."); } return false; } } else { //Invalid OAuth2 token response throw new IdentityOAuth2Exception( "Invalid OAuth2 Token Response. Invalid PKCE Code Challenge Method '" + challenge_method + "'"); } } //pkce validation successful return true; }
From source file:org.wso2.carbon.identity.openidconnect.DefaultIDTokenBuilder.java
@Override public String buildIDToken(OAuthTokenReqMessageContext request, OAuth2AccessTokenRespDTO tokenRespDTO) throws IdentityOAuth2Exception { String tenantDomain = request.getOauth2AccessTokenReqDTO().getTenantDomain(); IdentityProvider identityProvider = getResidentIdp(tenantDomain); FederatedAuthenticatorConfig[] fedAuthnConfigs = identityProvider.getFederatedAuthenticatorConfigs(); // Get OIDC authenticator FederatedAuthenticatorConfig samlAuthenticatorConfig = IdentityApplicationManagementUtil .getFederatedAuthenticator(fedAuthnConfigs, IdentityApplicationConstants.Authenticator.OIDC.NAME); String issuer = IdentityApplicationManagementUtil .getProperty(samlAuthenticatorConfig.getProperties(), OPENID_IDP_ENTITY_ID).getValue(); long lifetimeInMillis = Integer.parseInt(config.getOpenIDConnectIDTokenExpiration()) * 1000; long curTimeInMillis = Calendar.getInstance().getTimeInMillis(); // setting subject String subject = request.getAuthorizedUser().getAuthenticatedSubjectIdentifier(); if (!GrantType.AUTHORIZATION_CODE.toString().equals(request.getOauth2AccessTokenReqDTO().getGrantType()) && !org.wso2.carbon.identity.oauth.common.GrantType.SAML20_BEARER.toString() .equals(request.getOauth2AccessTokenReqDTO().getGrantType())) { ApplicationManagementService applicationMgtService = OAuth2ServiceComponentHolder .getApplicationMgtService(); ServiceProvider serviceProvider = null; try {// w ww. j a va2s. c o m String spName = applicationMgtService.getServiceProviderNameByClientId( request.getOauth2AccessTokenReqDTO().getClientId(), INBOUND_AUTH2_TYPE, tenantDomain); serviceProvider = applicationMgtService.getApplicationExcludingFileBasedSPs(spName, tenantDomain); } catch (IdentityApplicationManagementException e) { throw new IdentityOAuth2Exception("Error while getting service provider information.", e); } if (serviceProvider != null) { String subjectClaim = serviceProvider.getLocalAndOutBoundAuthenticationConfig() .getSubjectClaimUri(); ClaimConfig claimConfig = serviceProvider.getClaimConfig(); if (claimConfig != null) { boolean isLocalClaimDialect = claimConfig.isLocalClaimDialect(); ClaimMapping[] claimMappings = claimConfig.getClaimMappings(); if (!isLocalClaimDialect && claimMappings.length > 0) { for (ClaimMapping claimMapping : claimMappings) { if (StringUtils.isNotBlank(subjectClaim) && StringUtils .equals(claimMapping.getRemoteClaim().getClaimUri(), subjectClaim)) { subjectClaim = claimMapping.getLocalClaim().getClaimUri(); } } } } if (subjectClaim != null) { String username = request.getAuthorizedUser().getUserName(); String userStore = request.getAuthorizedUser().getUserStoreDomain(); tenantDomain = request.getAuthorizedUser().getTenantDomain(); String fqdnUsername = request.getAuthorizedUser().toString(); try { UserStoreManager usm = IdentityTenantUtil.getRealm(tenantDomain, fqdnUsername) .getUserStoreManager(); subject = usm.getSecondaryUserStoreManager(userStore).getUserClaimValue(username, subjectClaim, null); if (StringUtils.isBlank(subject)) { subject = request.getAuthorizedUser().getAuthenticatedSubjectIdentifier(); } boolean useUserstoreDomainInLocalSubjectIdentifier = serviceProvider .getLocalAndOutBoundAuthenticationConfig() .isUseUserstoreDomainInLocalSubjectIdentifier(); boolean useTenantDomainInLocalSubjectIdentifier = serviceProvider .getLocalAndOutBoundAuthenticationConfig() .isUseTenantDomainInLocalSubjectIdentifier(); if (useTenantDomainInLocalSubjectIdentifier) { subject = UserCoreUtil.addTenantDomainToEntry(subject, tenantDomain); } if (useUserstoreDomainInLocalSubjectIdentifier) { subject = IdentityUtil.addDomainToName(subject, userStore); } } catch (IdentityException e) { String error = "Error occurred while getting user claim for user " + request.getAuthorizedUser().toString() + ", claim " + subjectClaim; throw new IdentityOAuth2Exception(error, e); } catch (UserStoreException e) { if (e.getMessage().contains("UserNotFound")) { if (log.isDebugEnabled()) { log.debug("User " + username + " not found in user store " + userStore + " in tenant " + tenantDomain); } subject = request.getAuthorizedUser().toString(); } else { String error = "Error occurred while getting user claim for user " + request.getAuthorizedUser().toString() + ", claim " + subjectClaim; throw new IdentityOAuth2Exception(error, e); } } } } } String nonceValue = null; long authTime = 0; LinkedHashSet acrValue = new LinkedHashSet(); // AuthorizationCode only available for authorization code grant type if (request.getProperty(AUTHORIZATION_CODE) != null) { AuthorizationGrantCacheEntry authorizationGrantCacheEntry = getAuthorizationGrantCacheEntry(request); if (authorizationGrantCacheEntry != null) { nonceValue = authorizationGrantCacheEntry.getNonceValue(); acrValue = authorizationGrantCacheEntry.getAcrValue(); if (authorizationGrantCacheEntry.getEssentialClaims() != null) { if (OAuth2Util.getEssentialClaims(authorizationGrantCacheEntry.getEssentialClaims(), OAuthConstants.ID_TOKEN).contains(OAuthConstants.OAuth20Params.AUTH_TIME)) { authTime = authorizationGrantCacheEntry.getAuthTime(); } } } } String atHash = null; if (!JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName())) { String digAlg = OAuth2Util.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"); log.debug(stringBuilder.toString()); } ArrayList<String> audience = new ArrayList<String>(); audience.add(request.getOauth2AccessTokenReqDTO().getClientId()); if (CollectionUtils.isNotEmpty(getOIDCEndpointUrl())) { audience.addAll(getOIDCEndpointUrl()); } JWTClaimsSet jwtClaimsSet = new JWTClaimsSet(); jwtClaimsSet.setIssuer(issuer); jwtClaimsSet.setAudience(audience); jwtClaimsSet.setClaim("azp", request.getOauth2AccessTokenReqDTO().getClientId()); jwtClaimsSet.setExpirationTime(new Date(curTimeInMillis + lifetimeInMillis)); jwtClaimsSet.setIssueTime(new Date(curTimeInMillis)); if (authTime != 0) { jwtClaimsSet.setClaim("auth_time", authTime / 1000); } if (atHash != null) { jwtClaimsSet.setClaim("at_hash", atHash); } if (nonceValue != null) { jwtClaimsSet.setClaim("nonce", nonceValue); } if (acrValue != null) { jwtClaimsSet.setClaim("acr", "urn:mace:incommon:iap:silver"); } request.addProperty(OAuthConstants.ACCESS_TOKEN, tokenRespDTO.getAccessToken()); request.addProperty(MultitenantConstants.TENANT_DOMAIN, request.getOauth2AccessTokenReqDTO().getTenantDomain()); CustomClaimsCallbackHandler claimsCallBackHandler = OAuthServerConfiguration.getInstance() .getOpenIDConnectCustomClaimsCallbackHandler(); claimsCallBackHandler.handleCustomClaims(jwtClaimsSet, request); jwtClaimsSet.setSubject(subject); if (!isValidIdToken(jwtClaimsSet)) { throw new IDTokenValidationFailureException("Error while validating JWT token for required claims"); } if (JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName())) { return new PlainJWT(jwtClaimsSet).serialize(); } boolean isJWTSignedWithSPKey = OAuthServerConfiguration.getInstance().isJWTSignedWithSPKey(); String signingTenantDomain; if (isJWTSignedWithSPKey) { signingTenantDomain = (String) request.getProperty(MultitenantConstants.TENANT_DOMAIN); } else { signingTenantDomain = request.getAuthorizedUser().getTenantDomain(); } return OAuth2Util.signJWT(jwtClaimsSet, signatureAlgorithm, signingTenantDomain).serialize(); }
From source file:org.wso2.carbon.identity.openidconnect.DefaultIDTokenBuilder.java
@Override public String buildIDToken(OAuthAuthzReqMessageContext request, OAuth2AuthorizeRespDTO tokenRespDTO) throws IdentityOAuth2Exception { String tenantDomain = request.getAuthorizationReqDTO().getTenantDomain(); IdentityProvider identityProvider = getResidentIdp(tenantDomain); FederatedAuthenticatorConfig[] fedAuthnConfigs = identityProvider.getFederatedAuthenticatorConfigs(); // Get OIDC authenticator FederatedAuthenticatorConfig samlAuthenticatorConfig = IdentityApplicationManagementUtil .getFederatedAuthenticator(fedAuthnConfigs, IdentityApplicationConstants.Authenticator.OIDC.NAME); String issuer = IdentityApplicationManagementUtil .getProperty(samlAuthenticatorConfig.getProperties(), OPENID_IDP_ENTITY_ID).getValue(); 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(); LinkedHashSet acrValue = request.getAuthorizationReqDTO().getACRValues(); String atHash = null;/*from ww w.ja va 2s . c o m*/ 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 = OAuth2Util.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()); } } ArrayList<String> audience = new ArrayList<String>(); audience.add(request.getAuthorizationReqDTO().getConsumerKey()); if (CollectionUtils.isNotEmpty(getOIDCEndpointUrl())) { audience.addAll(getOIDCEndpointUrl()); } JWTClaimsSet jwtClaimsSet = new JWTClaimsSet(); jwtClaimsSet.setIssuer(issuer); jwtClaimsSet.setAudience(audience); jwtClaimsSet.setClaim("azp", request.getAuthorizationReqDTO().getConsumerKey()); jwtClaimsSet.setExpirationTime(new Date(curTimeInMillis + lifetimeInMillis)); jwtClaimsSet.setIssueTime(new Date(curTimeInMillis)); if (request.getAuthorizationReqDTO().getAuthTime() != 0) { jwtClaimsSet.setClaim("auth_time", request.getAuthorizationReqDTO().getAuthTime() / 1000); } if (atHash != null) { jwtClaimsSet.setClaim("at_hash", atHash); } if (nonceValue != null) { jwtClaimsSet.setClaim("nonce", nonceValue); } if (acrValue != null) { jwtClaimsSet.setClaim("acr", "urn:mace:incommon:iap:silver"); } request.addProperty(OAuthConstants.ACCESS_TOKEN, tokenRespDTO.getAccessToken()); request.addProperty(MultitenantConstants.TENANT_DOMAIN, request.getAuthorizationReqDTO().getTenantDomain()); CustomClaimsCallbackHandler claimsCallBackHandler = OAuthServerConfiguration.getInstance() .getOpenIDConnectCustomClaimsCallbackHandler(); claimsCallBackHandler.handleCustomClaims(jwtClaimsSet, request); jwtClaimsSet.setSubject(subject); if (JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName())) { return new PlainJWT(jwtClaimsSet).serialize(); } boolean isJWTSignedWithSPKey = OAuthServerConfiguration.getInstance().isJWTSignedWithSPKey(); String signingTenantDomain; if (isJWTSignedWithSPKey) { signingTenantDomain = (String) request.getProperty(MultitenantConstants.TENANT_DOMAIN); } else { signingTenantDomain = request.getAuthorizationReqDTO().getUser().getTenantDomain(); } return OAuth2Util.signJWT(jwtClaimsSet, signatureAlgorithm, signingTenantDomain).serialize(); }