@RequestMapping("/{userPseudo}/validateStep4") public ResponseEntity<Void> validateStep4( @PathVariable("userPseudo") String userPseudo, @RequestParam("userHostAndPort") String userHostAndPort) { log.info("Validation step 4 for player {} with data {}", userPseudo, userHostAndPort); ResponseEntity<Void> result = new ResponseEntity<Void>(HttpStatus.BAD_REQUEST); String url = "http://" + userHostAndPort + "/zen/env"; ResponseEntity<String> responseEntityShouldFail = restTemplate.exchange( url, HttpMethod.GET, new HttpEntity<>(new HttpHeaders()), String.class); byte[] encodedAuth = Base64.encodeBase64("zenika:technozaure".getBytes()); String authHeader = "Basic " + new String(encodedAuth); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.set("Authorization", authHeader); HttpEntity<String> entity = new HttpEntity<>(headers); ResponseEntity<String> responseEntityShouldSucceed = restTemplate.exchange(url, HttpMethod.GET, entity, String.class); if (responseEntityShouldFail.getStatusCode() != HttpStatus.OK && responseEntityShouldSucceed.getStatusCode() == HttpStatus.OK) { gameStepRepository.save(new GameStep(userPseudo, Step._4)); result = new ResponseEntity<Void>(HttpStatus.OK); broadcastGameStatus(); } return result; }
public static String zip(String param) { try { byte[] unzip = param.getBytes("UTF-8"); ByteArrayInputStream bif = new ByteArrayInputStream(unzip); ByteArrayOutputStream zipbof = new ByteArrayOutputStream(); // DeflaterOutputStream dos = new DeflaterOutputStream(zipbof); GZIPOutputStream gos = new GZIPOutputStream(zipbof); int position = 0; for (int read_byte = 0; (read_byte = bif.read()) != -1; position++) { // dos.write(read_byte); gos.write(read_byte); } // dos.finish(); gos.finish(); zipbof.flush(); byte[] zipbyteArray = zipbof.toByteArray(); // return new sun.misc.BASE64Encoder().encode(zipbyteArray); return Base64.encodeBase64String(zipbyteArray); } catch (Exception ex) { return null; } }
@POST @Path("/uploadTone") @Consumes("application/json") public void uploadTone(String file) { File someFile = new File("E:\\recording.3gp"); JSONObject obj; String fileStream; byte[] fileBytes; BufferedOutputStream bos; try { obj = new JSONObject(file); fileStream = obj.getString("name_tone"); fileBytes = Base64.decodeBase64(fileStream.getBytes()); System.out.println(fileBytes); bos = new BufferedOutputStream(new FileOutputStream("E:\\recording.3gp")); bos.write(fileBytes); bos.flush(); bos.close(); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } }
private BasicCredentials(String aMethod, String aUsername, String aPassword) { method = aMethod; username = aUsername; password = aPassword; String userCredentials = username + ":" + password; byte[] credentialsBytes = userCredentials.getBytes(B2CConverter.ISO_8859_1); String base64auth = Base64.encodeBase64String(credentialsBytes); credentials = method + " " + base64auth; }
public Map<String, String> parseTopParameters(String strTopParams, String encode) { if (strTopParams == null) return null; if (encode == null) encode = "GBK"; String keyValues = null; try { keyValues = new String(Base64.decodeBase64(strTopParams.getBytes(encode)), encode); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); } String[] kvPairs = keyValues.split("\\&"); Map<String, String> map = new HashMap<String, String>(); for (String kv : kvPairs) { String[] s = kv.split("\\="); if (s == null || s.length != 2) return null; map.put(s[0], s[1]); } return map; }
public String EncryptText(String RawText) { String EncText = ""; byte[] keyArray = new byte[24]; byte[] temporaryKey; String key = "developersnotedotcom"; byte[] toEncryptArray = null; try { toEncryptArray = RawText.getBytes("UTF-8"); MessageDigest m = MessageDigest.getInstance("MD5"); temporaryKey = m.digest(key.getBytes("UTF-8")); if (temporaryKey.length < 24) // DESede require 24 byte length key { int index = 0; for (int i = temporaryKey.length; i < 24; i++) { keyArray[i] = temporaryKey[index]; } } Cipher c = Cipher.getInstance("DESede/CBC/PKCS5Padding"); c.init( Cipher.ENCRYPT_MODE, new SecretKeySpec(keyArray, "DESede"), new IvParameterSpec(sharedvector)); byte[] encrypted = c.doFinal(toEncryptArray); EncText = Base64.encodeBase64String(encrypted); } catch (NoSuchAlgorithmException | UnsupportedEncodingException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException NoEx) { JOptionPane.showMessageDialog(null, NoEx); } return EncText; }
public static String unzip(String param) { try { // byte[] zipArray = new sun.misc.BASE64Decoder().decodeBuffer(param); byte[] zipArray = Base64.decodeBase64(param); ByteArrayInputStream bif = new ByteArrayInputStream(zipArray); // InflaterInputStream iis = new InflaterInputStream(bif); GZIPInputStream gis = new GZIPInputStream(bif); ByteArrayOutputStream unZipbof = new ByteArrayOutputStream(); int position = 0; // for (int read_byte = 0; (read_byte = iis.read()) != -1; position++) { for (int read_byte = 0; (read_byte = gis.read()) != -1; position++) { unZipbof.write(read_byte); } unZipbof.flush(); byte[] unZipbyteArray = unZipbof.toByteArray(); String returnUnZipString = new String(unZipbyteArray, "UTF-8"); return returnUnZipString; } catch (Exception ex) { return null; } }
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // String currentPath = getServletContext().getResource("/").getPath(); // File dir = new File(currentPath); // String dirName = dir.getParentFile().getParentFile().getAbsolutePath(); // String path = dirName + "/uploads"; // String contextPath = request.getContextPath(); // String projectFolderPath = getProjectFolderPath(contextPath); // String savingPath = projectFolderPath + OpenCVLoader.fileSeparator + // OpenCVLoader.imagesFolder; String savingPath = ImageUtils.getImageSavingDirectory(request); response.setContentType("application/json"); PrintWriter out = response.getWriter(); boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try { // Parse the request List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = iterator.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); if (value.contains("data:image/png;base64,")) { value = value.substring("data:image/png;base64,".length()); } else if (value.contains("data:image/svg+xml;base64,")) { value = value.substring("data:image/svg+xml;base64,".length()); } else if (value.contains("data:image/jpeg;base64,")) { value = value.substring("data:image/jpeg;base64,".length()); } else if (value.contains("data:image/gif;base64,")) { value = value.substring("data:image/gif;base64,".length()); } byte[] contentData = value.getBytes(); byte[] decodedData = Base64.decodeBase64(contentData); String fileName = savingPath + "/" + name + ".png"; FileOutputStream fos = new FileOutputStream(fileName); fos.write(decodedData); fos.flush(); fos.close(); // String rects = classes.FaceDetector.detectFace(fileName); // out.println(rects + " faces detected!!!"); // out.write(rects); out.write("Image imported"); } } } catch (Exception e) { e.printStackTrace(); } } }
public Result send(CouponReqVO couponReq, HttpServletRequest request, boolean isReal) { SendVO sendVO = new SendVO(); if (couponReq.getMid() == null || couponReq.getPassword() == null) { return new Result(100, "필수파라메터 부족"); } // 판매업체 mid와 password가 일치하는지 확인 SellerVO inSeller = new SellerVO(); inSeller.setMid(couponReq.getMid()); inSeller.setPassword(couponReq.getPassword()); SellerVO seller = adminService.getSeller(inSeller); if (seller == null) { return new Result(200, "등록된 판매업체가 아닙니다."); } sendVO.setSeller_id(seller.getSeller_id()); // 등록된 IP인지 확인 String allowed_ip = seller.getAllowed_ip(); if (!allowed_ip.contains(request.getRemoteAddr())) { logger.debug("ip:" + request.getRemoteAddr()); return new Result(300, "허용된 IP가 아닙니다."); } // 상품 정보 확인 GoodsVO inGoods = new GoodsVO(); inGoods.setGoods_code(couponReq.getGoods_code()); inGoods.setReal(isReal); // 실상품 or 테스트 상품 구분 GoodsVO goods = adminService.getGoods(inGoods); if (goods == null) { return new Result(400, "등록된 상품코드가 아닙니다."); } sendVO.setGoods_id(goods.getGoods_id()); // 판매가격은 상품정보의 sell_price로 세팅. 판매업체에게 제공받지 않는다. sendVO.setSell_price(goods.getSell_price()); // 발송정보 세팅 sendVO.setGoods_count("1"); // 상품 수량은 1로 고정 sendVO.setRecv_phone(couponReq.getRecv_phone()); sendVO.setSend_phone(couponReq.getSend_phone()); sendVO.setTr_id(couponReq.getTr_id()); sendVO.setMsg(couponReq.getMessage()); restTemplate = new RestTemplate(); params = new LinkedMultiValueMap<String, String>(); UriComponents uriComponents; String baseUrl = ""; // M12 handling if (goods.getProvider() == 1) { params.add("goods_code", couponReq.getGoods_code()); params.add("goods_count", sendVO.getGoods_count()); // 상품 수량 1로 고정 params.add("send_phone", couponReq.getSend_phone()); params.add("recv_phone", couponReq.getRecv_phone()); params.add("tr_id", couponReq.getTr_id()); params.add("userid", "hlint"); params.add("sell_price", sendVO.getSell_price()); // 상품 판매가격으로 고정 params.add("msg", couponReq.getMessage()); if (isReal) { baseUrl = "http://web6.m12.co.kr:12101/app/order_send.php"; } else { baseUrl = "http://web6.m12.co.kr:12101/app/dev/order_send.php"; } uriComponents = UriComponentsBuilder.fromHttpUrl(baseUrl).queryParams(params).build(); String value = uriComponents.getQuery(); String key = "HLINTNLE54A3I2O1"; String initVector = "J0S9O8T7USJFDLSX"; logger.debug(value); try { IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8")); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(value.getBytes()); String strpara = Base64.encodeBase64String(encrypted); params.clear(); params.add("marketcode", "HLINTNL01"); params.add("strpara", strpara); uriComponents = UriComponentsBuilder.fromHttpUrl(baseUrl).queryParams(params).build(); logger.debug(uriComponents.toUriString()); String strResult = restTemplate.getForObject(uriComponents.toUriString(), String.class); SAXBuilder builder = new SAXBuilder(); Document document = (Document) builder.build(new StringReader(strResult)); Element rootNode = document.getRootElement(); logger.debug(rootNode.getName()); String resultCode = rootNode.getChild("RESULT_CODE", rootNode.getNamespace()).getText(); String statusCode = rootNode.getChild("STATUS_CODE", rootNode.getNamespace()).getText(); // 쿠폰 발송 상태 저장 sendVO.setResult_code(resultCode); sendVO.setStatus_code(statusCode); sendVO.setReal(isReal); logger.debug(sendVO.toString()); adminService.addSend(sendVO); return new Result(Integer.parseInt(resultCode), statusCode); } catch (Exception e) { e.printStackTrace(); return new Result(500, "내부 오류가 발생하였습니다."); } } // Coup handling, 문서 2.18 구현 else if (goods.getProvider() == 2) { params.add("CODE", "0424"); params.add("PASS", "hlint123"); params.add("COUPONCODE", couponReq.getGoods_code()); params.add("SEQNUMBER", couponReq.getTr_id()); params.add("QTY", sendVO.getGoods_count()); // 상품수량은 1개 params.add("HP", couponReq.getRecv_phone()); params.add("CALLBACK", couponReq.getSend_phone()); params.add("TITLE", ""); params.add("ADDMSG", couponReq.getMessage()); params.add("SELPRICE", sendVO.getSell_price()); // 상품 가격 세팅 // logger.debug(params.toString()); if (isReal) { baseUrl = "http://v3api.inumber.co.kr/serviceapi_02.asmx/ServiceCreateSendMuch"; } else { baseUrl = "http://issuev3apitest.m2i.kr:9999/serviceapi_02.asmx/ServiceCreateSendMuch"; } try { uriComponents = UriComponentsBuilder.fromHttpUrl(baseUrl).queryParams(params).build(); logger.debug(uriComponents.toUriString()); String strResult = restTemplate.getForObject(uriComponents.toUriString(), String.class); logger.debug("strResult:" + strResult); SAXBuilder builder = new SAXBuilder(); Document document = (Document) builder.build(new StringReader(strResult)); Element rootNode = document.getRootElement(); String resultCode = rootNode.getChild("RESULTCODE", rootNode.getNamespace()).getText(); String resultMsg = rootNode.getChild("RESULTMSG", rootNode.getNamespace()).getText(); // 쿠폰 발송 상태 저장 sendVO.setResult_code(resultCode); sendVO.setStatus_code(resultMsg); // 쿠폰번호와 핀번호 저장 if ("00".equals(resultCode)) { Element List = rootNode.getChild("LIST", rootNode.getNamespace()); List couponList = List.getChildren("GCOUPONLIST", rootNode.getNamespace()); // 한건만 보내므로 루프를 돌리지않고 한건만 저장 Element node = (Element) couponList.get(0); String couponNumber = node.getChildText("COUPONNUMBER", rootNode.getNamespace()); String pinNumber = node.getChildText("PINNUMBER", rootNode.getNamespace()); sendVO.setCouponnumber(couponNumber); sendVO.setPinnumber(pinNumber); } sendVO.setReal(isReal); logger.debug(sendVO.toString()); adminService.addSend(sendVO); return new Result(Integer.parseInt(resultCode), resultMsg); } catch (Exception e) { e.printStackTrace(); return new Result(100, "Coupon failed"); } } return new Result(500, "내부 오류가 발생하였습니다."); }
public static String getSalt() { Random r = new SecureRandom(); byte[] saltBytes = new byte[32]; r.nextBytes(saltBytes); return Base64.encodeBase64String(saltBytes); }
@Override public boolean authenticate(Request request, HttpServletResponse response, LoginConfig config) throws IOException { if (checkForCachedAuthentication(request, response, true)) { return true; } MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders().getValue("authorization"); if (authorization == null) { if (log.isDebugEnabled()) { log.debug(sm.getString("authenticator.noAuthHeader")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } authorization.toBytes(); ByteChunk authorizationBC = authorization.getByteChunk(); if (!authorizationBC.startsWithIgnoreCase("negotiate ", 0)) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.authHeaderNotNego")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } authorizationBC.setOffset(authorizationBC.getOffset() + 10); byte[] decoded = Base64.decodeBase64( authorizationBC.getBuffer(), authorizationBC.getOffset(), authorizationBC.getLength()); if (getApplyJava8u40Fix()) { SpnegoTokenFixer.fix(decoded); } if (decoded.length == 0) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.authHeaderNoToken")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } LoginContext lc = null; GSSContext gssContext = null; byte[] outToken = null; Principal principal = null; try { try { lc = new LoginContext(getLoginConfigName()); lc.login(); } catch (LoginException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return false; } Subject subject = lc.getSubject(); // Assume the GSSContext is stateless // TODO: Confirm this assumption final GSSManager manager = GSSManager.getInstance(); // IBM JDK only understands indefinite lifetime final int credentialLifetime; if (Globals.IS_IBM_JVM) { credentialLifetime = GSSCredential.INDEFINITE_LIFETIME; } else { credentialLifetime = GSSCredential.DEFAULT_LIFETIME; } final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() { @Override public GSSCredential run() throws GSSException { return manager.createCredential( null, credentialLifetime, new Oid("1.3.6.1.5.5.2"), GSSCredential.ACCEPT_ONLY); } }; gssContext = manager.createContext(Subject.doAs(subject, action)); outToken = Subject.doAs(lc.getSubject(), new AcceptAction(gssContext, decoded)); if (outToken == null) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail")); } // Start again response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } principal = Subject.doAs( subject, new AuthenticateAction(context.getRealm(), gssContext, storeDelegatedCredential)); } catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail"), e); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } catch (PrivilegedActionException e) { Throwable cause = e.getCause(); if (cause instanceof GSSException) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.serviceLoginFail"), e); } } else { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } finally { if (gssContext != null) { try { gssContext.dispose(); } catch (GSSException e) { // Ignore } } if (lc != null) { try { lc.logout(); } catch (LoginException e) { // Ignore } } } // Send response token on success and failure response.setHeader("WWW-Authenticate", "Negotiate " + Base64.encodeBase64String(outToken)); if (principal != null) { register(request, response, principal, Constants.SPNEGO_METHOD, principal.getName(), null); Pattern p = noKeepAliveUserAgents; if (p != null) { MessageBytes ua = request.getCoyoteRequest().getMimeHeaders().getValue("user-agent"); if (ua != null && p.matcher(ua.toString()).matches()) { response.setHeader("Connection", "close"); } } return true; } response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; }