List of usage examples for org.apache.commons.net.util Base64 Base64
public Base64()
From source file:com.znsx.util.licence.LicenceUtil.java
/** * ??//www .j a v a2 s. c o m * * @param seed * ?? * @return * @throws Exception */ public static Map<String, String> generateKey(String seed) throws Exception { Map<String, String> map = new HashMap<String, String>(2); KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA"); SecureRandom random = new SecureRandom(); random.setSeed(seed.getBytes("utf8")); keygen.initialize(1024, random); KeyPair keyPair = keygen.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); Base64 base64 = new Base64(); String publicKeyString = new String(base64.encode(publicKey.getEncoded()), "utf8"); String privateKeyString = new String(base64.encode(privateKey.getEncoded()), "utf8"); // BASE64Encoder encoder = new BASE64Encoder(); // map.put("public", encoder.encode(publicKey.getEncoded())); // map.put("private", encoder.encode(privateKey.getEncoded())); map.put("public", publicKeyString); map.put("private", privateKeyString); System.out.println("publicKey: " + map.get("public")); System.out.println("privateKey: " + map.get("private")); return map; }
From source file:com.znsx.util.licence.LicenceUtil.java
/** * ?DSA??p,q,g,j,x,y/*from w w w .j a va2s. c om*/ * * @param seed * ?? * @throws Exception * @author huangbuji * <p /> * Create at 2014-2-8 ?4:45:26 */ @SuppressWarnings("restriction") public static void genKey(String seed) throws Exception { KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA"); SecureRandom random = new SecureRandom(); random.setSeed(seed.getBytes("utf8")); keygen.initialize(1024, random); KeyPair keyPair = keygen.generateKeyPair(); DSAPublicKeyImpl publicKey = (DSAPublicKeyImpl) keyPair.getPublic(); DSAPrivateKey privateKey = (DSAPrivateKey) keyPair.getPrivate(); DSAParams dsaParams = privateKey.getParams(); Base64 base64 = new Base64(); String p = new String(base64.encode(dsaParams.getP().toByteArray()), "utf8"); String q = new String(base64.encode(dsaParams.getQ().toByteArray()), "utf8"); String g = new String(base64.encode(dsaParams.getG().toByteArray()), "utf8"); String x = new String(base64.encode(privateKey.getX().toByteArray()), "utf8"); String y = new String(base64.encode(publicKey.getY().toByteArray()), "utf8"); System.out.println("P: " + p); System.out.println("Q: " + q); System.out.println("G: " + g); System.out.println("X: " + x); System.out.println("Y: " + y); String publicKeyString = new String(base64.encode(publicKey.getEncoded()), "utf8"); String privateKeyString = new String(base64.encode(privateKey.getEncoded()), "utf8"); System.err.println("public: " + publicKeyString); System.err.println("private: " + privateKeyString); File publicFile = new File("D:/binPublic.ky"); File privateFile = new File("D:/binPrivate.ky"); FileOutputStream out = new FileOutputStream(publicFile); out.write(publicKey.getEncoded()); out.flush(); out.close(); out = new FileOutputStream(privateFile); out.write(privateKey.getEncoded()); out.flush(); out.close(); }
From source file:com.znsx.util.licence.LicenceUtil.java
/** * ?????/* ww w . j av a 2 s. com*/ * * @param data * ?? * @param privateKey * ???base64? * @return base64???? * @throws Exception */ public static String sign(String data, String privateKeyString) throws Exception { Base64 base64 = new Base64(); // ???? // BASE64Decoder decoder = new BASE64Decoder(); // byte[] bytes = decoder.decodeBuffer(privateKeyString); byte[] bytes = base64.decode(privateKeyString.getBytes("utf8")); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes); PrivateKey privateKey = KeyFactory.getInstance("DSA").generatePrivate(keySpec); // ??? Signature signature = Signature.getInstance("DSA"); signature.initSign(privateKey); signature.update(data.getBytes("utf8")); // return new BASE64Encoder().encode(signature.sign()); return new String(base64.encode(signature.sign()), "utf8"); }
From source file:com.fcorti.aaar.GetPentahoTicketWebScript.java
/** * Invoke the REST service and get the result. * @return JSONObject/*w w w .j a v a 2 s.c om*/ */ private final JSONObject getRESTCall() { // Get properties. String protocol = (properties.containsKey(AAARProperties.pentaho_protocol) ? properties.getProperty(AAARProperties.pentaho_protocol) : AAARProperties.pentaho_protocol_default); String host = (properties.containsKey(AAARProperties.pentaho_host) ? properties.getProperty(AAARProperties.pentaho_host) : AAARProperties.pentaho_host_default); String port = (properties.containsKey(AAARProperties.pentaho_port) ? properties.getProperty(AAARProperties.pentaho_port) : AAARProperties.pentaho_port_default); String context = (properties.containsKey(AAARProperties.pentaho_context) ? properties.getProperty(AAARProperties.pentaho_context) : AAARProperties.pentaho_context_default); String user = (properties.containsKey(AAARProperties.pentaho_user) ? properties.getProperty(AAARProperties.pentaho_user) : AAARProperties.pentaho_user_default); String password = (properties.containsKey(AAARProperties.pentaho_password) ? properties.getProperty(AAARProperties.pentaho_password) : AAARProperties.pentaho_password_default); String application = (properties.containsKey(AAARProperties.pentaho_application) ? properties.getProperty(AAARProperties.pentaho_application) : AAARProperties.pentaho_application_default); JSONObject result = new JSONObject(); // REST connection. HttpURLConnection connection; try { String url = protocol + "://" + host + ":" + port + "/" + context + REST_path; URL urlObj = new URL(url); connection = (HttpURLConnection) urlObj.openConnection(); } catch (MalformedURLException e) { logger.error(e); return result; } catch (IOException e) { logger.error(e); return result; } // Authorization. String authorization = "Basic " + (new String(new Base64().encode((user + ":" + password).getBytes()))); // REST properties. try { connection.setDoOutput(true); connection.setRequestMethod(request_method); connection.setRequestProperty(property_authorization, authorization); connection.setRequestProperty(property_content_type, property_content_type_value); } catch (ProtocolException e) { logger.error(e); return result; } // Body. String body = ""; body += parameter_action + "=" + parameter_action_value + "&"; body += parameter_application + "=" + application + "&"; body += parameter_user + "=" + authenticationService.getCurrentUserName() + "&"; OutputStream os; try { os = connection.getOutputStream(); os.write(body.getBytes()); os.flush(); } catch (IOException e) { logger.error(e); return result; } // Get result. String resultAsString = ""; try { BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); resultAsString = br.readLine(); br.close(); } catch (IOException e) { logger.error(e); return result; } // Release of resources. try { os.close(); } catch (IOException e) { logger.error(e); return result; } connection.disconnect(); // Check result to be a JSON. try { JSONParser jsonParser = new JSONParser(); result = (JSONObject) jsonParser.parse(resultAsString); } catch (ParseException e) { logger.error(e); return result; } return result; }
From source file:com.znsx.util.licence.LicenceUtil.java
/** * ???//from w w w . j av a 2 s . c om * * @param data * ?? * @param publicKeyString * ??base64? * @param signature * base64???? * @return * @throws Exception */ public static boolean verify(String data, String publicKeyString, String signature) throws Exception { // ??? // BASE64Decoder decoder = new BASE64Decoder(); // byte[] bytes = decoder.decodeBuffer(publicKeyString); Base64 base64 = new Base64(); byte[] bytes = base64.decode(publicKeyString.getBytes("utf8")); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes); PublicKey publicKey = KeyFactory.getInstance("DSA").generatePublic(keySpec); // ? Signature sign = Signature.getInstance("DSA"); sign.initVerify(publicKey); sign.update(data.getBytes("utf8")); // return sign.verify(decoder.decodeBuffer(signature)); return sign.verify(base64.decode(signature.getBytes("utf8"))); }
From source file:com.znsx.util.licence.LicenceUtil.java
/** * ???// www.j a v a 2s . c om * * @param data * ?? * @param publicKey * 2 * @param signature * base64???? * @return * @throws Exception * @author huangbuji * <p /> * Create at 2014-2-12 ?5:37:18 */ public static boolean verifyBinKey(String data, byte[] publicKey, String signature) throws Exception { Base64 base64 = new Base64(); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey); PublicKey pub = KeyFactory.getInstance("DSA").generatePublic(keySpec); // ? Signature sign = Signature.getInstance("DSA"); sign.initVerify(pub); sign.update(data.getBytes("utf8")); // return sign.verify(decoder.decodeBuffer(signature)); return sign.verify(base64.decode(signature.getBytes("utf8"))); }
From source file:com.znsx.util.licence.LicenceUtil.java
/** * C#?????46?/* ww w . j a v a2 s . co m*/ * * @param sign * base64???? * @return ??? * @throws Exception * @author huangbuji * <p /> * Create at 2014-2-13 ?10:38:46 */ public static byte[] changeDSANet2java(String sign) throws Exception { Base64 base64 = new Base64(); byte tx[] = base64.decode(sign.getBytes("utf8")); byte[] tx_new = new byte[46]; tx_new[0] = 48; tx_new[1] = 44; tx_new[2] = 2; tx_new[3] = 20; for (int x = 0; x < 20; x++) { tx_new[x + 4] = tx[x]; } tx_new[24] = 2; tx_new[25] = 20; for (int x = 20; x < 40; x++) { tx_new[x + 6] = tx[x]; } return tx_new; }
From source file:com.gdo.servlet.RpcWrapper.java
private void apply(StclContext stclContext, RpcArgs args) { try {//from ww w .ja v a 2 s . com String enc = args.getCharacterEncoding(stclContext); // gets stencil PStcl stcl = args.getStencilFromPath(stclContext); if (StencilUtils.isNull(stcl)) { // null stencil may be accepted if (args.acceptNoStencil()) { StudioGdoServlet.writeHTMLResponse(stclContext.getResponse(), "", enc); return; } // return error HttpServletResponse response = stclContext.getResponse(); String msg = logInfo(stclContext, "apply : cannot found stencil at path %s : %s", args.getPath(), StencilUtils.getNullReason(stcl)); response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); return; } // gets command parameter String cmd = args.getStringParameter(stclContext, CMD_PARAM); if (StringUtils.isEmpty(cmd)) { HttpServletResponse response = stclContext.getResponse(); String msg = logWarn(stclContext, "apply : no command name defined (param %s)", CMD_PARAM); response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); return; } // gets command and verifies it exist PStcl cmdStcl = stcl.getCommand(stclContext, cmd); if (StencilUtils.isNull(cmdStcl)) { HttpServletResponse response = stclContext.getResponse(); String msg = logWarn(stclContext, "apply : cannot get command %s for stencil %s", cmd, stcl); response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); return; } // executes atomic action if (cmdStcl.getReleasedStencil(stclContext) instanceof AtomicActionStcl) { // calls execution CommandContext<StclContext, PStcl> cmdContext = createCommandContext(stclContext, args, stcl); CommandStencil<StclContext, PStcl> actionStcl = (CommandStencil<StclContext, PStcl>) cmdStcl .getReleasedStencil(stclContext); CommandStatus<StclContext, PStcl> result = actionStcl.execute(cmdContext, cmdStcl); // returns JSON result StudioGdoServlet.writeHTMLResponse(stclContext.getResponse(), result.jsonValue(result.getStatus()), enc); } else // executes composed action if (cmdStcl.getReleasedStencil(stclContext) instanceof ComposedActionStcl) { // calls execution String launchPath = PathUtils.createPath("/Session/Launch", GlobalCounter.uniqueInt()); CommandContext<StclContext, PStcl> cmdContext = createCommandContext(stclContext, args, stcl); ComposedActionStcl actionStcl = (ComposedActionStcl) cmdStcl.getReleasedStencil(stclContext); CommandStatus<StclContext, PStcl> result = actionStcl.launch(cmdContext, launchPath, cmdStcl); // encodes launched path Base64 base = new Base64(); String launched = result.getInfo(CommandStatus.SUCCESS, ComposedActionStcl.class.getName(), Status.LAUNCH_PATH); String encoded = new String(base.encode(launched.getBytes())); result.setInfo(CommandStatus.SUCCESS, ComposedActionStcl.class.getName(), Status.LAUNCH_PATH, encoded); // returns JSON result StudioGdoServlet.writeHTMLResponse(stclContext.getResponse(), result.jsonValue(result.getStatus()), enc); } // there is no other case else { HttpServletResponse response = stclContext.getResponse(); String msg = logWarn(stclContext, "command %s in stencil %s is not an action", cmd, stcl); response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); return; } } catch (Exception e) { fault(stclContext, LAUNCH_SERVICE, e, null); } }
From source file:com.sos.VirtualFileSystem.DataElements.SOSFileListEntry.java
private long doTransfer(final ISOSVirtualFile objInput, final ISOSVirtualFile objOutput) { @SuppressWarnings("unused") final String conMethodName = conClassName + "::doTransfer"; boolean flgClosingDone = false; if (objOutput == null) { RaiseException(SOSVfs_E_273.params("Target")); }//w w w.j ava 2s . co m if (objInput == null) { RaiseException(SOSVfs_E_273.params("Source")); } boolean flgCreateSecurityHash = objOptions.CreateSecurityHash.value() && flgIsHashFile == false; MessageDigest md = null; if (flgCreateSecurityHash) { try { // TODO implement in value-method of securityhashtype md = MessageDigest.getInstance(objOptions.SecurityHashType.Value()); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); flgCreateSecurityHash = false; } } executePreCommands(); long lngTotalBytesTransferred = 0; Base64 objBase64 = null; this.setStatus(enuTransferStatus.transferring); try { int intCumulativeFileSeperatorLength = 0; int lngBufferSize = objOptions.BufferSize.value(); byte[] buffer = new byte[lngBufferSize]; int intBytesTransferred; int intOffset = 0; boolean flgBase64EncodingOnOutput = false; boolean flgBase64EncodingOnInput = false; if (flgBase64EncodingOnOutput) { objBase64 = new Base64(); } synchronized (this) { if (objOptions.CumulateFiles.isTrue() && objOptions.CumulativeFileSeparator.IsNotEmpty()) { String strFS = objOptions.CumulativeFileSeparator.Value(); strFS = this.replaceVariables(strFS) + System.getProperty("line.separator"); byte[] bteB = strFS.getBytes(); intCumulativeFileSeperatorLength = bteB.length; objOutput.write(bteB); } if (objInput.getFileSize() <= 0) { objOutput.write(buffer, 0, 0); } else { while ((intBytesTransferred = objInput.read(buffer)) != -1) { try { int intBytes2Write = intBytesTransferred; if (flgBase64EncodingOnOutput) { byte[] bteIn = new byte[intBytesTransferred]; byte[] bteOut = objBase64.encode(bteIn); intBytes2Write = bteOut.length; buffer = bteOut; } objOutput.write(buffer, 0, intBytes2Write); } catch (JobSchedulerException e) { e.printStackTrace(System.err); break; } // TODO in case of wrong outputbuffer the handling of the error must be improved lngTotalBytesTransferred += intBytesTransferred; // intOffset += lngTotalBytesTransferred; setTransferProgress(lngTotalBytesTransferred); if (flgCreateSecurityHash) { md.update(buffer, 0, intBytesTransferred); } } } } objInput.closeInput(); objOutput.closeOutput(); flgClosingDone = true; if (flgCreateSecurityHash) { strMD5Hash = toHexString(md.digest()); logger.info(SOSVfs_I_274.params(strMD5Hash, strSourceTransferName, objOptions.SecurityHashType.Value())); if (objOptions.CreateSecurityHashFile.isTrue()) { JSTextFile objF = new JSTextFile(strSourceFileName + "." + objOptions.SecurityHashType.Value()); objF.WriteLine(strMD5Hash); objF.close(); objF.deleteOnExit(); } } // objDataTargetClient.CompletePendingCommand(); if (objDataTargetClient.isNegativeCommandCompletion()) { RaiseException( SOSVfs_E_175.params(objTargetTransferFile.getName(), objDataTargetClient.getReplyString())); } this.setNoOfBytesTransferred(lngTotalBytesTransferred); lngTotalBytesTransferred += intCumulativeFileSeperatorLength; executePostCommands(); return lngTotalBytesTransferred; } catch (Exception e) { RaiseException(e, SOSVfs_E_266.get()); } finally { if (flgClosingDone == false) { objInput.closeInput(); objOutput.closeOutput(); flgClosingDone = true; } } return lngTotalBytesTransferred; }
From source file:org.cloudsimulator.utility.RestAPI.java
private static String getBasicAuth(final String username, final String password) { String authString = username + ":" + password; Base64 base64 = new Base64(); String authStringEnc = new String( base64.encode(authString.getBytes(Charset.forName(CharsetRepository.UTF8))), Charset.forName(CharsetRepository.UTF8)); return "Basic " + authStringEnc.substring(0, authStringEnc.length() - 2); }