public static StringEntity toJson(Map<String, String> entries) { Encoder encoder = Base64.getEncoder(); try { return new StringEntity("[" + entries.entrySet().stream() .map(entry -> { String value = Optional.ofNullable(entry.getValue()) .map(entryValue -> "\"" + encoder.encodeToString(entryValue.getBytes()) + "\"") .orElse("null"); return "{\"Key\":\"" + entry.getKey() + "\",\"Value\":" + value + "}"; }) .collect(Collectors.joining(",")) + "]"); } catch (IOException e) { throw new RuntimeException(e); } }
public void refreshToken(){ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(authServerBaseUrl + oauth2TokenEndpointPath); // Here we don't authenticate the user, we authenticate the client and we pass the authcode proving that the user has accepted and loged in builder.queryParam("grant_type", "refresh_token"); builder.queryParam("refresh_token", refreshToken); // Add Basic Authorization headers for CLIENT authentication (user was authenticated in previous request (authorization code) HttpHeaders headers = new HttpHeaders(); Encoder encoder = Base64.getEncoder(); headers.add("Authorization","Basic " + encoder.encodeToString((getClientId() + ":" + getClientSecret()).getBytes())); HttpEntity<String> entity = new HttpEntity<>("", headers); ResponseEntity<OAuth2AccessToken> result2 = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entity, OAuth2AccessToken.class); assertEquals(HttpStatus.OK, result2.getStatusCode()); // Obtain and keep the token accessToken = result2.getBody().getValue(); assertNotNull(accessToken); refreshToken = result2.getBody().getRefreshToken().getValue(); assertNotNull(refreshToken); }
private static void test1() throws Exception { byte[] src = new byte[] { 46, -97, -35, -44, 127, -60, -39, -4, -112, 34, -57, 47, -14, 67, 40, 18, 90, -59, 68, 112, 23, 121, -91, 94, 35, 49, 104, 17, 30, -80, -104, -3, -53, 27, 38, -72, -47, 113, -52, 18, 5, -126 }; Encoder encoder = Base64.getMimeEncoder(49, new byte[] { 0x7e }); byte[] encoded = encoder.encode(src); Decoder decoder = Base64.getMimeDecoder(); byte[] decoded = decoder.decode(encoded); if (!Objects.deepEquals(src, decoded)) { throw new RuntimeException(); } }
public static String aesEncryptString(String content, String key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException { byte[] contentBytes = content.getBytes(charset); byte[] keyBytes = key.getBytes(charset); byte[] encryptedBytes = aesEncryptBytes(contentBytes, keyBytes); Encoder encoder = Base64.getEncoder(); return encoder.encodeToString(encryptedBytes); }
static String rfc4648Base64Encode(String arg) throws UnsupportedEncodingException { Encoder encoder = Base64.getMimeEncoder(0, new byte[0]); String res = encoder.encodeToString(arg.getBytes(TEXT_ENCODING)); res = res.replace("/", "_"); res = res.replace("+", "-"); res = res.replace("=", ""); return res; }
static String rfc4648Base64Encode(byte[] arg) throws UnsupportedEncodingException { Encoder encoder = Base64.getMimeEncoder(0, new byte[0]); String res = encoder.encodeToString(arg); res = res.replace("/", "_"); res = res.replace("+", "-"); res = res.replace("=", ""); return res; }
public static Content createContent(IExtensionHelpers helpers, byte[] httpResponse) { String[] response = new String(httpResponse).split("\r\n\r\n"); // size int size = 0; if (response.length > 1) { size = response[1].getBytes().length; } // mimeType String mimeType = getMimeType(httpResponse); String base64String = ""; if (response.length > 1) { IResponseInfo iResInfo = helpers.analyzeResponse(httpResponse); int bodyPos = iResInfo.getBodyOffset(); byte[] bodybyte = Arrays.copyOfRange(httpResponse,bodyPos,httpResponse.length); Encoder encoder = Base64.getMimeEncoder(); encoder = Base64.getMimeEncoder(); base64String = encoder.encodeToString(bodybyte); } Content retContent = new Content.Builder().size(size).compression(0).encoding("base64").mimeType(mimeType) .text(base64String).build(); return retContent; }
private void dumpCert(boolean rfc, Certificate certificate, PrintStream printstream) throws IOException, CertificateException { if (rfc) { final Encoder base64encoder = Base64.getEncoder(); final byte[] encoded = base64encoder.encode(certificate.getEncoded()); printstream.println("-----BEGIN CERTIFICATE-----"); printstream.write(encoded, 0, encoded.length); printstream.println("-----END CERTIFICATE-----"); } else { printstream.write(certificate.getEncoded()); } }
public static String generateApiKey(){ Encoder e = Base64.getEncoder(); ByteBuffer bb = ByteBuffer.wrap(new byte[16*2]); for(int i=0;i<2; i++){ UUID u = UUID.randomUUID(); bb.putLong(u.getMostSignificantBits()); bb.putLong(u.getLeastSignificantBits()); } return e.encodeToString(bb.array()); }
/** * Encrypt an array of integers to a String. * * @param integers * @param context * @return * @throws ServletException */ public static String encryptIntegers(int integers[], String password) throws ServletException { /* Generate salt. */ SecureRandom rand = new SecureRandom(); byte salt[] = new byte[8]; rand.nextBytes(salt); byte[] iv; byte[] ciphertext; try { /* Derive the key, given password and salt. */ SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256); SecretKey tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); /* Encrypt the SampleSetID. */ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = cipher.getParameters(); iv = params.getParameterSpec(IvParameterSpec.class).getIV(); ByteBuffer buff = ByteBuffer.allocate(integers.length * 4); for (int i = 0; i < integers.length; ++i) { buff.putInt(integers[i]); } ciphertext = cipher.doFinal(buff.array()); } catch (Exception ex) { throw new ServletException(ex); } /* Store the encrypted SampleSetID in a cookie */ Encoder encoder = Base64.getEncoder(); String encryptedStr = encoder.encodeToString(ciphertext) + "|" + encoder.encodeToString(iv) + "|" + encoder.encodeToString(salt); return encryptedStr; }
/** * Encrypt an integer to a String. * * @param integer * @param context * @return * @throws ServletException */ private static String encryptInteger(Integer integer, ServletContext context) throws ServletException { /* Get password. */ String password = context.getInitParameter("SampleSetIDEncryptionPassword"); /* Generate salt. */ SecureRandom rand = new SecureRandom(); byte salt[] = new byte[8]; rand.nextBytes(salt); byte[] iv; byte[] ciphertext; try { /* Derive the key, given password and salt. */ SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256); SecretKey tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); /* Encrypt the SampleSetID. */ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = cipher.getParameters(); iv = params.getParameterSpec(IvParameterSpec.class).getIV(); ciphertext = cipher.doFinal(ByteBuffer.allocate(4).putInt(integer).array()); } catch (Exception ex) { throw new ServletException(ex); } /* Store the encrypted SampleSetID in a cookie */ Encoder encoder = Base64.getEncoder(); String encryptedStr = encoder.encodeToString(ciphertext) + "|" + encoder.encodeToString(iv) + "|" + encoder.encodeToString(salt); return encryptedStr; }
@Test public void obtainTokenFromOuth2LoginEndpoint() throws Exception { obtainAuthorizationCode(); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(authServerBaseUrl + oauth2TokenEndpointPath); // Here we don't authenticate the user, we authenticate the client and we pass the authcode proving that the user has accepted and loged in builder.queryParam("client_id", getClientId()); builder.queryParam("grant_type", "authorization_code"); builder.queryParam("code", authorizationCode); builder.queryParam("redirect_uri", "http://anywhere"); // Add Basic Authorization headers for CLIENT authentication (user was authenticated in previous request (authorization code) HttpHeaders headers = new HttpHeaders(); Encoder encoder = Base64.getEncoder(); headers.add("Authorization","Basic " + encoder.encodeToString((getClientId() + ":" + getClientSecret()).getBytes())); HttpEntity<String> entity = new HttpEntity<>("", headers); ResponseEntity<OAuth2AccessToken> result2 = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entity, OAuth2AccessToken.class); // This means the user was correctly authenticated, then a redirection was performed to /oauth/authorize to obtain the token. // Then the token was sucessfully obtained (authenticating the client properly) and a last redirection was performed to the // redirect_uri with the token after # assertEquals(HttpStatus.OK, result2.getStatusCode()); // Obtain and keep the token accessToken = result2.getBody().getValue(); assertNotNull(accessToken); refreshToken = result2.getBody().getRefreshToken().getValue(); assertNotNull(refreshToken); }
/** * Returns an encoded BASE64 string of the value. * * @param salt * the salt to use for encoding * @param value * value to encode * * @return encoded BASE64 string of the value or null if no value given * * @throws CipherException */ public static String encode(String salt, String value) throws CipherException { // verify value if (null == value || value.isEmpty()) { return null; } // create cipher object SecretKeySpec keySpec = createAESCipher(salt); Cipher cipher; try { cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, keySpec); byte[] enc = cipher.doFinal(value.getBytes()); Encoder encoder = Base64.getEncoder(); return encoder.encodeToString(enc); } catch (Exception e) { throw new CipherException("Error during encryption.", e); } }
protected Encoder getEncoder() { return encoder; }
private String encodePropertyValue(final String value) throws IllegalArgumentException, EncryptionException { // simply obfuscate the values from clear text. final Encoder encoder = Base64.getUrlEncoder(); final String encoded = encoder.encodeToString(value.getBytes()); return encoded; }
public static String toBase64(byte[] bytes){ Encoder b64 = Base64.getEncoder(); return b64.encodeToString(bytes); }
@Override public Map<String, String> createConfiguration(final Map<String, String> attributes) throws GeneralSecurityException, IOException { final Provider provider = ProviderHelper .provider(option(attributes, "provider", ProviderHelper.WILDFLY_PROVIDER)); final String algorithm = option(attributes, "algorithm", DEFAULT_ALGORITHM); final PasswordFactory passwordFactory = PasswordFactory.getInstance(algorithm, provider); final String password = option(attributes, "password", null); final String salt = option(attributes, "salt", ""); final String iterations = option(attributes, "iterations", ""); final AlgorithmParameterSpec algorithmParameterSpec; if (salt.isEmpty() && iterations.isEmpty()) { algorithmParameterSpec = null; } else if (salt.isEmpty()) { algorithmParameterSpec = new IteratedPasswordAlgorithmSpec(parseInt(iterations)); } else { final byte[] saltBytes = Base64.getDecoder().decode(salt); algorithmParameterSpec = new IteratedSaltedPasswordAlgorithmSpec(parseInt(iterations), saltBytes); } final EncryptablePasswordSpec keySpec = new EncryptablePasswordSpec(password.toCharArray(), algorithmParameterSpec); final MaskedPassword maskedPassword = passwordFactory.generatePassword(keySpec).castAs(MaskedPassword.class); final MaskedPasswordAlgorithmSpec maskedPasswordAlgorithmSpec = maskedPassword.getParameterSpec(); final Map<String, String> configuration = new HashMap<>(); final Encoder encoder = Base64.getEncoder(); if (!DEFAULT_ALGORITHM.equals(algorithm)) { configuration.put(CREDENTIAL_STORE_PROTECTION_ALGORITHM, algorithm); } configuration.put(CREDENTIAL_STORE_PROTECTION, encoder.encodeToString(maskedPassword.getMaskedPasswordBytes())); final AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance(algorithm, provider); algorithmParameters.init(maskedPasswordAlgorithmSpec); final byte[] encoded = algorithmParameters.getEncoded(); configuration.put(CREDENTIAL_STORE_PROTECTION_PARAMS, encoder.encodeToString(encoded)); return configuration; }
static Crypted of(String info, byte[] content, byte[] iv) { Encoder encoder = getEncoder(); String contentBase64 = encoder.encodeToString(content); String ivBase64 = encoder.encodeToString(iv); return new AutoValue_ContentCryptographer_Crypted(info, contentBase64, ivBase64); }
private String getPassword(String userName) { Encoder encoder = Base64.getEncoder(); return encoder.encode(userName.getBytes()).toString(); }
/** * 对byte做base64编码 */ public static String encodeBase64(byte[] data) { Encoder encoder = Base64.getEncoder(); return encoder.encodeToString(data); }