public Image(long code) throws IOException { try { this.bufferedImage = ImageIO.read(new File(DEFAULT_LOCATION)); sideLength = bufferedImage.getWidth() / 16; } catch (IOException e) { Logger.getGlobal().log(Level.SEVERE, String.valueOf(e)); } for (int i = 0; i < 33; i++) { if ((code & ((long) 1 << (32 - i))) != 0L) { drawTopLeft(i); } } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "png", baos); byte[] bufferedImageBytes = baos.toByteArray(); this.base64 = Base64.getEncoder().encodeToString(bufferedImageBytes); }
public static void main(String[] args) { Base64.Decoder b64decoder = Base64.getUrlDecoder(); final Undertow server = Undertow.builder() .addHttpListener(8083, "localhost") .setHandler(exchange -> { exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain"); String credential = exchange.getRequestHeaders().getFirst("X-Bouncr-Credential"); String[] tokens = credential.split("\\.", 3); String json = new String(b64decoder.decode(tokens[1])); exchange.getResponseSender().send("Server1\n" + "profile=" + json + "\n" ); }) .build(); Runtime.getRuntime().addShutdownHook(new Thread(server::stop)); server.start(); }
/** * Combines multiple files into a ZIP archive, then base-64 the ZIP archive. * * @param paths a list of one or more input files, that are to be compressed together * @return the compressed output, as a String */ private static String zipBase64(List<Path> paths) { if (paths.isEmpty()) { throw new IllegalArgumentException("PortfolioDataFile requires at least one file"); } try { try (ByteArrayOutputStream baos = new ByteArrayOutputStream(1024 * 8)) { try (OutputStream baseos = Base64.getEncoder().wrap(baos)) { try (ZipOutputStream zos = new ZipOutputStream(baseos)) { for (Path path : paths) { ZipEntry entry = new ZipEntry(path.getFileName().toString()); zos.putNextEntry(entry); Files.copy(path, zos); zos.closeEntry(); } } } return baos.toString("ISO-8859-1"); // base-64 bytes are ASCII, so this is optimal } } catch (IOException ex) { throw new UncheckedIOException("Failed to zip base-64 content", ex); } }
private PublicKey getDERPublicKeyFromPEM(String key) throws Exception { try { // strip of header, footer, newlines, whitespaces String publicKeyPEM = key .replace("-----BEGIN PUBLIC KEY-----", "") .replace("-----END PUBLIC KEY-----", "") .replaceAll("\\s", ""); // decode to get the binary DER representation byte[] publicKeyDER = Base64.getDecoder().decode(publicKeyPEM); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyDER)); return publicKey; } catch (Exception e) { throw new InvalidConfig("Invalid JWE public key"); } }
private boolean authenticate(String authInfo) throws IOException { boolean matched = false; try { authInfo.trim(); int ind = authInfo.indexOf(' '); String recvdUserPlusPass = authInfo.substring(ind + 1).trim(); // extract encoded (username:passwd if (userPlusPass.equals( new String( Base64.getMimeDecoder() .decode(recvdUserPlusPass)))) { matched = true; } } catch (Exception e) { throw new IOException( "Proxy received invalid Proxy-Authorization value: " + authInfo); } return matched; }
private static void addOrUpdateAccount(String account, String password, String level) { try (Connection con = DatabaseFactory.getInstance().getConnection(); PreparedStatement ps = con.prepareStatement("REPLACE accounts(login, password, accessLevel) VALUES (?, ?, ?)")) { final MessageDigest md = MessageDigest.getInstance("SHA"); final byte[] newPassword = md.digest(password.getBytes("UTF-8")); ps.setString(1, account); ps.setString(2, Base64.getEncoder().encodeToString(newPassword)); ps.setString(3, level); if (ps.executeUpdate() > 0) { System.out.println("Account " + account + " has been created or updated"); } else { System.out.println("Account " + account + " does not exist"); } } catch (Exception e) { System.out.println("There was error while adding/updating account:"); System.out.println(e.getMessage()); } }
/** * 数据加密,算法(DES) * * @param data * 要进行加密的数据 * @param desKey DES密钥 * @return 加密后的数据 */ public static String encrypt(String data, byte[] desKey) { String encryptedData = null; try { // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom(); DESKeySpec deskey = new DESKeySpec(desKey); // 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(deskey); // 加密对象 Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, key, sr); // 加密,并把字节数组编码成字符串 encryptedData = Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes())); } catch (Exception e) { // log.error("加密错误,错误信息:", e); throw new RuntimeException("加密错误,错误信息:", e); } return encryptedData; }
private Token readQuotedBytes() throws IOException { int c; for (;;) { c = in.read(); switch (c) { case -1: throw new EOFException("Unexpected EOF reading quoted bytes at line " + getLine() + ":" + getCol()); case '\n': throw new EOFException("Unexpected end of line reading quoted bytes at line " + getLine() + ":" + getCol()); case '`': // End the bytes return new Token(Base64.getDecoder().decode(getToken(false, false).getBytes(UTF_8)), TokenType.BYTES); default: // Only allow valid Base64 characters: A-Z,a-z,0-9,\+ if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '=') { // Simply append to string so far token.append((char) c); } else { throw new IOException("Expected base64 character but got " + (char) c + " at line " + getLine() + ":" + getCol()); } } } }
public static String getPasswordHash(String p_password, byte[] p_seed) { byte[] pwd = p_password.getBytes(); byte[] result = new byte[pwd.length+p_seed.length]; for (int i = 0; i<result.length;i++) { if (i%2 == 0 && i/2<pwd.length) { result[i] = pwd[i/2]; } if ((i+1)%2 == 0 && (i+1)/2<p_seed.length) { result[i] = p_seed[(i+1)/2]; } } MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-256");} catch (NoSuchAlgorithmException e) { _logger.error(e.getMessage(), e); } return Base64.getEncoder().encodeToString(md.digest(result)); }
private static String getPEMPublicKeyFromDER(PublicKey publicKey) { String begin = "-----BEGIN PUBLIC KEY-----"; String end = "-----END PUBLIC KEY-----"; X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded()); String key = Base64.getEncoder().encodeToString(x509EncodedKeySpec.getEncoded()); return begin + "\n" + key + "\n" + end; }
/** * Internal method used during parsing : sets the private key in this entry * * @param key the chunk containing certificate * @throws CertificateException if key already exists */ private void setPrivateKey(List<String> key) throws CertificateException, NoSuchAlgorithmException { if (privateKey != null) throw new CertificateException("More than one private key in PEM input"); String b64key = key.subList(1, key.size()-1).stream().collect(Collectors.joining()); byte[] binKey = Base64.getDecoder().decode(b64key); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(binKey); KeyFactory kf = KeyFactory.getInstance("RSA"); try { privateKey = kf.generatePrivate(keySpec); } catch (InvalidKeySpecException e) { throw new CertificateException(e); } }
/** * Returns the username and password from a Basic Authentication header. * * @param auth The Basic Authentication header. * @return Either INVALID or a 2-item array. */ private static String[] getUsernamePassword(final String auth) { if (auth == null || !auth.startsWith(BASIC_PREFIX)) { // No Authorization header present // or not Basic authentication return INVALID; } final byte[] decodedBytes; try { decodedBytes = Base64.getDecoder().decode(auth.substring(BASIC_PREFIX.length())); } catch (final IllegalArgumentException ex) { return INVALID; } final String decoded = new String(decodedBytes, StandardCharsets.UTF_8); final int colonIndex = decoded.indexOf(':'); if (colonIndex == -1) { // No colon means this is a malformed header. return INVALID; } return decoded.split(":", 2); }
private SelectieVerwerkTaakBericht maakSelectieTaak(List<PersoonCache> caches, List<SelectieAutorisatieBericht> autorisatieChunk) { SelectieVerwerkTaakBericht selectieTaak = new SelectieVerwerkTaakBericht(); final List<SelectiePersoonBericht> selectiePersonen = new ArrayList<>(); for (PersoonCache persoonCache : caches) { final SelectiePersoonBericht selectiePersoonBericht = new SelectiePersoonBericht(); if (persoonCache.getAfnemerindicatieGegevens().length > 0) { final String afnemerindicatieData = new String(Base64.getEncoder().encode(persoonCache.getAfnemerindicatieGegevens()), StandardCharsets.UTF_8); selectiePersoonBericht.setAfnemerindicatieGegevens(afnemerindicatieData); } if (persoonCache.getPersoonHistorieVolledigGegevens().length > 0) { final String persoonData = new String(Base64.getEncoder().encode(persoonCache.getPersoonHistorieVolledigGegevens()), StandardCharsets.UTF_8); selectiePersoonBericht.setPersoonHistorieVolledigGegevens(persoonData); } selectiePersonen.add(selectiePersoonBericht); } selectieTaak.setPersonen(selectiePersonen); selectieTaak.setSelectieAutorisaties(autorisatieChunk); selectieTaak.setSelectieRunId(selectie.getSelectierun().getId()); selectieTaak.setSelectieStartDatum(DatumUtil.vanDatumNaarInteger(selectie.getSelectierun().getTijdstipStart())); return selectieTaak; }
@Test public final void testGenerateFulfillment() { PskContext context = PskContext.fromReceiverAddress(TEST_SECRET, TEST_ADDRESS); InterledgerPayment payment = InterledgerPayment.builder() .destinationAccount(TEST_ADDRESS) .destinationAmount(BigInteger.valueOf(100L)) .data(TEST_MESSAGE) .build(); Fulfillment fulfillment = context.generateFulfillment(payment); assertEquals("Incorrect fulfillment.", ((PreimageSha256Fulfillment) fulfillment).getPreimage(), //TODO Fix crypto-conditions to use Bas64Url without padding //Base64.getUrlEncoder().withoutPadding().encodeToString(TEST_PREIMAGE)); Base64.getUrlEncoder().encodeToString(TEST_PREIMAGE)); }
public String getSkinUrl(GameProfile prof) throws ParseException { Collection<Property> ps = prof.getProperties().get("textures"); if (ps == null || ps.isEmpty()) { return null; } else { Property p = Iterators.getLast(ps.iterator()); JSONObject obj = (JSONObject) new JSONParser().parse( new String(Base64.getDecoder().decode(p.getValue()))); obj = ((JSONObject) obj.get("textures")); obj = ((JSONObject) obj.get("SKIN")); return (String) obj.get("url"); } }
private String buildType3Msg (String challenge) throws GeneralSecurityException, IOException { /* First decode the type2 message to get the server nonce */ /* nonce is located at type2[24] for 8 bytes */ byte[] type2 = Base64.getDecoder().decode(challenge); byte[] nonce = new byte[8]; new java.util.Random().nextBytes(nonce); byte[] msg = client.type3(type2, nonce); String result = "NTLM " + Base64.getEncoder().encodeToString(msg); return result; }
@RequestMapping("/jackson") @ResponseBody public String jackson(@RequestParam(value = "sess") String session) throws IOException, ClassNotFoundException { String webUserJackson = new String(Base64.getDecoder().decode(session), "utf-8"); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enableDefaultTyping(); User webUser = (User) objectMapper.readValue(webUserJackson, Object.class); return "Hello " + webUser; }
private void testSubjectPublicKey() throws IOException, GeneralSecurityException { System.out.println("X.509 Certificate Match on subject public key"); // bad match X509CertSelector selector = new X509CertSelector(); X509EncodedKeySpec keySpec = new X509EncodedKeySpec( Base64.getMimeDecoder().decode(testKey.getBytes())); KeyFactory keyFactory = KeyFactory.getInstance("DSA"); PublicKey pubKey = keyFactory.generatePublic(keySpec); selector.setSubjectPublicKey(pubKey); checkMatch(selector, cert, false); // good match selector.setSubjectPublicKey(cert.getPublicKey()); checkMatch(selector, cert, true); }
@Override public Operation sendTo(Integer sender, Integer target, Double amount, Double fee, byte[] payload, PayLoadEncryptionMethod payloadMethod, String pwd) { Operation result = null; if (sender==null||target==null||amount==null||fee==null) throw new IllegalArgumentException("Missing mandatory params. sender,target, amount and fee are mandatory"); Map<String,Object> body = getRPCBody(); Map<String,Object> params = new HashMap<>(); body.put("method","sendto"); params.put("sender", sender); params.put("target", target); params.put("amount", amount); params.put("fee", fee); if (payload!=null) params.put("payload", Base64.getEncoder().encodeToString(payload)); if (payloadMethod!=null) params.put("payloadMethod", payloadMethod); if (pwd!=null) params.put("pwd", pwd); body.put("params",params); Call<OpResult<Operation>> sendToCall= pascalCoinService.sendTo(body); try { Response<OpResult<Operation>> response = sendToCall.execute(); if (response.body().isError()) { logger.log(Level.SEVERE, response.body().getErrorMessage()); throw new RuntimeException(response.body().getErrorMessage()); } result = response.body().getResult(); } catch (IOException e) { logger.log(Level.SEVERE, e.getMessage()); } return result; }
@Override public String convertToEntityAttribute(String dbVal) { if (dbVal == null) { return null; } try { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, key); return new String(cipher.doFinal(Base64.getDecoder().decode(dbVal))); } catch (Exception e) { throw new RuntimeException(e); } }
/*** * Create a new workspace on WCS if target workspace id is not provided Update * an existing workspace if target workspace id is provided * * @param jsonWCSPayload * @return * @throws IOException */ private void checkWCSWorkspace(JsonObject jsonWCSPayload) throws IOException { // Fetch Command Line Params String targetWorkspaceId = getTargetworkspaceID(); String versionDate = getVersionDate(); // Get WCS Creds String wcsCreds = getWCSCreds(); String authorizationHeader = "Basic " + Base64.getEncoder().encodeToString((wcsCreds).getBytes()); // Create or Update Watson Conv Workspace WCSUtils.putWCSWorkspace(targetWorkspaceId, authorizationHeader, versionDate, jsonWCSPayload); }
@Override public JSONObject serialise() { JSONObject json = new JSONObject(); byte[] terrain = new byte[width * width]; for (int x = 0; x < World.WORLD_SIZE; x++) { for (int y = 0; y < World.WORLD_SIZE; y++) { terrain[x * width + y] = (byte) tiles[x][y]; } } try { ByteArrayOutputStream stream = new ByteArrayOutputStream(); Deflater compressor = new Deflater(Deflater.BEST_COMPRESSION, true); DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(stream, compressor); deflaterOutputStream.write(terrain); deflaterOutputStream.close(); byte[] compressedBytes = stream.toByteArray(); json.put("z", new String(Base64.getEncoder().encode(compressedBytes))); } catch (IOException e) { e.printStackTrace(); } return json; }
/** * M:00,01,BASE64 * * First two parts are not known, the base64 encoded string contains the devices and the rooms * */ void parseMeta(Cube cube, String input) throws IOException { String[] metadata = input.split(","); String base64 = metadata[metadata.length - 1]; byte[] data = Base64.getDecoder().decode(base64.getBytes(UTF_8)); try (ByteArrayInputStream bis = new ByteArrayInputStream(data)) { // first numbers are unknown bis.read(); bis.read(); // read rooms int roomCount = bis.read(); for (int i = 0; i < roomCount; i++) { cube.getRooms().add(Room.read(bis)); } // read devices and map to rooms int deviceCount = bis.read(); for (int i = 0; i < deviceCount; i++) { Device device = Device.readFrom(bis); int roomId = bis.read(); Room room = cube.findRoom(roomId); room.getDevices().add(device); } // another last unknown byte bis.read(); } }
private byte[] getPNGData(Picture picture, double width, double height) { Base64.Decoder decoder = Base64.getDecoder(); byte[] decoded = decoder.decode(picture.getContent()); if (picture.getType() == ImageType.SVG) { ByteArrayOutputStream pngStream = new ByteArrayOutputStream(); //svgConverter.convertSvgToPng(new ByteArrayInputStream(decoded), pngStream, (float)width, (float)height); svgConverter.convertSvgToEmf(new ByteArrayInputStream(decoded), pngStream); return pngStream.toByteArray(); } else { return decoded; } }
private static ArrayList<Permission> getPermissions(MySecureClassLoader scl, Policy p, String url, String className, String classBytes, Certificate[] chain) throws IOException { CodeSource cs = new CodeSource(new URL(url), chain); Base64.Decoder bd = Base64.getDecoder(); byte[] bytes = bd.decode(classBytes); Class<?> c = scl.defineMyClass(className, bytes, cs); ProtectionDomain pd = c.getProtectionDomain(); return Collections.list(p.getPermissions(pd).elements()); }
private synchronized String[] getDigests(ZipEntry ze, ZipFile zf, MessageDigest[] digests) throws IOException { int n, i; InputStream is = null; try { is = zf.getInputStream(ze); long left = ze.getSize(); while((left > 0) && (n = is.read(buffer, 0, buffer.length)) != -1) { for (i=0; i<digests.length; i++) { digests[i].update(buffer, 0, n); } left -= n; } } finally { if (is != null) { is.close(); } } // complete the digests String[] base64Digests = new String[digests.length]; for (i=0; i<digests.length; i++) { base64Digests[i] = Base64.getEncoder().encodeToString(digests[i].digest()); } return base64Digests; }
/** * @throws IllegalArgumentException if builder data is invalid. */ public CreateOrUpdateSecretRequestV2 build() { // throws IllegalArgumentException if content not valid base64. Base64.getDecoder().decode(content()); CreateOrUpdateSecretRequestV2 request = autoBuild(); return request; }
/** * @throws IllegalArgumentException if builder data is invalid. */ public CreateSecretRequestV2 build() { // throws IllegalArgumentException if content not valid base64. Base64.getDecoder().decode(content()); CreateSecretRequestV2 request = autoBuild(); if (request.name().isEmpty()) { throw new IllegalStateException("name is empty"); } return request; }
/** * Test changeAccountInfo */ @Test public void testChangeAccountInfo() { Operation op = client.changeAccountInfo(account2Id, account2Id, null, b58PubKey2, "Testing account", Short.parseShort("0"), 0.0, "Testing".getBytes() , PayLoadEncryptionMethod.AES, "123456"); System.out.println(String.format("Operation Hash: %s\nOperation Type: %s(%s),Subtype: %s, Timestamp: %d\nAccount %d Account sender %d Balance: %.4f, Account dest: %d, Amount: %.4f, Block: %d, Fee:%.4f\nErrors %s, OpHash %s,\n Payload %s, Maturation %d, OperationBlock %d, V1Ophash %s\n,Valid %s ", op.getOpHash(), op.getType(),op.getTypeDescriptor(),op.getSubType(), op.getTime(), op.getAccount(),op.getSenderAccount(), op.getBalance(), op.getDestAccount(), op.getAmount(), op.getBlock(), op.getFee(), op.getErrors(),op.getOpHash(), Base64.getEncoder().encodeToString(op.getPayLoad()),op.getMaturation(), op.getOperationBlock(), op.getV1Ophash(), op.getValid() )); assertTrue(op!=null); }
/** * Test sendTo */ @Test public void testSendTo() { Operation op = client.sendTo(accountId, account3Id, 1.0000, 0.0, null, null, null); System.out.println(String.format("Operation Hash: %s\nOperation Type: %s(%s),Subtype: %s, Timestamp: %d\nAccount %d Account sender %d Balance: %.4f, Account dest: %d, Amount: %.4f, Block: %d, Fee:%.4f\nErrors %s, OpHash %s,\n Payload %s, Maturation %d, OperationBlock %d, V1Ophash %s\n,Valid %s ", op.getOpHash(), op.getType(),op.getTypeDescriptor(),op.getSubType(), op.getTime(), op.getAccount(),op.getSenderAccount(), op.getBalance(), op.getDestAccount(), op.getAmount(), op.getBlock(), op.getFee(), op.getErrors(),op.getOpHash(), Base64.getEncoder().encodeToString(op.getPayLoad()),op.getMaturation(), op.getOperationBlock(), op.getV1Ophash(), op.getValid() )); assertTrue(op!=null); }
/** * Test listAccountForSale */ @Test public void testListAccountForSale() { Operation op = client.listAccountForSale(account2Id, account2Id, 1000.0000, accountId, null, null, 151125, 0.0, "Testing listAccountForSale".getBytes() , PayLoadEncryptionMethod.AES, "123456"); System.out.println(String.format("Operation Hash: %s\nOperation Type: %s(%s),Subtype: %s, Timestamp: %d\nAccount %d Account sender %d Balance: %.4f, Account dest: %d, Amount: %.4f, Block: %d, Fee:%.4f\nErrors %s, OpHash %s,\n Payload %s, Maturation %d, OperationBlock %d, V1Ophash %s\n,Valid %s ", op.getOpHash(), op.getType(),op.getTypeDescriptor(),op.getSubType(), op.getTime(), op.getAccount(),op.getSenderAccount(), op.getBalance(), op.getDestAccount(), op.getAmount(), op.getBlock(), op.getFee(), op.getErrors(),op.getOpHash(), Base64.getEncoder().encodeToString(op.getPayLoad()),op.getMaturation(), op.getOperationBlock(), op.getV1Ophash(), op.getValid() )); assertTrue(op!=null); }
public static String getEncodedBasicToken(String apiKey) throws MojoExecutionException { if (apiKey == null || apiKey.isEmpty()) { throw new MojoExecutionException("please provide your Gemnasium apiKey"); } return Base64 .getEncoder() .encodeToString(("X:" + apiKey).getBytes(StandardCharsets.UTF_8)); }
private PublicKey getDERPublicKeyFromPEM(String key) { try { // strip of header, footer, newlines, whitespaces String publicKeyPEM = key .replace("-----BEGIN PUBLIC KEY-----", "") .replace("-----END PUBLIC KEY-----", "") .replaceAll("\\s", ""); // decode to get the binary DER representation byte[] publicKeyDER = Base64.getDecoder().decode(publicKeyPEM); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyDER)); return publicKey; } catch (Exception e) { return null; } }
public GLProof(GLRSSSignatureOutput.GLRSSSignedPart signedPart) { Base64.Encoder encoder = Base64.getEncoder(); this.randomValue = encoder.encodeToString(signedPart.getRandomValue()); this.accumulatorValue = encoder.encodeToString(signedPart.getAccumulatorValue()); this.gsProof = encoder.encodeToString(signedPart.getGsProof()); for (ByteArray byteArray : signedPart.getWitnesses()) { witnesses.add(encoder.encodeToString(byteArray.getArray())); } }
private String getInflatedAuthnRequest(final String location) throws Exception { final List<NameValuePair> pairs = URLEncodedUtils.parse(java.net.URI.create(location), "UTF-8"); final Inflater inflater = new Inflater(true); final byte[] decodedRequest = Base64.getDecoder().decode(pairs.get(0).getValue()); final ByteArrayInputStream is = new ByteArrayInputStream(decodedRequest); final InflaterInputStream inputStream = new InflaterInputStream(is, inflater); final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, HttpConstants.UTF8_ENCODING)); String line; final StringBuilder bldr = new StringBuilder(); while ((line = reader.readLine()) != null) { bldr.append(line); } return bldr.toString(); }
public Image(String base64) throws IOException { this.base64 = base64; byte[] bufferedImageByte = Base64.getDecoder().decode(base64); ByteArrayInputStream bis = new ByteArrayInputStream(bufferedImageByte); this.bufferedImage = ImageIO.read(bis); }
@Test public void testCredentialsEncoder() throws UnsupportedEncodingException { TestUtils.expectedException(IllegalStateException.class, new Runnable() { @Override public void run() { Credentials.encoder().build(); } }); final String secret = "test"; final byte[] secretBytes = ConversionUtils.toBytes(secret); byte[] bytes = Credentials.encoder().secret(secret).build(); assertTrue(Arrays.equals(secretBytes, bytes)); String sb = Credentials.encoder().secret(secret).buildAndEncodeBase64(); assertEquals(Base64.getEncoder().encodeToString(secret.getBytes("UTF-8")), sb); bytes = Credentials.encoder().secret(secret).hashMD5().build(); assertNotNull(bytes); bytes = Credentials.encoder().secret(secret).hashSHA1().build(); assertNotNull(bytes); bytes = Credentials.encoder().secret(secret).hashSHA256().build(); assertNotNull(bytes); bytes = Credentials.encoder().secret(secret).hashSHA384().build(); assertNotNull(bytes); bytes = Credentials.encoder().secret(secret).hashSHA512().charset("UTF-8").build(); assertNotNull(bytes); TestUtils.expectedException(RuntimeException.class, new Runnable() { @Override public void run() { Credentials.encoder().secret("test").hashAlgorithm("xxx").build(); } }); }
private static void testNull(Base64.Encoder enc) { checkNull(() -> enc.encode(ba_null)); checkNull(() -> enc.encodeToString(ba_null)); checkNull(() -> enc.encode(ba_null, new byte[10])); checkNull(() -> enc.encode(new byte[10], ba_null)); checkNull(() -> enc.encode(bb_null)); checkNull(() -> enc.wrap((OutputStream)null)); }