Java Code Examples for org.apache.shiro.codec.Base64#encodeToString()

The following examples show how to use org.apache.shiro.codec.Base64#encodeToString() . 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: ApplicationResourceIT.java    From usergrid with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve an authentication token using a combination of form input and payload
 */
@Test
public void clientCredentialsFlowWithHeaderAuthorizationAndPayload() throws Exception {
    //retrieve the credentials
    Credentials orgCredentials = getOrgCredentials();
    String clientId = orgCredentials.getClientId();
    String clientSecret = orgCredentials.getClientSecret();

    //Encode the credentials
    String clientCredentials = clientId + ":" + clientSecret;
    String token = Base64.encodeToString(clientCredentials.getBytes());

    //POST the form to the application token endpoint along with the payload
    Token apiResponse = this.app().token().getTarget( false ).request()
        .header( "Authorization", "Basic " + token )
        .accept( MediaType.APPLICATION_JSON )
        .post(javax.ws.rs.client.Entity.entity(
            hashMap("grant_type", "client_credentials"), MediaType.APPLICATION_JSON_TYPE), Token.class);

    //Assert that a valid token with a valid TTL is returned
    assertNotNull("It has access_token.", apiResponse.getAccessToken());
    assertNotNull("It has expires_in.", apiResponse.getExpirationDate());
}
 
Example 2
Source File: HMACSignature.java    From gazpachoquest with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Computes RFC 2104-compliant HMAC signature.
 * * @param data
 * The data to be signed.
 * 
 * @param key
 *            The signing key.
 * @return
 *         The Base64-encoded RFC 2104-compliant HMAC signature.
 * @throws java.security.SignatureException
 *             when signature generation fails
 */
public static String calculateRFC2104HMAC(String data, String key) throws java.security.SignatureException {
    String result = null;
    try {
        Charset utf8ChartSet = Charset.forName("UTF-8");
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(utf8ChartSet), HMAC_SHA1_ALGORITHM);

        // get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);

        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data.getBytes(utf8ChartSet));

        // base64-encode the hmac
        result = Base64.encodeToString(rawHmac);
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
    return result;
}
 
Example 3
Source File: CookieRememberMeManager.java    From nano-framework with Apache License 2.0 6 votes vote down vote up
@Override
protected void rememberSerializedIdentity(Subject subject, byte[] serialized) {
    if (!WebUtils.isHttp(subject)) {
        if (LOGGER.isDebugEnabled()) {
            String msg = "Subject argument is not an HTTP-aware instance.  This is required to obtain a servlet " +
                    "request and response in order to set the rememberMe cookie. Returning immediately and " +
                    "ignoring rememberMe operation.";
            LOGGER.debug(msg);
        }
        
        return;
    }


    HttpServletRequest request = WebUtils.getHttpRequest(subject);
    HttpServletResponse response = WebUtils.getHttpResponse(subject);

    // base 64 encode it and store as a cookie:
    String base64 = Base64.encodeToString(serialized);

    // the class attribute is really a template for the outgoing cookies
    Cookie cookie = getCookie(); 
    cookie.setValue(base64);
    cookie.saveTo(request, response);
}
 
Example 4
Source File: TestTwilioAckEventHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public void buildMocks(String anweredBy,String host, String sigHost,String callStatus) throws Exception{
   URIBuilder builder = new URIBuilder("/ivr/event/ack")
      .addParameter(TwilioBaseHandler.SCRIPT_PARAM, "alarm.smoke.triggered")
      .addParameter(TwilioHelper.NOTIFICATION_ID_PARAM_NAME, "place:"+UUID.randomUUID())
      .addParameter(TwilioHelper.PERSON_ID_PARAM_NAME, "test")
      .addParameter(TwilioHelper.NOTIFICATION_EVENT_TIME_PARAM_NAME, "12345678910")
      .addParameter(TwilioHelper.CALL_STATUS_PARAM_KEY, callStatus)
      .addParameter(TwilioHelper.ANSWEREDBY_PARAM_KEY, anweredBy);
   
   String testURI=builder.build().toString();
   FieldUtils.writeField(handler, "twilioAccountAuth", "AUTHKEY", true);
   
   String protocol =TwilioHelper.PROTOCOL_HTTPS;
   
   String sig = Base64.encodeToString(HmacUtils.hmacSha1 ("AUTHKEY", protocol + sigHost + testURI));
   
   EasyMock.expect(request.getMethod()).andReturn(HttpMethod.GET).anyTimes();
   EasyMock.expect(request.getUri()).andReturn(testURI).anyTimes();
   EasyMock.expect(request.headers()).andReturn(httpHeaders).anyTimes();
   EasyMock.expect(httpHeaders.contains(TwilioHelper.SIGNATURE_HEADER_KEY)).andReturn(true).anyTimes();
   EasyMock.expect(httpHeaders.get(TwilioHelper.SIGNATURE_HEADER_KEY)).andReturn(sig).anyTimes();
   EasyMock.expect(httpHeaders.get(TwilioHelper.HOST_HEADER_KEY)).andReturn(host).anyTimes();
   EasyMock.expect(mockPopulationCacheMgr.getPopulationByPlaceId(EasyMock.anyObject(UUID.class))).andReturn(Population.NAME_GENERAL);
}
 
Example 5
Source File: TestTwilioAckScriptHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
   super.setUp();
   builder = buildParameters(null);
   FieldUtils.writeField(handler, "twilioAccountAuth", "AUTHKEY", true);

   sig = Base64.encodeToString(HmacUtils.hmacSha1 ("AUTHKEY", TwilioHelper.PROTOCOL_HTTPS + "somehost" + builder.toString()));
   EasyMock.expect(request.getUri()).andReturn(builder.toString()).anyTimes();
   EasyMock.expect(request.getMethod()).andReturn(HttpMethod.GET);
   EasyMock.expect(request.headers()).andReturn(httpHeaders).anyTimes();
   
   EasyMock.expect(httpHeaders.contains(TwilioHelper.SIGNATURE_HEADER_KEY)).andReturn(true).anyTimes();
   EasyMock.expect(httpHeaders.get(TwilioHelper.SIGNATURE_HEADER_KEY)).andReturn(sig).anyTimes();
   EasyMock.expect(httpHeaders.get(TwilioHelper.HOST_HEADER_KEY)).andReturn("somehost").anyTimes();
   EasyMock.expect(personDAO.findById(personID)).andReturn(person);
   EasyMock.expect(placeDAO.findById(placeId)).andReturn(place);
   EasyMock.expect(populationCacheMgr.getPopulationByPlaceId(EasyMock.anyObject(UUID.class))).andReturn(Population.NAME_GENERAL).anyTimes();
}
 
Example 6
Source File: MySimpleHash.java    From cms with Apache License 2.0 5 votes vote down vote up
public String toBase64() {
    if (this.base64Encoded == null) {
        this.base64Encoded = Base64.encodeToString(this.getBytes());
    }

    return this.base64Encoded;
}
 
Example 7
Source File: AesEncryptUtil.java    From jeecg-boot-with-activiti with MIT License 5 votes vote down vote up
/**
 * 加密方法
 * @param data  要加密的数据
 * @param key 加密key
 * @param iv 加密iv
 * @return 加密的结果
 * @throws Exception
 */
public static String encrypt(String data, String key, String iv) throws Exception {
    try {

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");//"算法/模式/补码方式"NoPadding PkcsPadding
        int blockSize = cipher.getBlockSize();

        byte[] dataBytes = data.getBytes();
        int plaintextLength = dataBytes.length;
        if (plaintextLength % blockSize != 0) {
            plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
        }

        byte[] plaintext = new byte[plaintextLength];
        System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

        SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

        cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
        byte[] encrypted = cipher.doFinal(plaintext);

        return Base64.encodeToString(encrypted);

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 8
Source File: SimpleHash.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @return a Base64-encoded string of the underlying {@link #getBytes byte array}.
 */
public String toBase64() {
    if (this.base64Encoded == null) {
        //cache result in case this method is called multiple times.
        this.base64Encoded = Base64.encodeToString(getBytes());
    }
    return this.base64Encoded;
}
 
Example 9
Source File: AbstractHash.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @return a Base64-encoded string of the underlying {@link #getBytes byte array}.
 */
public String toBase64() {
    if (this.base64Encoded == null) {
        //cache result in case this method is called multiple times.
        this.base64Encoded = Base64.encodeToString(getBytes());
    }
    return this.base64Encoded;
}
 
Example 10
Source File: ApplicationResourceIT.java    From usergrid with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve an app user access token using HTTP Basic authentication
 */
@Test
public void clientCredentialsFlowWithHeaderAuthorization() throws Exception {

    // get app credentials from /<org>/<app>/credentials end-point (using admin credentials)
    Credentials appCredentials = getAppCredentials();
    String clientId = appCredentials.getClientId();
    String clientSecret = appCredentials.getClientSecret();

    // use app credentials to admin user access token
    Token token = clientSetup.getRestClient().management().token()
        .post(Token.class,new Token("client_credentials", clientId, clientSecret));

    String clientCredentials = clientId + ":" + clientSecret;
    String encodedToken = Base64.encodeToString( clientCredentials.getBytes() );

    Map<String, String> payload = hashMap( "grant_type", "client_credentials" );

    // use admin user access token to get app user access token
    Token apiResponse = this.app().token().getTarget( false ).request()
        //add the auth header
        .header( "Authorization", "Basic " + encodedToken )
        .accept( MediaType.APPLICATION_JSON )
        .post(javax.ws.rs.client.Entity.entity(payload, MediaType.APPLICATION_JSON_TYPE ), Token.class );

    //Assert that a valid token with a valid TTL is returned
    assertNotNull("A valid response was returned.", apiResponse);
    assertNull("There is no error.", apiResponse.getError());
    assertNotNull("It has access_token.", apiResponse.getAccessToken());
    assertNotNull("It has expires_in.", apiResponse.getExpirationDate());




}
 
Example 11
Source File: SerializableUtil.java    From zheng with MIT License 5 votes vote down vote up
public static String serialize(Session session) {
    if (null == session) {
        return null;
    }
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(session);
        return Base64.encodeToString(bos.toByteArray());
    } catch (Exception e) {
        throw new RuntimeException("serialize session error", e);
    }
}
 
Example 12
Source File: ApplicationResourceIT.java    From usergrid with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve an access token using HTTP Basic authentication
 */
@Test
public void clientCredentialsFlowWithBasicAuthentication() throws Exception {
    //retrieve the credentials
    Credentials orgCredentials = getOrgCredentials();
    String clientId = orgCredentials.getClientId();
    String clientSecret = orgCredentials.getClientSecret();

    //encode the credentials
    String clientCredentials = clientId + ":" + clientSecret;
    String token = Base64.encodeToString(clientCredentials.getBytes());

    Map<String, String> map = new HashMap<>(1);
    map.put("grant_type", "client_credentials");
    //GET the token endpoint, adding the basic auth header
    Token apiResponse = clientSetup.getRestClient().management().token().getTarget( false )
        //add the auth header
        .request()
        .header( "Authorization", "Basic " + token )
        .accept(MediaType.APPLICATION_JSON)
        .post( javax.ws.rs.client.Entity.entity(map, MediaType.APPLICATION_JSON_TYPE), Token.class );

    //Assert that a valid token with a valid TTL is returned
    assertNotNull("A valid response was returned.", apiResponse);
    assertNull("There is no error.", apiResponse.getError());
    assertNotNull("It has access_token.", apiResponse.getAccessToken());
    assertNotNull("It has expires_in.", apiResponse.getExpirationDate());
}
 
Example 13
Source File: ShiroByteSource.java    From xmanager with Apache License 2.0 5 votes vote down vote up
@Override
public String toBase64() {
	if ( this.cachedBase64 == null ) {
		this.cachedBase64 = Base64.encodeToString(getBytes());
	}
	return this.cachedBase64;
}
 
Example 14
Source File: AesEncryptUtil.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 加密方法
 * @param data  要加密的数据
 * @param key 加密key
 * @param iv 加密iv
 * @return 加密的结果
 * @throws Exception
 */
public static String encrypt(String data, String key, String iv) throws Exception {
    try {

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");//"算法/模式/补码方式"NoPadding PkcsPadding
        int blockSize = cipher.getBlockSize();

        byte[] dataBytes = data.getBytes();
        int plaintextLength = dataBytes.length;
        if (plaintextLength % blockSize != 0) {
            plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
        }

        byte[] plaintext = new byte[plaintextLength];
        System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

        SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

        cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
        byte[] encrypted = cipher.doFinal(plaintext);

        return Base64.encodeToString(encrypted);

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 15
Source File: AesEncryptUtil.java    From teaching with Apache License 2.0 5 votes vote down vote up
/**
 * 加密方法
 * @param data  要加密的数据
 * @param key 加密key
 * @param iv 加密iv
 * @return 加密的结果
 * @throws Exception
 */
public static String encrypt(String data, String key, String iv) throws Exception {
    try {

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");//"算法/模式/补码方式"NoPadding PkcsPadding
        int blockSize = cipher.getBlockSize();

        byte[] dataBytes = data.getBytes();
        int plaintextLength = dataBytes.length;
        if (plaintextLength % blockSize != 0) {
            plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
        }

        byte[] plaintext = new byte[plaintextLength];
        System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

        SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

        cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
        byte[] encrypted = cipher.doFinal(plaintext);

        return Base64.encodeToString(encrypted);

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 16
Source File: MD5.java    From spring-boot-demo with MIT License 4 votes vote down vote up
public static String encodeBase64(String str) {
    return Base64.encodeToString(str.getBytes());
}
 
Example 17
Source File: CryptographyUtil.java    From songjhh_blog with Apache License 2.0 4 votes vote down vote up
public static String encBase64(String str) {
    return Base64.encodeToString(str.getBytes());
}
 
Example 18
Source File: MySimpleByteSource.java    From VideoMeeting with Apache License 2.0 4 votes vote down vote up
public String toBase64() {
	if (this.cachedBase64 == null) {
		this.cachedBase64 = Base64.encodeToString(getBytes());
	}
	return this.cachedBase64;
}
 
Example 19
Source File: SimpleByteSource.java    From nano-framework with Apache License 2.0 4 votes vote down vote up
public String toBase64() {
    if ( this.cachedBase64 == null ) {
        this.cachedBase64 = Base64.encodeToString(getBytes());
    }
    return this.cachedBase64;
}
 
Example 20
Source File: EndecryptUtil.java    From LazyREST with Apache License 2.0 2 votes vote down vote up
/**
 * base64进制加密
 *
 * @param content
 * @return
 */
public static String encrytBase64(String content) {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(content), "不能为空");
    byte[] bytes = content.getBytes();
    return Base64.encodeToString(bytes);
}