List of usage examples for org.apache.commons.net.util Base64 encode
public byte[] encode(byte[] pArray)
From source file:com.znsx.util.licence.LicenceUtil.java
/** * ??// www .jav a 2s .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 www . j av a 2 s.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
/** * ?????/*www .ja v a 2s .c om*/ * * @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.gdo.servlet.RpcWrapper.java
private void apply(StclContext stclContext, RpcArgs args) { try {/*from ww w . j av a 2 s. c o m*/ 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 ww. j a v a2 s . c o 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); }