List of usage examples for java.util Base64 getDecoder
public static Decoder getDecoder()
From source file:bg.vitkinov.edu.services.JokeService.java
@RequestMapping(method = { RequestMethod.POST, RequestMethod.PUT }) public ResponseEntity<?> insert(@RequestParam String title, @RequestParam String content, @RequestParam(required = false, defaultValue = "false") boolean base64) { String jokeContent = base64 ? new String(Base64.getDecoder().decode(content)) : content; Optional<Joke> joke = jokeRepository.findFirstByContentIgnoreCaseContaining(jokeContent); if (joke.isPresent()) { return new ResponseEntity<>(joke.get(), HttpStatus.CONFLICT); }// ww w .j a v a 2s .c o m Joke newJoke = new Joke(); newJoke.setTitle(title); newJoke.setContent(jokeContent); newJoke.setCategory(findCategories(jokeContent)); return new ResponseEntity<>(jokeRepository.save(newJoke), HttpStatus.CREATED); }
From source file:com.streamsets.datacollector.publicrestapi.CredentialsDeploymentResource.java
private boolean validateSignature(CredentialsBeanJson credentialsBeanJson) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException { // getProperty so we can test it String publicKey = Preconditions.checkNotNull(System.getProperty(DPM_AGENT_PUBLIC_KEY)); X509EncodedKeySpec kspec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey)); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey key = kf.generatePublic(kspec); Signature sig = Signature.getInstance("SHA256withRSA"); sig.initVerify(key);// w ww .ja v a 2s .com sig.update(credentialsBeanJson.getToken().getBytes(Charsets.UTF_8)); LOG.info("Token : {}, Signature {}", credentialsBeanJson.getToken(), credentialsBeanJson.getTokenSignature()); return sig.verify(Base64.getDecoder().decode(credentialsBeanJson.getTokenSignature())); }
From source file:me.ikenga.SvnCollector.java
private long getHeadRevision(SVNURL svnurl) throws ScmException { try {/*from ww w . ja v a 2 s . c o m*/ DAVRepositoryFactory.setup(); SVNRepository repository = SVNRepositoryFactory.create(svnurl); byte[] decodedBytes = Base64.getDecoder().decode(properties.getProperty("password")); ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager( properties.getProperty("username"), new String(decodedBytes)); repository.setAuthenticationManager(authManager); return repository.info(".", SVNRevision.HEAD.getNumber()).getRevision(); } catch (SVNException ex) { throw new ScmException("could not create SvnRepositoryFactory", ex); } }
From source file:ddf.catalog.transformer.output.rtf.BaseTestConfiguration.java
Attribute createInvalidMediaAttribute() throws IOException { Attribute mockAttribute = mock(Attribute.class); byte[] image = Base64.getDecoder().decode(getReferenceImageString().substring(0, 12)); when(mockAttribute.getValue()).thenReturn(image); return mockAttribute; }
From source file:com.adeptj.modules.security.jwt.internal.JwtKeys.java
private static byte[] decodePrivateKeyData(String keyData, boolean encryptedKey) { return Base64.getDecoder() .decode(keyData.replace(encryptedKey ? PRIVATE_ENCRYPTED_KEY_HEADER : PRIVATE_KEY_HEADER, EMPTY) .replace(encryptedKey ? PRIVATE_ENCRYPTED_KEY_FOOTER : PRIVATE_KEY_FOOTER, EMPTY) .replaceAll(REGEX_SPACE, EMPTY).trim().getBytes(UTF_8)); }
From source file:org.apache.syncope.client.console.PreferenceManager.java
public void set(final Request request, final Response response, final String key, final String value) { String prefString = COOKIE_UTILS.load(COOKIE_NAME); final Map<String, String> current = new HashMap<>(); if (prefString != null) { current.putAll(getPrefs(new String(Base64.getDecoder().decode(prefString.getBytes())))); }/*w ww.j ava2 s . c om*/ // after retrieved previous setting in order to overwrite the key ... current.put(key, value); try { COOKIE_UTILS.save(COOKIE_NAME, Base64.getEncoder().encodeToString(setPrefs(current).getBytes())); } catch (IOException e) { LOG.error("Could not save {} info: {}", getClass().getSimpleName(), current, e); } }
From source file:com.github.cambierr.lorawanpacket.semtech.Rxpk.java
public Rxpk(JSONObject _json) throws MalformedPacketException { /**//from w ww.j a v a 2s.c o m * tmst */ if (!_json.has("tmst")) { throw new MalformedPacketException("missing tmst"); } else { tmst = _json.getInt("tmst"); } /** * time */ if (!_json.has("time")) { throw new MalformedPacketException("missing time"); } else { time = _json.getString("time"); } /** * chan */ if (!_json.has("chan")) { throw new MalformedPacketException("missing chan"); } else { chan = _json.getInt("chan"); } /** * rfch */ if (!_json.has("rfch")) { throw new MalformedPacketException("missing rfch"); } else { rfch = _json.getInt("rfch"); } /** * freq */ if (!_json.has("freq")) { throw new MalformedPacketException("missing freq"); } else { freq = _json.getDouble("stat"); } /** * stat */ if (!_json.has("stat")) { throw new MalformedPacketException("missing stat"); } else { stat = _json.getInt("stat"); if (stat > 1 || stat < -1) { throw new MalformedPacketException("stat must be equal to -1, 0, or 1"); } } /** * modu */ if (!_json.has("modu")) { throw new MalformedPacketException("missing modu"); } else { modu = Modulation.parse(_json.getString("modu")); } /** * datr */ if (!_json.has("datr")) { throw new MalformedPacketException("missing datr"); } else { switch (modu) { case FSK: datr = _json.getInt("datr"); break; case LORA: datr = _json.getString("datr"); break; } } /** * codr */ if (!_json.has("codr")) { if (modu.equals(Modulation.FSK)) { codr = null; } else { throw new MalformedPacketException("missing codr"); } } else { codr = _json.getString("codr"); } /** * rssi */ if (!_json.has("rssi")) { throw new MalformedPacketException("missing rssi"); } else { rssi = _json.getInt("rssi"); } /** * lsnr */ if (!_json.has("lsnr")) { if (modu.equals(Modulation.FSK)) { lsnr = Double.MAX_VALUE; } else { throw new MalformedPacketException("missing lsnr"); } } else { lsnr = _json.getDouble("lsnr"); } /** * size */ if (!_json.has("size")) { throw new MalformedPacketException("missing size"); } else { size = _json.getInt("size"); } /** * data */ if (!_json.has("data")) { throw new MalformedPacketException("missing data"); } else { byte[] raw; try { raw = Base64.getDecoder().decode(_json.getString("data")); } catch (IllegalArgumentException ex) { throw new MalformedPacketException("malformed data"); } data = new PhyPayload(ByteBuffer.wrap(raw)); } }
From source file:ai.grakn.engine.tasks.manager.redisqueue.RedisTaskStorage.java
@Override public Set<TaskState> getTasks(@Nullable TaskStatus taskStatus, @Nullable String taskClassName, @Nullable String createdBy, @Nullable EngineID runningOnEngine, int limit, int offset) { try (Jedis jedis = redis.getResource()) { Stream<TaskState> stream = jedis.keys(PREFIX + "*").stream().map(key -> { String v = jedis.get(key); try { return (TaskState) deserialize(Base64.getDecoder().decode(v)); } catch (IllegalArgumentException e) { LOG.error("Could not decode key:value {}:{}", key, v); throw e; }//from w ww . java 2 s. co m }); if (taskStatus != null) { stream = stream.filter(t -> t.status().equals(taskStatus)); } if (taskClassName != null) { stream = stream.filter(t -> t.taskClass().getName().equals(taskClassName)); } if (createdBy != null) { stream = stream.filter(t -> t.creator().equals(createdBy)); } if (runningOnEngine != null) { stream = stream.filter(t -> t.engineID() != null && t.engineID().equals(runningOnEngine)); } stream = stream.skip(offset); if (limit > 0) { stream = stream.limit(limit); } Set<TaskState> results = stream.collect(toSet()); LOG.debug("getTasks returning {} results", results.size()); return results; } catch (Exception e) { throw GraknBackendException.stateStorageTaskRetrievalFailure(e); } }
From source file:ddf.security.cas.WebSSOTokenValidator.java
/** * Validate a Token using the given TokenValidatorParameters. *//*from w w w. j a v a 2s.com*/ @Override public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) { LOGGER.debug("Validating SSO Token"); STSPropertiesMBean stsProperties = tokenParameters.getStsProperties(); Crypto sigCrypto = stsProperties.getSignatureCrypto(); CallbackHandler callbackHandler = stsProperties.getCallbackHandler(); RequestData requestData = new RequestData(); requestData.setSigVerCrypto(sigCrypto); WSSConfig wssConfig = WSSConfig.getNewInstance(); requestData.setWssConfig(wssConfig); requestData.setCallbackHandler(callbackHandler); LOGGER.debug("Setting validate state to invalid before check."); TokenValidatorResponse response = new TokenValidatorResponse(); ReceivedToken validateTarget = tokenParameters.getToken(); validateTarget.setState(STATE.INVALID); response.setToken(validateTarget); if (!validateTarget.isBinarySecurityToken()) { LOGGER.debug("Validate target is not a binary security token, returning invalid response."); return response; } LOGGER.debug("Getting binary security token from validate target"); BinarySecurityTokenType binarySecurityToken = (BinarySecurityTokenType) validateTarget.getToken(); // // Decode the token // LOGGER.debug("Decoding binary security token."); String base64Token = binarySecurityToken.getValue(); String ticket = null; String service = null; try { byte[] token = Base64.getDecoder().decode(base64Token); if (token == null || token.length == 0) { throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "Binary security token NOT successfully decoded, is empty or null."); } String decodedToken = new String(token, Charset.forName("UTF-8")); if (StringUtils.isNotBlank(decodedToken)) { LOGGER.debug("Binary security token successfully decoded: {}", decodedToken); // Token is in the format ticket|service String[] parts = StringUtils.split(decodedToken, CAS_BST_SEP); if (parts.length == 2) { ticket = parts[0]; service = parts[1]; } else { throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "Was not able to parse out BST propertly. Should be in ticket|service format."); } } else { throw new WSSecurityException(WSSecurityException.ErrorCode.INVALID_SECURITY_TOKEN, "Binary security token NOT successfully decoded, is empty or null."); } } catch (WSSecurityException wsse) { String msg = "Unable to decode BST into ticket and service for validation to CAS."; LOGGER.error(msg, wsse); return response; } // // Do some validation of the token here // try { LOGGER.debug("Validating ticket [{}] for service [{}].", ticket, service); // validate either returns an assertion or throws an exception Assertion assertion = validate(ticket, service); AttributePrincipal principal = assertion.getPrincipal(); LOGGER.debug("User name retrieved from CAS: {}", principal.getName()); response.setPrincipal(principal); LOGGER.debug("CAS ticket successfully validated, setting state to valid."); validateTarget.setState(STATE.VALID); } catch (TicketValidationException e) { LOGGER.error("Unable to validate CAS token.", e); } return response; }
From source file:net.menthor.editor.v2.util.Util.java
/** Read the object from Base64 string. */ public static Object fromBase64String(String s) throws IOException, ClassNotFoundException { byte[] data = Base64.getDecoder().decode(s); ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data)); Object o = ois.readObject();/*w w w . j a va 2s .co m*/ ois.close(); return o; }