Java Code Examples for org.springframework.security.crypto.codec.Base64#encode()

The following examples show how to use org.springframework.security.crypto.codec.Base64#encode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AuthorizationServerConfigurationTest.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void missingGrant(String username, String password, String clientId, String secret, String grantType) throws Exception {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("grant_type", grantType);
    params.add("username", username);
    params.add("password", password);
    String hash = new String(Base64.encode((clientId + ":" + secret).getBytes()));
    ResultActions result
            = mockMvc.perform(post("/oauth/token")
                    .params(params)
                    .header("Authorization", "Basic " + hash)
                    .accept("application/json;charset=UTF-8"))
            .andExpect(status().isBadRequest())
            .andExpect(content().contentType("application/json;charset=UTF-8"));
    String resultString = result.andReturn().getResponse().getContentAsString();
    Assert.assertTrue(StringUtils.isNotBlank(resultString));
    result.andExpect(jsonPath("$.error", is("invalid_request")));
    result.andExpect(jsonPath("$.error_description", is("Missing grant type")));
    Collection<OAuth2AccessToken> oauthTokens = apiOAuth2TokenManager.findTokensByUserName(username);
    Assert.assertEquals(0, oauthTokens.size());
}
 
Example 2
Source File: DefaultUserService.java    From attic-rave with Apache License 2.0 6 votes vote down vote up
@Override
public void sendPasswordReminder(User newUser) {
    log.debug("Calling send password change link for user {}", newUser);
    User user = userRepository.getByUserEmail(newUser.getEmail());
    if (user == null) {
        throw new IllegalArgumentException("Could not find user for email " + newUser.getEmail());
    }
    // create user hash:
    String input = user.getEmail() + user.getUsername() + String.valueOf(user.getId()) + System.nanoTime();
    // hash needs to be URL friendly:
    String safeString = new String(Base64.encode(passwordEncoder.encode(input).getBytes()));
    String  hashedInput = safeString.replaceAll("[/=]", "A");
    user.setForgotPasswordHash(hashedInput);
    user.setForgotPasswordTime(Calendar.getInstance().getTime());
    userRepository.save(user);
    String to = user.getUsername() + " <" + user.getEmail() + '>';
    Map<String, Object> templateData = new HashMap<String, Object>();
    templateData.put("user", user);
    templateData.put("reminderUrl", baseUrl + hashedInput);
    emailService.sendEmail(to, passwordReminderSubject, passwordReminderTemplate, templateData);
}
 
Example 3
Source File: AuthorizationServerConfigurationTest.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void authenticationFailed(String username, String password) throws Exception {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("grant_type", "password");
    params.add("username", username);
    params.add("password", password);
    String hash = new String(Base64.encode("test1_consumer:secret".getBytes()));
    ResultActions result
            = mockMvc.perform(post("/oauth/token")
                    .params(params)
                    .header("Authorization", "Basic " + hash)
                    .accept("application/json;charset=UTF-8"))
            .andExpect(status().isUnauthorized())
            .andExpect(content().contentType("application/json;charset=UTF-8"));
    String resultString = result.andReturn().getResponse().getContentAsString();
    Assert.assertTrue(StringUtils.isNotBlank(resultString));
    result.andExpect(jsonPath("$.error", is("unauthorized")));
    result.andExpect(jsonPath("$.error_description", anything()));
    if (!StringUtils.isEmpty(username)) {
        Collection<OAuth2AccessToken> oauthTokens = apiOAuth2TokenManager.findTokensByUserName(username);
        Assert.assertEquals(0, oauthTokens.size());
    }
}
 
Example 4
Source File: HttpAuthInterceptor.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
private void interceptInner(HttpHeaders headers, HttpRequest httpRequest) {
    URI uri = httpRequest.getURI();
    String host = uri.getHost();
    int port = uri.getPort();
    String url = host + (port == -1 ? "" : ":" + port);
    String name = registryName.get();
    log.debug("try to auth request to registry: {}", name);
    RegistryService registry = registryRepository.getByName(name);
    if (registry == null) {
        log.debug("auth : none due to unknown registry \"{}\"", name);
        return;
    }
    RegistryCredentials credentials = registry.getCredentials();
    if (credentials == null || !StringUtils.hasText(credentials.getPassword())) {
        log.debug("auth : none due to unknown registry \"{}\"", name);
        return;
    }
    String result = format("'{'\"username\":\"{0}\",\"password\":\"{1}\",\"email\":\"[email protected]\",\"serveraddress\":\"{2}\",\"auth\":\"\"'}'",
            credentials.getUsername(), credentials.getPassword(), url);
    log.debug("auth : {}", result);
    String xRegistryAuth = new String(Base64.encode(result.getBytes()));
    log.debug("X-Registry-Auth : [{}]", xRegistryAuth);
    headers.add("X-Registry-Auth", xRegistryAuth);
}
 
Example 5
Source File: RoomDetailsBackend.java    From unitime with Apache License 2.0 5 votes vote down vote up
public String signRequest(String mapsUrl) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, URISyntaxException, MalformedURLException {
	URL url = new URL(mapsUrl);
	String resource = url.getPath() + "?" + url.getQuery();
	SecretKeySpec sha1Key = new SecretKeySpec(key, "HmacSHA1");
	Mac mac = Mac.getInstance("HmacSHA1");
	mac.init(sha1Key);
	byte[] sigBytes = mac.doFinal(resource.getBytes());
	String signature = new String(Base64.encode(sigBytes));
	signature = signature.replace('+', '-');
	signature = signature.replace('/', '_');
	return signature;
}
 
Example 6
Source File: SecurityUtils.java    From spring-backend-boilerplate with Apache License 2.0 5 votes vote down vote up
public static String generatePasswordSalt() {
	byte[] aesKey = new byte[16];
	ranGen.nextBytes(aesKey);
	String salt = new String(Base64.encode(aesKey));
	salt = salt.replace("\r", "");
	salt = salt.replace("\n", "");
	return salt;
}
 
Example 7
Source File: AES.java    From bushido-java-core with GNU General Public License v3.0 5 votes vote down vote up
public String encrypt(String plainText, SecretKey secretKey)
        throws Exception {
    byte[] plainTextByte = plainText.getBytes();
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    byte[] encryptedByte = cipher.doFinal(plainTextByte);
    byte[] encryptedText = Base64.encode(encryptedByte);
    return new String(encryptedText);
}
 
Example 8
Source File: AuthorizationServerConfigurationTest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private OAuth2AccessToken obtainAccessToken(String username, String password, boolean remove) throws Exception {
    OAuth2AccessToken oauthToken = null;
    try {
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("grant_type", "password");
        params.add("username", username);
        params.add("password", password);
        String hash = new String(Base64.encode("test1_consumer:secret".getBytes()));
        ResultActions result
                = mockMvc.perform(post("/oauth/token")
                        .params(params)
                        .header("Authorization", "Basic " + hash)
                        .accept("application/json;charset=UTF-8"))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"));
        String resultString = result.andReturn().getResponse().getContentAsString();
        System.out.println(resultString);
        Assert.assertTrue(StringUtils.isNotBlank(resultString));
        String token = JsonPath.parse(resultString).read("$.access_token");
        Assert.assertTrue(StringUtils.isNotBlank(token));
        Collection<OAuth2AccessToken> oauthTokens = apiOAuth2TokenManager.findTokensByUserName(username);
        Assert.assertEquals(1, oauthTokens.size());
        oauthToken = oauthTokens.stream().findFirst().get();
        Assert.assertEquals(token, oauthToken.getValue());
    } catch (Exception e) {
        throw e;
    } finally {
        if (null != oauthToken && remove) {
            this.apiOAuth2TokenManager.removeAccessToken(oauthToken);
        }
    }
    return oauthToken;
}
 
Example 9
Source File: CustomRemoteTokenServices.java    From microservice-integration with MIT License 5 votes vote down vote up
private String getAuthorizationHeader(String clientId, String clientSecret) {
    String creds = String.format("%s:%s", clientId, clientSecret);
    try {
        return "Basic " + new String(Base64.encode(creds.getBytes("UTF-8")));
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("Could not convert String");
    }
}
 
Example 10
Source File: AbstractEncryptingService.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected String encrypt(String value) {
    try {
        Cipher cipher = Cipher.getInstance(AES_CYPHER);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, initializationVectorSpec);
        byte[] encrypted = cipher.doFinal(value.getBytes());
        return new String(Base64.encode(encrypted), UTF8_ENCODING);
    } catch (GeneralSecurityException nsae) {
        throw new RuntimeException(nsae);
    } catch (UnsupportedEncodingException uee) {
        throw new RuntimeException(uee);
    }
}
 
Example 11
Source File: JwtAccessTokenConverter.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
public void setKeyPair(KeyPair keyPair) {
    PrivateKey privateKey = keyPair.getPrivate();
    Assert.state(privateKey instanceof RSAPrivateKey, "KeyPair must be an RSA ");
    signer = new RsaSigner((RSAPrivateKey) privateKey);
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    verifier = new RsaVerifier(publicKey);
    verifierKey = "-----BEGIN PUBLIC KEY-----\n" + new String(Base64.encode(publicKey.getEncoded()))
            + "\n-----END PUBLIC KEY-----";
}
 
Example 12
Source File: _CustomPersistentRememberMeServices.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 4 votes vote down vote up
private String generateSeriesData() {
    byte[] newSeries = new byte[DEFAULT_SERIES_LENGTH];
    random.nextBytes(newSeries);
    return new String(Base64.encode(newSeries));
}
 
Example 13
Source File: CustomPersistentRememberMeServices.java    From expper with GNU General Public License v3.0 4 votes vote down vote up
private String generateSeriesData() {
    byte[] newSeries = new byte[DEFAULT_SERIES_LENGTH];
    random.nextBytes(newSeries);
    return new String(Base64.encode(newSeries));
}
 
Example 14
Source File: CustomPersistentRememberMeServices.java    From ServiceCutter with Apache License 2.0 4 votes vote down vote up
private String generateTokenData() {
	byte[] newToken = new byte[DEFAULT_TOKEN_LENGTH];
	random.nextBytes(newToken);
	return new String(Base64.encode(newToken));
}
 
Example 15
Source File: CustomPersistentRememberMeServices.java    From expper with GNU General Public License v3.0 4 votes vote down vote up
private String generateTokenData() {
    byte[] newToken = new byte[DEFAULT_TOKEN_LENGTH];
    random.nextBytes(newToken);
    return new String(Base64.encode(newToken));
}
 
Example 16
Source File: _CustomPersistentRememberMeServices.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 4 votes vote down vote up
private String generateTokenData() {
    byte[] newToken = new byte[DEFAULT_TOKEN_LENGTH];
    random.nextBytes(newToken);
    return new String(Base64.encode(newToken));
}
 
Example 17
Source File: TokenManagerSingle.java    From restful-spring-security with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private String generateToken() {
	byte[] tokenBytes = new byte[32];
	new SecureRandom().nextBytes(tokenBytes);
	return new String(Base64.encode(tokenBytes), StandardCharsets.UTF_8);
}
 
Example 18
Source File: SecurityUtils.java    From spring-backend-boilerplate with Apache License 2.0 4 votes vote down vote up
public static String generateBase64Key() {
	byte[] hexBytes = Hex.decode(generateHexKey());
	return new String(Base64.encode(hexBytes));
}
 
Example 19
Source File: PersistentTokenServiceImpl.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
private String generateSeriesData() {
  byte[] newSeries = new byte[DEFAULT_SERIES_LENGTH];
  random.nextBytes(newSeries);
  return new String(Base64.encode(newSeries));
}
 
Example 20
Source File: SecurityTestUtils.java    From spring-cloud-skipper with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a basic authorization header for the given username and password.
 *
 * @param username Must not be null
 * @param password Must not be null
 * @return Returns the header as String. Never returns null.
 */
public static String basicAuthorizationHeader(String username, String password) {
	Assert.notNull(username, "The username must not be null.");
	Assert.notNull(password, "The password must not be null.");

	return "Basic " + new String(Base64.encode((username + ":" + password).getBytes(StandardCharsets.ISO_8859_1)));
}