Java Examples for sun.misc.BASE64Encoder
The following java examples will help you to understand the usage of sun.misc.BASE64Encoder. These source code samples are taken from different open source projects.
Example 1
Project: BettaServer-master File: UsuarioUtil.java View source code |
public static String criptografaSenha(String senha) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(senha.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); return senha; } }
Example 2
Project: javamelody-master File: TestBase64Coder.java View source code |
/** * Test Base64Coder against sun.misc.BASE64Encoder/Decoder with random data. * Line length below 76. * @throws IOException e */ @SuppressWarnings("restriction") @Test public void test2() throws IOException { // the Sun encoder adds a CR/LF when a line is longer final int maxLineLen = 76 - 1; final int maxDataBlockLen = maxLineLen * 3 / 4; final sun.misc.BASE64Encoder sunEncoder = new sun.misc.BASE64Encoder(); final sun.misc.BASE64Decoder sunDecoder = new sun.misc.BASE64Decoder(); final Random rnd = new Random(0x538afb92); for (int i = 0; i < 100; i++) { final int len = rnd.nextInt(maxDataBlockLen + 1); final byte[] b0 = new byte[len]; rnd.nextBytes(b0); final String e1 = new String(Base64Coder.encode(b0)); final String e2 = sunEncoder.encode(b0); assertEquals("test2", e2, e1); final byte[] b1 = Base64Coder.decode(e1); final byte[] b2 = sunDecoder.decodeBuffer(e2); assertArrayEquals(b0, b1); assertArrayEquals(b0, b2); } }
Example 3
Project: javamelody-mirror-backup-master File: TestBase64Coder.java View source code |
/** * Test Base64Coder against sun.misc.BASE64Encoder/Decoder with random data. * Line length below 76. * @throws IOException e */ @SuppressWarnings("restriction") @Test public void test2() throws IOException { // the Sun encoder adds a CR/LF when a line is longer final int maxLineLen = 76 - 1; final int maxDataBlockLen = maxLineLen * 3 / 4; final sun.misc.BASE64Encoder sunEncoder = new sun.misc.BASE64Encoder(); final sun.misc.BASE64Decoder sunDecoder = new sun.misc.BASE64Decoder(); final Random rnd = new Random(0x538afb92); for (int i = 0; i < 100; i++) { final int len = rnd.nextInt(maxDataBlockLen + 1); final byte[] b0 = new byte[len]; rnd.nextBytes(b0); final String e1 = new String(Base64Coder.encode(b0)); final String e2 = sunEncoder.encode(b0); assertEquals("test2", e2, e1); final byte[] b1 = Base64Coder.decode(e1); final byte[] b2 = sunDecoder.decodeBuffer(e2); assertArrayEquals(b0, b1); assertArrayEquals(b0, b2); } }
Example 4
Project: processFlowProvision-master File: GuvnorRestApi.java View source code |
public InputStream getBinaryPackage(String packageName) throws java.io.IOException { String urlString = guvnorURI + "/rest/packages/" + packageName + "/binary"; URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_OCTET_STREAM); BASE64Encoder enc = new sun.misc.BASE64Encoder(); String userpassword = "admin:admin"; String encodedAuth = enc.encode(userpassword.getBytes()); connection.setRequestProperty("Authorization", "Basic " + encodedAuth); connection.connect(); log.info("getBinaryPackage() response code for GET request to : " + urlString + " is : " + connection.getResponseCode()); iStream = connection.getInputStream(); return iStream; }
Example 5
Project: clock-in-out-cpsc502-final-project-master File: DesEncrypter.java View source code |
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
Example 6
Project: encryption-jvm-bootcamp-master File: TestBase64Sun.java View source code |
@Test public void testBase64Apache() throws IOException { final String message1 = "This is <bold>code</bold> with \t tabs, semicolons;" + " and alert-bells \b that could cause escaping issues if not encoded in Base64"; System.out.println("Sun Raw text:\r\n" + message1); System.out.println("Sun Raw text byte count: " + message1.length() + "\r\n"); Assert.assertEquals(126, message1.length()); BASE64Encoder b64e = new sun.misc.BASE64Encoder(); String base64Encoded = b64e.encode(message1.getBytes("UTF-8")); System.out.println("Sun Base64 encoded text:\r\n" + base64Encoded); System.out.println("Sun Base64 encoded text byte count: " + base64Encoded.length() + "\r\n"); //Isn't it awesome that it has newlines embedded? Assert.assertEquals("VGhpcyBpcyA8Ym9sZD5jb2RlPC9ib2xkPiB3aXRoIAkgdGFicywgc2VtaWNvbG9uczsgYW5kIGFs\n" + "ZXJ0LWJlbGxzIAggdGhhdCBjb3VsZCBjYXVzZSBlc2NhcGluZyBpc3N1ZXMgaWYgbm90IGVuY29k\n" + "ZWQgaW4gQmFzZTY0", base64Encoded); BASE64Decoder b64d = new sun.misc.BASE64Decoder(); String base64Decoded = new String(b64d.decodeBuffer(base64Encoded), "UTF-8"); System.out.println("Sun Decoded text:\r\n" + base64Decoded); Assert.assertEquals(message1, base64Decoded); }
Example 7
Project: java-basecamp-api-wrapper-master File: BaseCampEntity.java View source code |
//--- Base REST interaction methods /*** * GET HTTP Operation * * @param request Request URI * @return Element Root Element of XML Response */ protected Element get(String request) { HttpURLConnection connection = null; Element rootElement; try { URL url = new URL(this.baseUrl + request); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); BASE64Encoder enc = new sun.misc.BASE64Encoder(); String userpassword = this.username + ":" + this.password; String encodedAuthorization = enc.encode(userpassword.getBytes()); connection.setRequestProperty("Authorization", "Basic " + encodedAuthorization); connection.setRequestProperty("Content-type", "application/xml"); connection.setRequestProperty("Accept", "application/xml"); InputStream responseStream = connection.getInputStream(); //--- Parse XML response InputStream into DOM DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(responseStream); rootElement = doc.getDocumentElement(); } catch (Exception e) { System.out.print(e.toString()); rootElement = null; } finally { if (connection != null) { connection.disconnect(); } } return rootElement; }
Example 8
Project: jdeps-maven-plugin-master File: AbstractDependencyJudgeTest.java View source code |
@Test public void judgeSeverity_dependencyOccursInSamePackageRule_ruleIsNotApplied() { DependencyJudge judge = builder().withDefaultSeverity(Severity.INFORM).addDependency(// this rule defined for "sun.misc.Unsafe" MUST NOT be applied to "sun.misc.BASE64Encoder" "com.foo.Bar", "sun.misc.Unsafe", Severity.FAIL).build(); Severity severity = judge.judgeSeverity("com.foo.Bar", "sun.misc.BASE64Encoder"); assertThat(severity).isSameAs(Severity.INFORM); }
Example 9
Project: ephesoft-extension-master File: PushBulletHelper.java View source code |
public boolean testConnection() {
boolean verified = false;
int responseCode;
try {
// Trying to get the list of devices
URL obj = new URL(getTestUrl());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
// Set authentication
String userPassword = getApiKey() + ":";
String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
con.setRequestProperty("Authorization", "Basic " + encoding);
responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
verified = responseCode == 200;
} catch (Exception e) {
e.printStackTrace();
}
return verified;
}
Example 10
Project: infoglue-maven-master File: PropertiesFilePropertySet.java View source code |
//~ Methods //////////////////////////////////////////////////////////////// public void flush() throws IOException { Iterator iter = getMap().entrySet().iterator(); Properties p = new Properties(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String name = (String) entry.getKey(); ValueEntry valueEntry = (ValueEntry) entry.getValue(); String value; switch(valueEntry.getType()) { case XML: value = XMLUtils.print((Document) valueEntry.getValue()); break; case PROPERTIES: case OBJECT: ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream os = new ObjectOutputStream(bos); os.writeObject(valueEntry.getValue()); byte[] data = bos.toByteArray(); value = new sun.misc.BASE64Encoder().encode(data); break; case DATE: value = DateFormat.getDateTimeInstance().format((Date) valueEntry.getValue()); break; case DATA: if (valueEntry.getValue() instanceof byte[]) { value = new sun.misc.BASE64Encoder().encode((byte[]) valueEntry.getValue()); } else { value = new sun.misc.BASE64Encoder().encode(((Data) valueEntry.getValue()).getBytes()); } break; default: value = valueEntry.getValue().toString(); } p.put(name + "." + valueEntry.getType(), value); } p.store(new FileOutputStream(file), null); }
Example 11
Project: aq2o-master File: Crypter.java View source code |
public String encryptBlowfish(String to_encrypt) { try { SecretKeySpec key = new SecretKeySpec(strkey.getBytes(), "Blowfish"); Cipher cipher = Cipher.getInstance("Blowfish"); cipher.init(Cipher.ENCRYPT_MODE, key); BASE64Encoder enc = new BASE64Encoder(); return enc.encode(cipher.doFinal(to_encrypt.getBytes())); } catch (Exception e) { return null; } }
Example 12
Project: codjo-data-process-master File: DpFdownloadCommand.java View source code |
@Override public CommandResult executeQuery(CommandQuery query) throws HandlerException, SQLException { StringBuilder response = new StringBuilder(); String filePath = query.getArgumentString("filePath"); int block = query.getArgumentInteger("block"); int blockSize = query.getArgumentInteger("blockSize"); BASE64Encoder base64Encoder = new BASE64Encoder(); try { FileInputStream fis = new FileInputStream(filePath); long skipped = fis.skip(block * blockSize); response.append(skipped).append("\n"); byte[] toRead = new byte[blockSize]; int realReader = fis.read(toRead); response.append(realReader).append("\n"); response.append(base64Encoder.encode(toRead)); fis.close(); } catch (IOException ex) { throw new HandlerException(ex.getLocalizedMessage() + " (filePath = " + filePath + ", block = " + block + ", blockSize = " + blockSize + ") ", ex); } return createResult(response.toString()); }
Example 13
Project: JFOA-master File: Image2Base64str.java View source code |
public static String GetImageStr(File img) { byte[] data = null; // 读å?–图片å—节数组 try { InputStream in = new FileInputStream(img); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } // 对å—节数组Base64ç¼–ç ? BASE64Encoder encoder = new BASE64Encoder(); // 返回Base64ç¼–ç ?过的å—节数组å—符串 return encoder.encode(data); }
Example 14
Project: moonjava-flight-master File: LoginController.java View source code |
private void logar() {
// Encriptografia para senha utilizando codigos 'sun.misc.BASE64Encoder'
EncryptPassword encrypt = new EncryptPassword();
RequestParamWrapper request = getLogin();
request.set("senha", encrypt.toEncryptMD5(request.stringParam("senha")));
Usuario usuarioLogado = new UsuarioModel().consultarUsuario(request);
// Usuario Logado finaliza Frame atual e inicializa a Frame principal
if (usuarioLogado != null) {
new FlightController(usuarioLogado, bundle);
new PainelController(bundle);
dispose();
} else {
incorrectLoginMessage();
}
}
Example 15
Project: mtools-master File: Crypto.java View source code |
public static String encode(String vClearText) throws Exception { String encode = ""; CEA cea = new CEA(); byte[] key = "12345678".getBytes(); int intStrLen = vClearText.length(); if (intStrLen < 16) { for (int i = 0; i < 16 - intStrLen; i++) vClearText = String.valueOf(String.valueOf(vClearText)).concat(" "); } byte plain[] = vClearText.getBytes(); byte cipher[] = new byte[plain.length]; cea.Encrypt(plain, cipher, plain.length, key, key.length); BASE64Encoder b64Enc = new BASE64Encoder(); encode = b64Enc.encode(cipher); return encode; }
Example 16
Project: ServletStudyDemo-master File: AutoLoginFilter.java View source code |
//½«Óû§ÃûÃÜÂëºÍcookieÎÞЧÆÚÁªºÏmd5Ï£¬·ÀÖ¹ÃÜÂë±»È˱©Á¦Æƽâ private String md5(String username, String password, long expirestime) { String value = password + ":" + expirestime + ":" + username; //ʹÓÃMessageDigest½«Ò»¸ö×Ö·û´®md5 try { // ·µ»ØʵÏÖÖ¸¶¨ÕªÒªËã·¨µÄ MessageDigest ¶ÔÏó MessageDigest md = MessageDigest.getInstance("md5"); byte md5[] = md.digest(value.getBytes()); //ʹÓÃBASE64¶Ômd5±àÂë BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(md5); } catch (Exception e) { throw new RuntimeException(e); } }
Example 17
Project: twilio-cookbook-master File: PasswordUtils.java View source code |
public static String createPasswordWithHashAlgorithm(String pwd, String algorithm) {
MessageDigest md;
try {
// es MD5, SHA-256
md = MessageDigest.getInstance(algorithm);
md.update(pwd.getBytes());
byte[] enc = md.digest();
// Encode bytes to base64 to get a string
String encode = new BASE64Encoder().encode(enc);
logger.info(encode);
return encode;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
Example 18
Project: jcommerce-master File: SendMail.java View source code |
public boolean sendChangePWMail(String pwd) { Properties props = new Properties(); props.put("mail.smtp.host", "smtp.vanceinfo.com"); //å…?许smtpæ ¡éªŒ props.put("mail.smtp.auth", "true"); Session sendMailSession = Session.getInstance(props, null); try { Transport transport = sendMailSession.getTransport("smtp"); transport.connect("smtp.vanceinfo.com", "zhao_jin", "2008YWBOMHF"); Message newMessage = new MimeMessage(sendMailSession); //设置mail主题 String mail_subject = "更改ishop账户密ç ?"; sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); newMessage.setSubject("=?GB2312?B?" + enc.encode(mail_subject.getBytes()) + "?="); //设置å?‘信人地å?€ String strFrom = "zhao_jin@vanceinfo.com"; strFrom = new String(strFrom.getBytes(), "8859_1"); newMessage.setFrom(new InternetAddress(strFrom)); //设置收件人地å?€ newMessage.setRecipients(Message.RecipientType.TO, this.addressTo); //设置mailæ£æ–‡ newMessage.setSentDate(new java.util.Date()); String mail_text = "尊敬的用户" + this.userName + ":\n" + " 您好ï¼?您的密ç ?已被é‡?置为" + pwd + ",请å?Šæ—¶ä¿®æ”¹ä»¥å…?é€ æˆ?ä¸?å¿…è¦?çš„æ?Ÿå¤±ï¼?\n\n" + "ishop客æœ?\n" + "zj36083@163.com"; mail_text = new String(mail_text.getBytes("iso-8859-1"), "gb2312"); newMessage.setContent(mail_text, "text/plain;charset=gb2312"); //ä¿?å˜å?‘é€?ä¿¡æ?¯ newMessage.saveChanges(); //å?‘é€?邮件 transport.sendMessage(newMessage, newMessage.getRecipients(Message.RecipientType.TO)); transport.close(); System.out.println("Send successï¼?"); return true; } catch (Exception e) { System.out.println("Send false!" + e); return false; } }
Example 19
Project: OneSwarm-master File: InlineResourceContext.java View source code |
@Override public String deploy(String suggestedFileName, String mimeType, byte[] data, boolean xhrCompatible) throws UnableToCompleteException { TreeLogger logger = getLogger(); // data: URLs are not compatible with XHRs on FF and Safari browsers if ((!xhrCompatible) && (data.length < MAX_INLINE_SIZE)) { logger.log(TreeLogger.DEBUG, "Inlining", null); // This is bad, but I am lazy and don't want to write _another_ encoder sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); String base64Contents = enc.encode(data).replaceAll("\\s+", ""); return "\"data:" + mimeType + ";base64," + base64Contents + "\""; } else { return super.deploy(suggestedFileName, mimeType, data, true); } }
Example 20
Project: opennms_dashboard-master File: BasicHttpMethods.java View source code |
/* ********************************************************************* * BASIC HTTP POST, DELETE PUT AND GET METHODS * See http://stackoverflow.com/questions/1051004/how-to-send-put-delete * *********************************************************************/ /** * Sends an HTTP GET request to a url * * @param endpoint - The URL of the server. (Example: " http://www.yahoo.com/search") * @param requestParameters - all the request parameters (Example: "param1=val1¶m2=val2"). Note: This method will add the question mark (?) to the request - DO NOT add it yourself * @return - The response from the end point */ public String sendGetRequest(String endpoint, String requestParameters, String username, String password) throws Exception { String result = null; if (endpoint.startsWith("http://")) { // Send a GET request to the servlet try { // Send data String urlStr = endpoint; if (requestParameters != null && requestParameters.length() > 0) { urlStr += "?" + requestParameters; } URL url = new URL(urlStr); URLConnection conn = url.openConnection(); // set username and password // see http://www.javaworld.com/javaworld/javatips/jw-javatip47.html String userPassword = username + ":" + password; // Encode String // String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes()); // depreciated sun.misc.BASE64Encoder() byte[] encoding = org.apache.commons.codec.binary.Base64.encodeBase64(userPassword.getBytes()); String authStringEnc = new String(encoding); log.debug("Base64 encoded auth string: '" + authStringEnc + "'"); conn.setRequestProperty("Authorization", "Basic " + authStringEnc); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); result = sb.toString(); } catch (Throwable e) { throw new Exception("problem issuing get to URL", e); } } return result; }
Example 21
Project: collaboro-master File: AbstractRendererServlet.java View source code |
/** * Encodes a JPG picture into the BASE64 format * * @param imagePath * @return * @throws IOException */ String encodeToString(File imagePath) throws IOException { BufferedImage image = ImageIO.read(imagePath); String imageString = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ImageIO.write(image, "JPG", bos); byte[] imageBytes = bos.toByteArray(); BASE64Encoder encoder = new BASE64Encoder(); imageString = encoder.encode(imageBytes); bos.close(); } catch (IOException e) { e.printStackTrace(); } return imageString; }
Example 22
Project: glassfish-master File: TestClient.java View source code |
private int invokeServlet(String url, String userPassword) throws Exception {
log("Invoking url = " + url + ", password = " + userPassword);
URL u = new URL(url);
String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
HttpURLConnection c1 = (HttpURLConnection) u.openConnection();
c1.setRequestProperty("Authorization", "Basic " + encoding);
int code = c1.getResponseCode();
InputStream is = c1.getInputStream();
BufferedReader input = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = input.readLine()) != null) {
log(line);
if (line.indexOf("So the RESULT OF EJB webservice IS") != -1)
found1 = true;
if (line.indexOf("[JBI-SecurityTest PrincipalSent=user PrincipalGot=user]") != -1)
found2 = true;
}
return code;
}
Example 23
Project: gscrot-imgur-master File: Imgur.java View source code |
public static String upload(byte[] b) throws Exception {
URL url = new URL("https://api.imgur.com/3/image");
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
String sImage = new BASE64Encoder().encode(b);
String postdata = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(sImage, "UTF-8");
uc.setDoOutput(true);
uc.setDoInput(true);
uc.setRequestMethod("POST");
uc.setRequestProperty("Authorization", "Client-ID " + CLIENT_ID);
uc.connect();
OutputStreamWriter writer = new OutputStreamWriter(uc.getOutputStream());
writer.write(postdata);
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String s = "";
String line;
while ((line = reader.readLine()) != null) {
s += line + "\n";
}
writer.close();
reader.close();
System.out.println(s);
return s.toString();
}
Example 24
Project: java_security-master File: Base64Test.java View source code |
// 用jdk实现 public static void jdkBase64() { try { BASE64Encoder encoder = new BASE64Encoder(); String encode = encoder.encode(src.getBytes()); System.out.println("encode:" + encode); BASE64Decoder decoder = new BASE64Decoder(); System.out.println("decode:" + new String(decoder.decodeBuffer(encode))); } catch (Exception e) { e.printStackTrace(); } }
Example 25
Project: jdk7u-jdk-master File: Test6277246.java View source code |
public static void main(String[] args) throws IntrospectionException {
Class type = BASE64Encoder.class;
System.setSecurityManager(new SecurityManager());
BeanInfo info = Introspector.getBeanInfo(type);
for (MethodDescriptor md : info.getMethodDescriptors()) {
Method method = md.getMethod();
System.out.println(method);
String name = method.getDeclaringClass().getName();
if (name.startsWith("sun.misc.")) {
throw new Error("found inaccessible method");
}
}
}
Example 26
Project: livepreview_test_sauce-master File: SauceREST.java View source code |
public void updateJobInfo(String jobId, Map<String, Object> updates) throws IOException { URL restEndpoint = new URL(RESTURL + "/v1/" + username + "/jobs/" + jobId); String auth = username + ":" + accessKey; BASE64Encoder encoder = new BASE64Encoder(); auth = "Basic " + new String(encoder.encode(auth.getBytes())); HttpURLConnection postBack = (HttpURLConnection) restEndpoint.openConnection(); postBack.setDoOutput(true); postBack.setRequestMethod("PUT"); postBack.setRequestProperty("Authorization", auth); String jsonText = JSONValue.toJSONString(updates); postBack.getOutputStream().write(jsonText.getBytes()); postBack.getInputStream().close(); }
Example 27
Project: ManagedRuntimeInitiative-master File: Test6277246.java View source code |
public static void main(String[] args) {
try {
System.setSecurityManager(new SecurityManager());
Class container = Class.forName("java.lang.Class");
Class parameter = Class.forName("java.lang.String");
Method method = container.getMethod("forName", parameter);
Object[] arglist = new Object[] { "sun.misc.BASE64Encoder" };
EventHandler eh = new EventHandler(Test6277246.class, "forName", "", "forName");
Object object = eh.invoke(null, method, arglist);
throw new Error((object != null) ? "test failure" : "test error");
} catch (ClassNotFoundException exception) {
throw new Error("unexpected exception", exception);
} catch (NoSuchMethodException exception) {
throw new Error("unexpected exception", exception);
} catch (RuntimeException exception) {
if (exception.getCause() instanceof SecurityException) {
return;
}
throw new Error("unexpected exception", exception);
}
}
Example 28
Project: openjdk8-jdk-master File: TestBase64.java View source code |
private static void test(Base64.Encoder enc, Base64.Decoder dec, int numRuns, int numBytes) throws Throwable {
Random rnd = new java.util.Random();
enc.encode(new byte[0]);
dec.decode(new byte[0]);
for (int i = 0; i < numRuns; i++) {
for (int j = 1; j < numBytes; j++) {
byte[] orig = new byte[j];
rnd.nextBytes(orig);
// --------testing encode/decode(byte[])--------
byte[] encoded = enc.encode(orig);
byte[] decoded = dec.decode(encoded);
checkEqual(orig, decoded, "Base64 array encoding/decoding failed!");
// compare to sun.misc.BASE64Encoder
byte[] encoded2 = sunmisc.encode(orig).getBytes("ASCII");
checkEqual(normalize(encoded), normalize(encoded2), "Base64 enc.encode() does not match sun.misc.base64!");
// remove padding '=' to test non-padding decoding case
if (encoded[encoded.length - 2] == '=')
encoded2 = Arrays.copyOf(encoded, encoded.length - 2);
else if (encoded[encoded.length - 1] == '=')
encoded2 = Arrays.copyOf(encoded, encoded.length - 1);
else
encoded2 = null;
// --------testing encodetoString(byte[])/decode(String)--------
String str = enc.encodeToString(orig);
if (!Arrays.equals(str.getBytes("ASCII"), encoded)) {
throw new RuntimeException("Base64 encodingToString() failed!");
}
byte[] buf = dec.decode(new String(encoded, "ASCII"));
checkEqual(buf, orig, "Base64 decoding(String) failed!");
if (encoded2 != null) {
buf = dec.decode(new String(encoded2, "ASCII"));
checkEqual(buf, orig, "Base64 decoding(String) failed!");
}
//-------- testing encode/decode(Buffer)--------
testEncode(enc, ByteBuffer.wrap(orig), encoded);
ByteBuffer bin = ByteBuffer.allocateDirect(orig.length);
bin.put(orig).flip();
testEncode(enc, bin, encoded);
testDecode(dec, ByteBuffer.wrap(encoded), orig);
bin = ByteBuffer.allocateDirect(encoded.length);
bin.put(encoded).flip();
testDecode(dec, bin, orig);
if (encoded2 != null)
testDecode(dec, ByteBuffer.wrap(encoded2), orig);
// -------- testing encode(Buffer, Buffer)--------
testEncode(enc, encoded, ByteBuffer.wrap(orig), ByteBuffer.allocate(encoded.length + 10));
testEncode(enc, encoded, ByteBuffer.wrap(orig), ByteBuffer.allocateDirect(encoded.length + 10));
// --------testing decode(Buffer, Buffer);--------
testDecode(dec, orig, ByteBuffer.wrap(encoded), ByteBuffer.allocate(orig.length + 10));
testDecode(dec, orig, ByteBuffer.wrap(encoded), ByteBuffer.allocateDirect(orig.length + 10));
// --------testing decode.wrap(input stream)--------
// 1) random buf length
ByteArrayInputStream bais = new ByteArrayInputStream(encoded);
InputStream is = dec.wrap(bais);
buf = new byte[orig.length + 10];
int len = orig.length;
int off = 0;
while (true) {
int n = rnd.nextInt(len);
if (n == 0)
n = 1;
n = is.read(buf, off, n);
if (n == -1) {
checkEqual(off, orig.length, "Base64 stream decoding failed");
break;
}
off += n;
len -= n;
if (len == 0)
break;
}
buf = Arrays.copyOf(buf, off);
checkEqual(buf, orig, "Base64 stream decoding failed!");
// 2) read one byte each
bais.reset();
is = dec.wrap(bais);
buf = new byte[orig.length + 10];
off = 0;
int b;
while ((b = is.read()) != -1) {
buf[off++] = (byte) b;
}
buf = Arrays.copyOf(buf, off);
checkEqual(buf, orig, "Base64 stream decoding failed!");
// --------testing encode.wrap(output stream)--------
ByteArrayOutputStream baos = new ByteArrayOutputStream((orig.length + 2) / 3 * 4 + 10);
OutputStream os = enc.wrap(baos);
off = 0;
len = orig.length;
for (int k = 0; k < 5; k++) {
if (len == 0)
break;
int n = rnd.nextInt(len);
if (n == 0)
n = 1;
os.write(orig, off, n);
off += n;
len -= n;
}
if (len != 0)
os.write(orig, off, len);
os.close();
buf = baos.toByteArray();
checkEqual(buf, encoded, "Base64 stream encoding failed!");
// 2) write one byte each
baos.reset();
os = enc.wrap(baos);
off = 0;
while (off < orig.length) {
os.write(orig[off++]);
}
os.close();
buf = baos.toByteArray();
checkEqual(buf, encoded, "Base64 stream encoding failed!");
// --------testing encode(in, out); -> bigger buf--------
buf = new byte[encoded.length + rnd.nextInt(100)];
int ret = enc.encode(orig, buf);
checkEqual(ret, encoded.length, "Base64 enc.encode(src, null) returns wrong size!");
buf = Arrays.copyOf(buf, ret);
checkEqual(buf, encoded, "Base64 enc.encode(src, dst) failed!");
// --------testing decode(in, out); -> bigger buf--------
buf = new byte[orig.length + rnd.nextInt(100)];
ret = dec.decode(encoded, buf);
checkEqual(ret, orig.length, "Base64 enc.encode(src, null) returns wrong size!");
buf = Arrays.copyOf(buf, ret);
checkEqual(buf, orig, "Base64 dec.decode(src, dst) failed!");
}
}
}
Example 29
Project: restfiddle-master File: BasicAuthHandler.java View source code |
public void setBasicAuthWithBase64Encode(RfRequestDTO requestDTO, RequestBuilder requestBuilder) {
BasicAuthDTO basicAuthDTO = requestDTO.getBasicAuthDTO();
if (basicAuthDTO == null) {
return;
}
String userName = basicAuthDTO.getUsername();
String password = basicAuthDTO.getPassword();
if (userName == null || userName.isEmpty() || password == null || password.isEmpty()) {
return;
}
String authStr = userName + ":" + password;
String encodedAuth = (new BASE64Encoder()).encode(authStr.getBytes());
requestBuilder.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth);
}
Example 30
Project: spring-rest-server-master File: EncryptionUtil.java View source code |
public String encrypt(final String plainValue, final String password) throws IOException, GeneralSecurityException {
if (this.encryptionEnabled) {
final byte[] encryptedBytes = this.getEncryptionCipher(password).doFinal(plainValue.getBytes(ENCODING_CHARSET));
final String base64WithNewlines = new sun.misc.BASE64Encoder().encode(encryptedBytes);
return base64WithNewlines.replace(System.getProperty("line.separator"), "");
} else {
return plainValue;
}
}
Example 31
Project: stripes-cdi-master File: PasswordHasher.java View source code |
/** * Encrypts the password given to be stored in the database. * * @param password * @param salt * @return */ public String encrypt(String password, String salt) { try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.reset(); digest.update(base64ToBytes(salt)); byte[] enc = digest.digest(password.getBytes("UTF-8")); for (int i = 0; i < 100; i++) { digest.reset(); enc = digest.digest(enc); } BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(enc); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } }
Example 32
Project: albert-master File: JavaMailWithAttachment.java View source code |
/** * å?‘é€?邮件 * * @param subject * 邮件主题 * @param sendHtml * 邮件内容 * @param receiveUser * 收件人地å?€ * @param attachment * 附件 */ public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) { try { // å?‘件人 InternetAddress from = new InternetAddress(sender_username); message.setFrom(from); // 收件人 InternetAddress to = new InternetAddress(receiveUser); message.setRecipient(Message.RecipientType.TO, to); // 邮件主题 message.setSubject(subject); // å?‘multipart对象ä¸æ·»åŠ 邮件的å?„个部分内容,包括文本内容和附件 Multipart multipart = new MimeMultipart(); // æ·»åŠ é‚®ä»¶æ£æ–‡ BodyPart contentPart = new MimeBodyPart(); contentPart.setContent(sendHtml, "text/html;charset=UTF-8"); multipart.addBodyPart(contentPart); // æ·»åŠ é™„ä»¶çš„å†…å®¹ if (attachment != null) { BodyPart attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachment); attachmentBodyPart.setDataHandler(new DataHandler(source)); // 网上æµ?ä¼ çš„è§£å†³æ–‡ä»¶å??ä¹±ç ?的方法,其实用MimeUtility.encodeWordå°±å?¯ä»¥å¾ˆæ–¹ä¾¿çš„æ?žå®š // 这里很é‡?è¦?,通过下é?¢çš„Base64ç¼–ç ?的转æ?¢å?¯ä»¥ä¿?è¯?ä½ çš„ä¸æ–‡é™„ä»¶æ ‡é¢˜å??在å?‘é€?æ—¶ä¸?会å?˜æˆ?ä¹±ç ? //sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); //messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?="); //MimeUtility.encodeWordå?¯ä»¥é?¿å…?文件å??ä¹±ç ? attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName())); multipart.addBodyPart(attachmentBodyPart); } // å°†multipart对象放到messageä¸ message.setContent(multipart); // ä¿?å˜é‚®ä»¶ message.saveChanges(); transport = session.getTransport("smtp"); // smtp验è¯?ï¼Œå°±æ˜¯ä½ ç”¨æ?¥å?‘邮件的邮箱用户å??密ç ? // transport.connect(mailHost, sender_username, sender_password); transport.connect(host, port, sender_username, sender_password); // å?‘é€? transport.sendMessage(message, message.getAllRecipients()); System.out.println("send success!"); } catch (Exception e) { e.printStackTrace(); } finally { if (transport != null) { try { transport.close(); } catch (MessagingException e) { e.printStackTrace(); } } } }
Example 33
Project: ceres-master File: UrlHelper.java View source code |
private static void addProxyAuthorization(URLConnection urlConnection, ProxyConfig proxyConfig) { // from http://floatingsun.net/articles/java-proxy.html String s = proxyConfig.getUsername() + ':' + new String(proxyConfig.getPassword()); byte[] bytes = s.getBytes(); // todo - this encoder might not be available on Mac OS X!!! sun.misc.BASE64Encoder base64Encoder = new sun.misc.BASE64Encoder(); urlConnection.setRequestProperty("Proxy-Authorization", "Basic " + base64Encoder.encode(bytes)); }
Example 34
Project: dk-master File: MailNotifyServiceImpl.java View source code |
protected void sendContext(MimeMessage msg, NotifyDo message) throws MessagingException { // å?‘multipart对象ä¸æ·»åŠ 邮件的å?„个部分内容,包括文本内容和附件 Multipart multipart = new MimeMultipart(); // 设置邮件的文本内容 BodyPart contentPart = new MimeBodyPart(); contentPart.setText(message.MESSAGE_CONTEXT); multipart.addBodyPart(contentPart); // æ·»åŠ é™„ä»¶ BodyPart messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(message.getFilePath()); // æ·»åŠ é™„ä»¶çš„å†…å®¹ messageBodyPart.setDataHandler(new DataHandler(source)); // æ·»åŠ é™„ä»¶çš„æ ‡é¢˜ // 这里很é‡?è¦?,通过下é?¢çš„Base64ç¼–ç ?的转æ?¢å?¯ä»¥ä¿?è¯?ä½ çš„ä¸æ–‡é™„ä»¶æ ‡é¢˜å??在å?‘é€?æ—¶ä¸?会å?˜æˆ?ä¹±ç ? sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); messageBodyPart.setFileName("=?UTF-8?B?" + enc.encode((message.getFileName() + ".xls").getBytes()) + "?="); multipart.addBodyPart(messageBodyPart); msg.setContent(multipart); msg.saveChanges(); }
Example 35
Project: glassfish-main-master File: TestClient.java View source code |
private int invokeServlet(String url, String userPassword) throws Exception {
log("Invoking url = " + url + ", password = " + userPassword);
URL u = new URL(url);
String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
HttpURLConnection c1 = (HttpURLConnection) u.openConnection();
c1.setRequestProperty("Authorization", "Basic " + encoding);
int code = c1.getResponseCode();
InputStream is = c1.getInputStream();
BufferedReader input = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = input.readLine()) != null) {
log(line);
if (line.indexOf("So the RESULT OF EJB webservice IS") != -1)
found1 = true;
if (line.indexOf("[JBI-SecurityTest PrincipalSent=user PrincipalGot=user]") != -1)
found2 = true;
}
return code;
}
Example 36
Project: Netcarity---HGW-master File: WebCamClientComm.java View source code |
/**
* check if input 1 is pressed == 1 ring button
* @param port
* @return
*/
public int checkPortStatus(int port) {
try {
String curport = Integer.toString(port);
//reply with input1=1 o 0
URL url = new URL("http://" + ip + "/axis-cgi/io/input.cgi?check=" + curport.toString());
String userPassword = "<user>" + ":" + "<passwd>";
String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
URLConnection uc = url.openConnection();
uc.setRequestProperty("Authorization", "Basic " + encoding);
InputStream content = (InputStream) uc.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(content));
String str;
str = in.readLine();
if (str.contentEquals("input1=1")) {
//high
return 1;
} else if (str.contentEquals("input1=0")) {
//low
return 0;
}
in.close();
} catch (MalformedURLException ex) {
WebCamClientCommLogger.error(ex);
} catch (IOException ex) {
WebCamClientCommLogger.error(ex);
}
return -1;
}
Example 37
Project: Payara-master File: TestClient.java View source code |
private int invokeServlet(String url, String userPassword) throws Exception {
log("Invoking url = " + url + ", password = " + userPassword);
URL u = new URL(url);
String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
HttpURLConnection c1 = (HttpURLConnection) u.openConnection();
c1.setRequestProperty("Authorization", "Basic " + encoding);
int code = c1.getResponseCode();
InputStream is = c1.getInputStream();
BufferedReader input = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = input.readLine()) != null) {
log(line);
if (line.indexOf("So the RESULT OF EJB webservice IS") != -1)
found1 = true;
if (line.indexOf("[JBI-SecurityTest PrincipalSent=user PrincipalGot=user]") != -1)
found2 = true;
}
return code;
}
Example 38
Project: robombs-master File: TalkBack.java View source code |
public void run() { try { noTalkBack(); URL url = new URL("http://jpct.de/talkback/store.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); OutputStream out = conn.getOutputStream(); OutputStreamWriter wr = new OutputStreamWriter(out); Iterator<ImageWriter> itty = ImageIO.getImageWritersBySuffix("jpg"); if (itty.hasNext()) { ImageWriter iw = (ImageWriter) itty.next(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageWriteParam iwp = iw.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality(0.85f); ImageOutputStream ios = ImageIO.createImageOutputStream(bos); iw.setOutput(ios); iw.write(null, new IIOImage((RenderedImage) img, null, null), iwp); ios.close(); sun.misc.BASE64Encoder benc = new sun.misc.BASE64Encoder(); String id = System.currentTimeMillis() + "_" + (int) (Math.random() * 100000); wr.write("id=" + id); wr.write("&width=" + fb.getOutputWidth()); wr.write("&height=" + fb.getOutputHeight()); wr.write("&aa=" + fb.getSamplingMode()); wr.write("&version=" + Globals.GAME_VERSION); wr.write("&jpct=" + Config.getVersion()); wr.write("&java=" + URLEncoder.encode(System.getProperty("java.version"), "UTF-8")); wr.write("&vm=" + URLEncoder.encode(System.getProperty("java.vm.name"), "UTF-8")); wr.write("&vendor=" + URLEncoder.encode(System.getProperty("java.vm.vendor"), "UTF-8")); wr.write("&arch=" + URLEncoder.encode(System.getProperty("os.arch"), "UTF-8")); wr.write("&os=" + URLEncoder.encode(System.getProperty("os.name"), "UTF-8")); wr.write("&osversion=" + URLEncoder.encode(System.getProperty("os.version"), "UTF-8")); wr.write("&adapter=" + URLEncoder.encode(Globals.graphicsAdapter, "UTF-8")); wr.write("&shadows=" + URLEncoder.encode(Globals.shadowMode, "UTF-8")); wr.write("&cpus=" + Runtime.getRuntime().availableProcessors()); wr.write("&pic="); ByteArrayOutputStream sbo = new ByteArrayOutputStream(); benc.encodeBuffer(new ByteArrayInputStream(bos.toByteArray()), sbo); wr.write(URLEncoder.encode(new String(sbo.toByteArray(), "UTF-8"), "UTF-8")); wr.flush(); wr.close(); out.flush(); out.close(); char[] buffy = new char[1000]; StringBuffer html = new StringBuffer(); InputStream in = conn.getInputStream(); InputStreamReader reader = new InputStreamReader(in); int len = 0; do { len = reader.read(buffy, 0, buffy.length); if (len != -1) { html.append(buffy, 0, len); } } while (len != -1); reader.close(); in.close(); String res = html.toString(); if (res.startsWith("ok/")) { NetLogger.log("Talkback data transfered!"); } else { NetLogger.log("Talkback data not transfered!"); System.err.println(res); } } out.close(); } catch (Exception e) { NetLogger.log("Talkback data not transfered!"); e.printStackTrace(); } }
Example 39
Project: 10gen-m101j-master File: UserDAO.java View source code |
private String makePasswordHash(String password, String salt) { try { String saltedAndHashed = password + "," + salt; MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(saltedAndHashed.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); byte hashedBytes[] = (new String(digest.digest(), "UTF-8")).getBytes(); return encoder.encode(hashedBytes) + "," + salt; } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 is not available", e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 unavailable? Not a chance", e); } }
Example 40
Project: course-mongodb-M101J-master File: UserDAO.java View source code |
private String makePasswordHash(String password, String salt) { try { String saltedAndHashed = password + "," + salt; MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(saltedAndHashed.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); byte hashedBytes[] = (new String(digest.digest(), "UTF-8")).getBytes(); return encoder.encode(hashedBytes) + "," + salt; } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 is not available", e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 unavailable? Not a chance", e); } }
Example 41
Project: geoserver-2.0.x-master File: LoginTest.java View source code |
public String generateCookie(String username) throws Exception { SecretKeySpec key = new SecretKeySpec(secret.getBytes(), "SHA"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(key); mac.update(username.getBytes()); byte[] result = (mac.doFinal()); String blah = "0123456789abcdef"; String resultString = ""; for (int i = 0; i < result.length; i++) { int first = (result[i] >> 4) & 0x0f; int second = result[i] & 0x0f; resultString += Character.valueOf(blah.charAt(first)) + Character.valueOf(blah.charAt(second)).toString(); } BASE64Encoder be = new BASE64Encoder(); // System.out.println(resultString); return be.encode((username + "\0" + resultString).getBytes()); }
Example 42
Project: jsystem-master File: Encryptor.java View source code |
/**
* The method gets a String which its secret key is hard coded and encrypt it <br>
*
* @param str - String to encrypt
* @return encrypted String
* @throws Exception
*/
public static String encrypt(String str) throws Exception {
Cipher ecipher;
Cipher dcipher;
SecretKeySpec key = new SecretKeySpec(SECRET_KEY, "DES");
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return (new sun.misc.BASE64Encoder().encode(enc)) + ENCRYPTION_TERMINATING_STRING;
}
Example 43
Project: M101J-master File: UserDAO.java View source code |
private String makePasswordHash(String password, String salt) { try { String saltedAndHashed = password + "," + salt; MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(saltedAndHashed.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); byte hashedBytes[] = (new String(digest.digest(), "UTF-8")).getBytes(); return encoder.encode(hashedBytes) + "," + salt; } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 is not available", e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 unavailable? Not a chance", e); } }
Example 44
Project: mongoDB-course-M101J-master File: UserDAO.java View source code |
private String makePasswordHash(String password, String salt) { try { String saltedAndHashed = password + "," + salt; MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(saltedAndHashed.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); byte hashedBytes[] = (new String(digest.digest(), "UTF-8")).getBytes(); return encoder.encode(hashedBytes) + "," + salt; } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 is not available", e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 unavailable? Not a chance", e); } }
Example 45
Project: mongodb-m101j-training-master File: UserDAO.java View source code |
private String makePasswordHash(String password, String salt) { try { String saltedAndHashed = password + "," + salt; MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(saltedAndHashed.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); byte hashedBytes[] = (new String(digest.digest(), "UTF-8")).getBytes(); return encoder.encode(hashedBytes) + "," + salt; } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 is not available", e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 unavailable? Not a chance", e); } }
Example 46
Project: MongoUniversityProj-master File: UserDAO.java View source code |
private String makePasswordHash(String password, String salt) { try { String saltedAndHashed = password + "," + salt; MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(saltedAndHashed.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); byte hashedBytes[] = (new String(digest.digest(), "UTF-8")).getBytes(); return encoder.encode(hashedBytes) + "," + salt; } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 is not available", e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 unavailable? Not a chance", e); } }
Example 47
Project: My-Blog-master File: Tools.java View source code |
public static String enAes(String data, String key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
return new BASE64Encoder().encode(encryptedBytes);
}
Example 48
Project: openclouddb-master File: RainbowSecurityImpl.java View source code |
public String encrypt(String securityCode, String modulus, String privateExponent) { String encStr = null; try { if (securityCode != null) { BASE64Encoder enc = new BASE64Encoder(); PrivateKey privateKey = SecurityUtil.getInstance().getPrivateKey(modulus, privateExponent); byte[] encByte = SecurityUtil.getInstance().encrypt(privateKey, securityCode.getBytes()); encStr = enc.encode(encByte); } } catch (Exception ex) { ex.printStackTrace(); } return encStr; }
Example 49
Project: rainbow-master File: RainbowSecurityImpl.java View source code |
public String encrypt(String securityCode, String modulus, String privateExponent) { String encStr = null; try { if (securityCode != null) { BASE64Encoder enc = new BASE64Encoder(); PrivateKey privateKey = SecurityUtil.getInstance().getPrivateKey(modulus, privateExponent); byte[] encByte = SecurityUtil.getInstance().encrypt(privateKey, securityCode.getBytes()); encStr = enc.encode(encByte); } } catch (Exception ex) { ex.printStackTrace(); } return encStr; }
Example 50
Project: Breakbulk-master File: BuilderServlet.java View source code |
// *****************************************************
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
//Pull out the parameters.
String version = req.getParameter("version");
String cdn = req.getParameter("cdn");
String dependencies = req.getParameter("dependencies");
String optimize = req.getParameter("optimize");
String cacheFile = null;
String result = null;
boolean isCached = false;
Boolean isError = true;
//Validate parameters
if (!version.equals("1.3.2")) {
result = "invalid version: " + version;
}
if (!cdn.equals("google") && !cdn.equals("aol")) {
result = "invalide CDN type: " + cdn;
}
if (!optimize.equals("comments") && !optimize.equals("shrinksafe") && !optimize.equals("none") && !optimize.equals("shrinksafe.keepLines")) {
result = "invalid optimize type: " + optimize;
}
if (!dependencies.matches("^[\\w\\-\\,\\s\\.]+$")) {
result = "invalid dependency list: " + dependencies;
}
try {
//See if we already did the work.
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA");
} catch (NoSuchAlgorithmException e) {
result = e.getMessage();
}
if (result == null) {
md.update(dependencies.getBytes());
String digest = (new BASE64Encoder()).encode(md.digest()).replace('+', '~').replace('/', '_').replace('=', '_');
cacheFile = cachePath + "/" + version + "/" + cdn + "/" + digest + "/" + optimize + ".js";
File file = new File(cacheFile);
if (file.exists()) {
isCached = true;
isError = false;
}
}
//Generate the build.
if (result == null && !isCached) {
BuilderContextAction contextAction = new BuilderContextAction(builderPath, version, cdn, dependencies, optimize);
ContextFactory.getGlobal().call(contextAction);
Exception exception = contextAction.getException();
if (exception != null) {
result = exception.getMessage();
} else {
result = contextAction.getResult();
FileUtil.writeToFile(cacheFile, result, null, true);
isError = false;
}
}
} catch (Exception e) {
result = e.getMessage();
}
//Write out response.
res.setCharacterEncoding("utf-8");
if (isError) {
result = result.replaceAll("\\\"", "\\\"");
result = "<html><head><script type=\"text/javascript\">alert(\"" + result + "\");</script></head><body></body></html>";
PrintWriter writer = res.getWriter();
writer.append(result);
} else {
res.setHeader("Content-Type", "application/x-javascript");
res.setHeader("Content-disposition", "attachment; filename=dojo.js");
res.setHeader("Content-Encoding", "gzip");
//Read in the gzipped bytes of the cached file.
File file = new File(cacheFile);
BufferedInputStream in = new java.io.BufferedInputStream(new DataInputStream(new FileInputStream(file)));
OutputStream out = res.getOutputStream();
byte[] bytes = new byte[64000];
int bytesRead = 0;
while (bytesRead != -1) {
bytesRead = in.read(bytes);
if (bytesRead != -1) {
out.write(bytes, 0, bytesRead);
}
}
}
}
Example 51
Project: buckminster-master File: Utils.java View source code |
/**
* Creates a hash code for specified url, suitable for creating a folder in the cache structure.
*
* @param jnlp
* @return
* @throws JNLPException
*/
public static String createHash(URL jnlp) throws JNLPException {
MessageDigest md;
try {
//$NON-NLS-1$
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new JNLPException(e.getMessage(), Messages.getString("report_problem_to_distro_vendor"), BootstrapConstants.ERROR_CODE_JNLP_SAX_EXCEPTION, e);
}
return new BASE64Encoder().encode(md.digest(jnlp.toString().getBytes()));
}
Example 52
Project: constellio-master File: NtlmAuthenticationFilter.java View source code |
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
Enumeration<String> headerNames = httpRequest.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
System.out.println(headerName + "=" + httpRequest.getHeader(headerName));
}
String auth = httpRequest.getHeader("Authorization");
if (auth != null && auth.startsWith("NTLM ")) {
byte[] msg = Base64.decodeBase64(auth.substring(5));
if (msg[8] == 1) {
byte z = 0;
byte[] msg1 = { (byte) 'N', (byte) 'T', (byte) 'L', (byte) 'M', (byte) 'S', (byte) 'S', (byte) 'P', z, (byte) 2, z, z, z, z, z, z, z, (byte) 40, z, z, z, (byte) 1, (byte) 130, z, z, z, (byte) 2, (byte) 2, (byte) 2, z, z, z, z, z, z, z, z, z, z, z, z };
httpResponse.setHeader("WWW-Authenticate", "NTLM " + new sun.misc.BASE64Encoder().encodeBuffer(msg1));
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
httpResponse.setContentLength(0);
httpResponse.flushBuffer();
} else if (msg[8] == 3) {
// Did Authentication Succeed?
Type3Message type3 = new Type3Message(msg);
String user = type3.getUser();
String remoteHost = type3.getWorkstation();
String domain = type3.getDomain();
System.out.println("Login user:" + user + " remoteHost:" + remoteHost + " domain:" + type3.getDomain());
try (PrintWriter out = httpResponse.getWriter()) {
//TODO Checking for password in NTLM is not simple...
if (USER.equals(user) && DOMAIN.equalsIgnoreCase(domain)) {
chain.doFilter(request, response);
} else {
httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
}
}
} else {
// The Type 2 message is sent by the server to the client in response to the client's Type 1 message.
httpResponse.setHeader("WWW-Authenticate", "NTLM");
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
httpResponse.setContentLength(0);
httpResponse.flushBuffer();
}
}
Example 53
Project: credenjava-master File: DesEncrypter.java View source code |
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
} catch (java.io.IOException e) {
}
return null;
}
Example 54
Project: crezoo-master File: StringEncrypter.java View source code |
public String encrypt(String unencryptedString) throws EncryptionException { if (unencryptedString == null || unencryptedString.trim().length() == 0) throw new IllegalArgumentException("unencrypted string was null or empty"); try { SecretKey key = keyFactory.generateSecret(keySpec); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] cleartext = unencryptedString.getBytes(UNICODE_FORMAT); byte[] ciphertext = cipher.doFinal(cleartext); BASE64Encoder base64encoder = new BASE64Encoder(); return base64encoder.encode(ciphertext); } catch (Exception e) { throw new EncryptionException(e); } }
Example 55
Project: cyrille-leclerc-master File: UrlTest.java View source code |
@Test
public void testBasicAuth() throws Exception {
URL url = new URL("http://www-devsf:8081/acegi-security-sfrcas-demo/protected/parameters.jsp");
URLConnection connection = url.openConnection();
String username = "osm";
String password = "1111";
String loginPassword = username + ":" + password;
connection.setRequestProperty("Authorization", "Basic " + new sun.misc.BASE64Encoder().encode(loginPassword.getBytes()));
connection.connect();
dumpConnection(connection);
}
Example 56
Project: ignite-master File: GridRestProtocolAdapter.java View source code |
/** * Authenticates current request. * <p> * Token consists of 2 parts separated by semicolon: * <ol> * <li>Timestamp (time in milliseconds)</li> * <li>Base64 encoded SHA1 hash of {1}:{secretKey}</li> * </ol> * * @param tok Authentication token. * @return {@code true} if authentication info provided in request is correct. */ protected boolean authenticate(@Nullable String tok) { if (F.isEmpty(secretKey)) return true; if (F.isEmpty(tok)) return false; StringTokenizer st = new StringTokenizer(tok, ":"); if (st.countTokens() != 2) return false; String ts = st.nextToken(); String hash = st.nextToken(); String s = ts + ':' + secretKey; try { MessageDigest md = MessageDigest.getInstance("SHA-1"); BASE64Encoder enc = new BASE64Encoder(); md.update(s.getBytes(UTF_8)); String compHash = enc.encode(md.digest()); return hash.equalsIgnoreCase(compHash); } catch (NoSuchAlgorithmException e) { U.error(log, "Failed to check authentication signature.", e); } return false; }
Example 57
Project: infoglue-master File: DesEncryptionHelper.java View source code |
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new String(Base64.encodeBase64(enc), "ASCII");
//return new sun.misc.BASE64Encoder().encode(enc);
} catch (Exception ex) {
logger.error("Error when encrypting value. Message: " + ex.getMessage());
logger.warn("Error when encrypting value.", ex);
}
return null;
}
Example 58
Project: invoicing-master File: DESUtils.java View source code |
/** * 对str进行DESåŠ å¯† * * @param str * @return */ public static String getEncryptString(String str) { BASE64Encoder base64en = new BASE64Encoder(); try { byte[] strBytes = str.getBytes("UTF8"); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] encryptStrBytes = cipher.doFinal(strBytes); return base64en.encode(encryptStrBytes); } catch (Exception e) { throw new RuntimeException(e); } }
Example 59
Project: izpack-with-ips-master File: PasswordEncryptionValidator.java View source code |
public String encryptString(String string) throws Exception {
String result = null;
try {
byte[] cryptedbytes = null;
cryptedbytes = encryptCipher.doFinal(string.getBytes("UTF-8"));
result = (new BASE64Encoder()).encode(cryptedbytes);
} catch (Exception e) {
Debug.trace("Error encrypting string: " + e.getMessage());
throw e;
}
return result;
}
Example 60
Project: knox-master File: SecureQueryDecodeProcessorTest.java View source code |
@Test public void testSimpleQueryDecode() throws Exception { UrlRewriteEnvironment environment = new UrlRewriteEnvironment() { @Override public URL getResource(String name) throws IOException { return null; } @Override public <T> T getAttribute(String name) { return null; } @Override public List<String> resolve(String name) { return null; } }; BASE64Encoder encoder = new BASE64Encoder(); String encQuery = encoder.encode("test-query".getBytes("utf-8")); encQuery = encQuery.replaceAll("\\=", ""); String inString = "http://host:0/root/path?_=" + encQuery; Template inTemplate = Parser.parseLiteral(inString); UrlRewriteContext context = EasyMock.createNiceMock(UrlRewriteContext.class); EasyMock.expect(context.getCurrentUrl()).andReturn(inTemplate); Capture<Template> outTemplate = new Capture<Template>(); context.setCurrentUrl(EasyMock.capture(outTemplate)); EasyMock.replay(context); SecureQueryDecodeDescriptor descriptor = new SecureQueryDecodeDescriptor(); SecureQueryDecodeProcessor processor = new SecureQueryDecodeProcessor(); processor.initialize(environment, descriptor); processor.process(context); String outActual = outTemplate.getValue().toString(); assertThat(outActual, is("http://host:0/root/path?test-query")); }
Example 61
Project: l1j-tw-99nets-master File: Logins.java View source code |
public static boolean loginValid(String account, String password, String ip, String host) throws IOException {
boolean flag1 = false;
_log.info("Connect from : " + account);
Connection con = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
byte abyte1[];
byte abyte2[];
MessageDigest messagedigest = MessageDigest.getInstance("SHA");
byte abyte0[] = password.getBytes("UTF-8");
abyte1 = messagedigest.digest(abyte0);
abyte2 = null;
con = L1DatabaseFactory.getInstance().getConnection();
pstm = con.prepareStatement("SELECT password FROM accounts WHERE login=? LIMIT 1");
pstm.setString(1, account);
rs = pstm.executeQuery();
if (rs.next()) {
abyte2 = new BASE64Decoder().decodeBuffer(rs.getString(1));
_log.fine("account exists");
}
SQLUtil.close(rs);
SQLUtil.close(pstm);
SQLUtil.close(con);
if (abyte2 == null) {
if (Config.AUTO_CREATE_ACCOUNTS) {
con = L1DatabaseFactory.getInstance().getConnection();
pstm = con.prepareStatement("INSERT INTO accounts SET login=?,password=?,lastactive=?,access_level=?,ip=?,host=?");
pstm.setString(1, account);
pstm.setString(2, new BASE64Encoder().encode(abyte1));
pstm.setLong(3, 0L);
pstm.setInt(4, 0);
pstm.setString(5, ip);
pstm.setString(6, host);
pstm.execute();
_log.info("created new account for " + account);
return true;
} else {
_log.warning("account missing for user " + account);
return false;
}
}
try {
flag1 = true;
int i = 0;
do {
if (i >= abyte2.length) {
break;
}
if (abyte1[i] != abyte2[i]) {
flag1 = false;
break;
}
i++;
} while (true);
} catch (Exception e) {
_log.warning("could not check password:" + e);
flag1 = false;
}
} catch (SQLException e) {
_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
} catch (NoSuchAlgorithmException e) {
_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
} catch (UnsupportedEncodingException e) {
_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
} finally {
SQLUtil.close(rs);
SQLUtil.close(pstm);
SQLUtil.close(con);
}
return flag1;
}
Example 62
Project: mediation-master File: MediationSecurityAdminService.java View source code |
/** * Operation to do the encryption ops by invoking secure vault api * * @param plainTextPass * @return * @throws AxisFault */ public String doEncrypt(String plainTextPass) throws AxisFault { CipherInitializer ciperInitializer = CipherInitializer.getInstance(); byte[] plainTextPassByte = plainTextPass.getBytes(); try { Cipher cipher = ciperInitializer.getEncryptionProvider(); if (cipher == null) { log.error("Either Configuration properties can not be loaded or No secret" + " repositories have been configured please check PRODUCT_HOME/conf/security " + " refer links related to configure WSO2 Secure vault"); handleException(log, "Failed to load security key store information ," + "Configure secret-conf.properties properly by referring to " + "\"Carbon Secure Vault Implementation\" in WSO2 Documentation", null); } byte[] encryptedPassword = cipher.doFinal(plainTextPassByte); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(encryptedPassword); } catch (IllegalBlockSizeExceptionBadPaddingException | e) { handleException(log, "Error encrypting password ", e); } return null; }
Example 63
Project: NettyGameServer-master File: DesEncrypter.java View source code |
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (javax.crypto.BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (java.io.IOException e) {
}
return null;
}
Example 64
Project: OpenNotification-master File: OpenNMSSender.java View source code |
public void handleResponse(Notification notification, Member responder, String response, String text) {
if (notification.getStatus() == Notification.EXPIRED) {
BrokerFactory.getLoggingBroker().logInfo(responder + " tried to confirm an expired notification with uuid " + notification.getUuid());
return;
}
if (response.equalsIgnoreCase("acknowledge")) {
try {
URL url = new URL(this.url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("action", "1");
//String encoding = new sun.misc.BASE64Encoder().encode ((username+":"+password).getBytes());
String encoding = Base64.encode((username + ":" + password));
conn.setRequestProperty("Authorization", "Basic " + encoding);
PrintStream out = new PrintStream(conn.getOutputStream());
out.print("action=1&event=" + event);
InputStream in = conn.getInputStream();
} catch (MalformedURLException e) {
BrokerFactory.getLoggingBroker().logError(e);
} catch (IOException e) {
}
}
}
Example 65
Project: rapid-framework-master File: JdbcSessionStore.java View source code |
public static String encode(Map<String, ?> sessionData) {
try {
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(byteOutput);
oos.writeObject(sessionData);
byte[] bytes = byteOutput.toByteArray();
return new BASE64Encoder().encode(bytes);
} catch (IOException e) {
throw new RuntimeException("encode session data error", e);
}
}
Example 66
Project: sakuli-master File: ScreenshotDivConverter.java View source code |
protected String extractScreenshotAsBase64(Throwable exception) {
if (exception instanceof SakuliExceptionWithScreenshot) {
Path screenshotPath = ((SakuliExceptionWithScreenshot) exception).getScreenshot();
if (screenshotPath != null) {
try {
byte[] binaryScreenshot = Files.readAllBytes(screenshotPath);
String base64String = new BASE64Encoder().encode(binaryScreenshot);
for (String newLine : Arrays.asList("\n", "\r")) {
base64String = StringUtils.remove(base64String, newLine);
}
return base64String;
} catch (IOException e) {
exceptionHandler.handleException(new SakuliForwarderException(e, String.format("error during the BASE64 encoding of the screenshot '%s'", screenshotPath.toString())));
}
}
}
return null;
}
Example 67
Project: streamflow-core-master File: Strings.java View source code |
public static String hashString(String string) {
try {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(string.getBytes("UTF-8"));
byte raw[] = md.digest();
String hash = (new BASE64Encoder()).encode(raw);
return hash;
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("No SHA algorithm founde", e);
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
Example 68
Project: Thngm-master File: PasswordUtil.java View source code |
public static String encrypt(String password, Key key) { try { //TODO find out why certain jars on the cp break this Cipher cipher = Cipher.getInstance(CIPHER_TYPE); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] outputBytes = cipher.doFinal(password.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); String base64 = encoder.encode(outputBytes); return base64; } catch (Exception e) { throw new RuntimeException("Failed to encrypt password", e); } }
Example 69
Project: wso2-synapse-master File: EncodingHelper.java View source code |
/**
* Encodes the provided ByteArrayOutputStream using the specified encoding type.
*
* @param baos The ByteArrayOutputStream to encode
* @param encodingType The encoding to use
* @return The encoded ByteArrayOutputStream as a String
*/
public static byte[] encode(ByteArrayOutputStream baos, EncodingType encodingType) {
switch(encodingType) {
case BASE64:
if (log.isDebugEnabled()) {
log.debug("base64 encoding on output ");
}
return new BASE64Encoder().encode(baos.toByteArray()).getBytes();
case BIGINTEGER16:
if (log.isDebugEnabled()) {
log.debug("BigInteger 16 encoding on output ");
}
return new BigInteger(baos.toByteArray()).toByteArray();
default:
throw new IllegalArgumentException("Unsupported encoding type");
}
}
Example 70
Project: java-utils-master File: EmailUtil.java View source code |
/** * å?‘é€?邮件 * * @param subject 邮件主题 * @param sendHtml 邮件内容 * @param receiveUser 收件人地å?€ * @param attachment 附件 */ public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) { try { // å?‘件人 InternetAddress from = new InternetAddress(sender_username); message.setFrom(from); // 收件人 InternetAddress to = new InternetAddress(receiveUser); message.setRecipient(Message.RecipientType.TO, to); // 邮件主题 message.setSubject(subject); // å?‘multipart对象ä¸æ·»åŠ 邮件的å?„个部分内容,包括文本内容和附件 Multipart multipart = new MimeMultipart(); // æ·»åŠ é‚®ä»¶æ£æ–‡ BodyPart contentPart = new MimeBodyPart(); contentPart.setContent(sendHtml, "text/html;charset=UTF-8"); multipart.addBodyPart(contentPart); // æ·»åŠ é™„ä»¶çš„å†…å®¹ if (attachment != null) { BodyPart attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachment); attachmentBodyPart.setDataHandler(new DataHandler(source)); // 网上æµ?ä¼ çš„è§£å†³æ–‡ä»¶å??ä¹±ç ?的方法,其实用MimeUtility.encodeWordå°±å?¯ä»¥å¾ˆæ–¹ä¾¿çš„æ?žå®š // 这里很é‡?è¦?,通过下é?¢çš„Base64ç¼–ç ?的转æ?¢å?¯ä»¥ä¿?è¯?ä½ çš„ä¸æ–‡é™„ä»¶æ ‡é¢˜å??在å?‘é€?æ—¶ä¸?会å?˜æˆ?ä¹±ç ? //sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); //messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?="); //MimeUtility.encodeWordå?¯ä»¥é?¿å…?文件å??ä¹±ç ? attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName())); multipart.addBodyPart(attachmentBodyPart); } // å°†multipart对象放到messageä¸ message.setContent(multipart); // ä¿?å˜é‚®ä»¶ message.saveChanges(); transport = session.getTransport("smtp"); // smtp验è¯?ï¼Œå°±æ˜¯ä½ ç”¨æ?¥å?‘邮件的邮箱用户å??密ç ? transport.connect(mailHost, port, sender_username, sender_password); // å?‘é€? transport.sendMessage(message, message.getAllRecipients()); System.out.println("send success!"); } catch (Exception e) { e.printStackTrace(); } finally { if (transport != null) { try { transport.close(); } catch (MessagingException e) { e.printStackTrace(); } } } }
Example 71
Project: OPS-master File: EmailUtil.java View source code |
/** * å?‘é€?邮件 * * @param subject 邮件主题 * @param sendHtml 邮件内容 * @param receiveUser 收件人地å?€ * @param attachment 附件 */ public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) { try { // å?‘件人 InternetAddress from = new InternetAddress(sender_username); message.setFrom(from); // 收件人 InternetAddress to = new InternetAddress(receiveUser); message.setRecipient(Message.RecipientType.TO, to); // 邮件主题 message.setSubject(subject); // å?‘multipart对象ä¸æ·»åŠ 邮件的å?„个部分内容,包括文本内容和附件 Multipart multipart = new MimeMultipart(); // æ·»åŠ é‚®ä»¶æ£æ–‡ BodyPart contentPart = new MimeBodyPart(); contentPart.setContent(sendHtml, "text/html;charset=UTF-8"); multipart.addBodyPart(contentPart); // æ·»åŠ é™„ä»¶çš„å†…å®¹ if (attachment != null) { BodyPart attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachment); attachmentBodyPart.setDataHandler(new DataHandler(source)); // 网上æµ?ä¼ çš„è§£å†³æ–‡ä»¶å??ä¹±ç ?的方法,其实用MimeUtility.encodeWordå°±å?¯ä»¥å¾ˆæ–¹ä¾¿çš„æ?žå®š // 这里很é‡?è¦?,通过下é?¢çš„Base64ç¼–ç ?的转æ?¢å?¯ä»¥ä¿?è¯?ä½ çš„ä¸æ–‡é™„ä»¶æ ‡é¢˜å??在å?‘é€?æ—¶ä¸?会å?˜æˆ?ä¹±ç ? //sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); //messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?="); //MimeUtility.encodeWordå?¯ä»¥é?¿å…?文件å??ä¹±ç ? attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName())); multipart.addBodyPart(attachmentBodyPart); } // å°†multipart对象放到messageä¸ message.setContent(multipart); // ä¿?å˜é‚®ä»¶ message.saveChanges(); transport = session.getTransport("smtp"); // smtp验è¯?ï¼Œå°±æ˜¯ä½ ç”¨æ?¥å?‘邮件的邮箱用户å??密ç ? transport.connect(mailHost, port, sender_username, sender_password); // å?‘é€? transport.sendMessage(message, message.getAllRecipients()); System.out.println("send success!"); } catch (Exception e) { e.printStackTrace(); } finally { if (transport != null) { try { transport.close(); } catch (MessagingException e) { e.printStackTrace(); } } } }
Example 72
Project: plugins-sdk-6.2-master File: Security.java View source code |
/**
* Creates the secure file name.
*
* @return the string
*/
public static String createSecureFileName() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
long msec = System.currentTimeMillis();
String time = msec + "";
ReadWriteDES.encode(time.getBytes(), out, "11091980");
String s = new BASE64Encoder().encode(out.toByteArray());
// replace bad characters!
s = s.replace('/', 'a');
s = s.replace('\\', 'b');
s = s.replace('\'', 'n');
s = s.replace('+', 'm');
s = s.replace('-', 'r');
s = s.replace('#', 't');
s = s.replace('(', 'k');
s = s.replace(')', 'l');
s = s.replace('.', 'i');
s = s.replace(',', 'n');
s = s.replace('_', 'e');
s = s.replace('"', 'v');
s = s.replace('=', 'x');
return s;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Example 73
Project: upshot-smash-uploader-master File: UpConnection.java View source code |
/**
* Post request to setted up host
* it send the file given, with all its informations
* @param f The file that will be sent
*
*/
private String sendData(ImageFile imf) {
String answer = "";
if (logged & ready) {
try {
connection.setRequestMethod("POST");
osr = new OutputStreamWriter(connection.getOutputStream());
osr.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
/*convert the file to 64base format*/
FileInputStream fis = new FileInputStream(imf.getFile());
byte[] buffer = new byte[(int) imf.getFile().length()];
fis.read(buffer);
fis.close();
//Base64.encode(buffer);
String encode = new sun.misc.BASE64Encoder().encode(buffer);
/*Then create the xml file to send, with encoded file inside*/
osr.write("<upshot>");
osr.write("<title>" + imf.getTitle() + "</title>");
osr.write("<file_name>" + imf.getFile().getName() + "</file_name>");
osr.write("<size>" + imf.getFile().length() + "</size>");
osr.write("<javafile>" + encode + "</javafile>");
osr.write("</upshot>");
osr.flush();
osr.close();
/*You have to read the response of the host to make the changes happen*/
isr = new InputStreamReader(connection.getInputStream());
int c;
c = isr.read();
while (c != -1) {
answer += (char) c;
c = isr.read();
}
isr.close();
} catch (IOException ioe) {
JOptionPane.showMessageDialog(Smash.getFrames()[0], "UpConnection.sendData() : " + ioe.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
} finally {
connection.disconnect();
}
}
return answer;
}
Example 74
Project: xwiki-clams-core-master File: UploadToWiki.java View source code |
private void pullResource(String encoding, boolean verify) throws Exception {
HttpURLConnection conn;
URL readURL = new URL(uploadTo + "/xwiki/bin/view/" + space + "/" + name + "?xpage=xml&language=" + language);
conn = (HttpURLConnection) readURL.openConnection();
if (conn instanceof HttpsURLConnection) {
SSLSocketFactory factory = disableSSLValidation();
((HttpsURLConnection) conn).setSSLSocketFactory(factory);
}
conn.setUseCaches(false);
//String encoding = new sun.misc.BASE64Encoder().encode((userName + ":" + password).getBytes());
conn.setRequestProperty("Authorization", "Basic " + encoding);
System.out.println("-- Downloading: " + conn.getResponseCode() + " " + conn.getResponseMessage());
final StringBuilder contentB = new StringBuilder(), updateDate = new StringBuilder(), version = new StringBuilder();
SAXParserFactory.newInstance().newSAXParser().parse(conn.getInputStream(), new DefaultHandler() {
boolean inContent = false, incontentUpdateDate = false, inVersion = false;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (UploadToWiki.this.fieldName.equals(qName))
inContent = true;
if ("contentUpdateDate".equals(qName))
incontentUpdateDate = true;
if ("version".equals(qName))
inVersion = true;
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (UploadToWiki.this.fieldName.equals(qName))
inContent = false;
if ("contentUpdateDate".equals(qName))
incontentUpdateDate = false;
if ("version".equals(qName))
inVersion = false;
}
public void characters(char[] ch, int start, int length) throws SAXException {
if (inContent)
contentB.append(ch, start, length);
if (incontentUpdateDate)
updateDate.append(ch, start, length);
if (inVersion)
version.append(ch, start, length);
}
});
String date = "-";
if (updateDate != null && updateDate.length() > 0)
date = new Date(Long.parseLong(updateDate.toString())).toString();
System.out.println("-- Version " + version + ", modification date: " + date);
if (verify) {
boolean verified = contentB.toString().equals(fileContents);
System.out.println("-- Content equals? " + verified);
if (!verified) {
File f = new File("/tmp/upload-failed-read-from-server");
Writer o = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
o.write(contentB.toString());
o.flush();
o.close();
System.out.println("-- Please compare \n " + f + " with \n " + file);
System.exit(1);
}
int p = 0;
// while((p=conn.getInputStream().read())!=-1) System.out.print((char) p);
}
}
Example 75
Project: blade-master File: Tools.java View source code |
public static String enAes(String data, String key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
return new BASE64Encoder().encode(encryptedBytes);
}
Example 76
Project: bpm-console-master File: HTTP.java View source code |
public static String post(String urlString, InputStream inputStream) throws Exception {
String userPassword = "admin:admin";
String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
HttpURLConnection conn = null;
BufferedReader br = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
InputStream is = null;
OutputStream os = null;
boolean ret = false;
String StrMessage = "";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";
try {
//------------------ CLIENT REQUEST
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "Basic " + encoding);
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"upload\";" + " filename=\"" + UUID.randomUUID().toString() + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = inputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = inputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = inputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = inputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
inputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
throw ex;
} catch (IOException ioe) {
throw ioe;
}
//------------------ read the SERVER RESPONSE
StringBuffer sb = new StringBuffer();
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
sb.append(str).append("");
}
inStream.close();
} catch (IOException ioex) {
System.out.println("From (ServerResponse): " + ioex);
}
return sb.toString();
}
Example 77
Project: cambodia-master File: DES.java View source code |
/** * åŠ å¯†String明文输入,String密文输出 * * @param strMing * @return */ public String getEncString(String strMing) { byte[] byteMi = null; byte[] byteMing = null; String strMi = ""; BASE64Encoder base64en = new BASE64Encoder(); try { byteMing = strMing.getBytes("UTF8"); byteMi = getEncCode(byteMing); strMi = base64en.encode(byteMi); } catch (Exception e) { e.printStackTrace(); } finally { base64en = null; byteMing = null; byteMi = null; } return strMi; }
Example 78
Project: ComplexRapidMiner-master File: CipherTools.java View source code |
public static String encrypt(String text) throws CipherException { Key key = null; try { key = KeyGeneratorTool.getUserKey(); } catch (IOException e) { throw new CipherException("Cannot retrieve key, probably no one was created: " + e.getMessage()); } try { Cipher cipher = Cipher.getInstance(CIPHER_TYPE); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] outputBytes = cipher.doFinal(text.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); String base64 = encoder.encode(outputBytes); return base64; } catch (NoSuchAlgorithmException e) { throw new CipherException("Failed to encrypt text: " + e.getMessage()); } catch (NoSuchPaddingException e) { throw new CipherException("Failed to encrypt text: " + e.getMessage()); } catch (InvalidKeyException e) { throw new CipherException("Failed to encrypt text: " + e.getMessage()); } catch (IllegalBlockSizeException e) { throw new CipherException("Failed to encrypt text: " + e.getMessage()); } catch (BadPaddingException e) { throw new CipherException("Failed to encrypt text: " + e.getMessage()); } }
Example 79
Project: Cynthia-master File: ImageManager.java View source code |
/** * @description:convert the image file to base64 string * @date:2014-5-6 上å?ˆ9:55:58 * @version:v1.0 * @param imgInputStream * @return */ public static String getImageStr(InputStream imgInputStream) { byte[] data = null; // 读å?–图片å—节数组 try { data = new byte[imgInputStream.available()]; imgInputStream.read(data); imgInputStream.close(); } catch (IOException e) { e.printStackTrace(); } // 对å—节数组Base64ç¼–ç ? BASE64Encoder encoder = new BASE64Encoder(); // 返回Base64ç¼–ç ?过的å—节数组å—符串 return encoder.encode(data); }
Example 80
Project: deegree2-desktop-master File: Encryption.java View source code |
/**
* Encrpyts text
*
* @param textToEncrypt
* @return encrypted text
*/
public static String encrypt(String textToEncrypt, String ciph, String passFilename) {
try {
Cipher cipher = Cipher.getInstance(ciph);
Key key = loadKey(ciph, passFilename);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encrypted = cipher.doFinal(textToEncrypt.getBytes("UTF-8"));
return new BASE64Encoder().encode(encrypted);
} catch (Exception e) {
LOG.logError("Could not encrypt, returning original text:" + e.getMessage());
return textToEncrypt;
}
}
Example 81
Project: DKIM-for-JavaMail-master File: DKIMUtil.java View source code |
protected static String base64Encode(byte[] b) { BASE64Encoder base64Enc = new BASE64Encoder(); String encoded = base64Enc.encode(b); // remove unnecessary linefeeds after 76 characters // Linux+Win encoded = encoded.replace("\n", ""); // Win --> FSTODO: select Encoder without line termination return encoded.replace("\r", ""); }
Example 82
Project: Duke-master File: SparqlClient.java View source code |
private static InputSource getResponse(String url, String username, String password) {
try {
URL urlobj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlobj.openConnection();
// Basic Authentication
if (username != null && password != null) {
byte[] buf = (username + ":" + password).getBytes("utf-8");
String encoding = new sun.misc.BASE64Encoder().encode(buf);
conn.setRequestProperty("Authorization", "Basic " + encoding);
}
conn.setRequestProperty("Accept", "application/sparql-results+xml");
return new InputSource(conn.getInputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Example 83
Project: flower-platform-3-master File: Util.java View source code |
/**
* Encrypts the given <code>text</code> using the SHA mechanism.
*
*/
public static String encrypt(String text) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
try {
md.update(text.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
byte raw[] = md.digest();
String hash = (new BASE64Encoder()).encode(raw);
return hash;
}
Example 84
Project: gsearch-master File: FgsTestCase.java View source code |
protected static StringBuffer doRESTOp(String urlString) throws Exception {
StringBuffer result = new StringBuffer();
String restUrl = urlString;
int p = restUrl.indexOf("://");
if (p < 0)
restUrl = System.getProperty("fedoragsearch.protocol") + "://" + System.getProperty("fedoragsearch.hostport") + "/" + System.getProperty("fedoragsearch.path") + restUrl;
URL url = null;
url = new URL(restUrl);
URLConnection conn = null;
conn = url.openConnection();
conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode((System.getProperty("fedoragsearch.fgsUserName") + ":" + System.getProperty("fedoragsearch.fgsPassword")).getBytes()));
conn.connect();
content = null;
content = conn.getContent();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) content));
while ((line = br.readLine()) != null) result.append(line);
// throw new Exception(result.toString());
return result;
}
Example 85
Project: open-wechat-sdk-master File: Encrypt.java View source code |
// åŠ å¯†String明文输入,String密文输出 @SuppressWarnings("restriction") public void setEncString(String strMing) { BASE64Encoder base64en = new BASE64Encoder(); try { this.byteMing = strMing.getBytes("UTF8"); this.byteMi = this.getEncCode(this.byteMing); this.strMi = base64en.encode(this.byteMi); } catch (Exception e) { e.printStackTrace(); } finally { this.byteMing = null; this.byteMi = null; } }
Example 86
Project: org.opensixen.server.zkwebui-master File: BrowserToken.java View source code |
private static String getPasswordHash(MSession session, MUser user) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("SHA-512"); BASE64Encoder encoder = new BASE64Encoder(); digest.reset(); if (session.getWebSession() != null) digest.update(session.getWebSession().getBytes("UTF-8")); String password = null; if (MSystem.isZKRememberPasswordAllowed()) password = user.getPassword(); else password = new String(""); byte[] input = digest.digest(password.getBytes("UTF-8")); String hash = encoder.encode(input); hash = URLEncoder.encode(hash, "UTF-8"); return hash; }
Example 87
Project: rapidminer-5-master File: CipherTools.java View source code |
public static String encrypt(String text, Key key) throws CipherException { try { Cipher cipher = Cipher.getInstance(CIPHER_TYPE); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] outputBytes = cipher.doFinal(text.getBytes()); //BASE64Encoder encoder = new BASE64Encoder(); //String base64 = encoder.encode(outputBytes); String base64 = Base64.encodeBytes(outputBytes); return base64; } catch (NoSuchAlgorithmException e) { throw new CipherException("Failed to encrypt text: " + e.getMessage()); } catch (NoSuchPaddingException e) { throw new CipherException("Failed to encrypt text: " + e.getMessage()); } catch (InvalidKeyException e) { throw new CipherException("Failed to encrypt text: " + e.getMessage()); } catch (IllegalBlockSizeException e) { throw new CipherException("Failed to encrypt text: " + e.getMessage()); } catch (BadPaddingException e) { throw new CipherException("Failed to encrypt text: " + e.getMessage()); } }
Example 88
Project: rapidminer-vega-master File: CipherTools.java View source code |
public static String encrypt(String text, Key key) throws CipherException { try { Cipher cipher = Cipher.getInstance(CIPHER_TYPE); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] outputBytes = cipher.doFinal(text.getBytes()); //BASE64Encoder encoder = new BASE64Encoder(); //String base64 = encoder.encode(outputBytes); String base64 = Base64.encodeBytes(outputBytes); return base64; } catch (NoSuchAlgorithmException e) { throw new CipherException("Failed to encrypt text: " + e.getMessage()); } catch (NoSuchPaddingException e) { throw new CipherException("Failed to encrypt text: " + e.getMessage()); } catch (InvalidKeyException e) { throw new CipherException("Failed to encrypt text: " + e.getMessage()); } catch (IllegalBlockSizeException e) { throw new CipherException("Failed to encrypt text: " + e.getMessage()); } catch (BadPaddingException e) { throw new CipherException("Failed to encrypt text: " + e.getMessage()); } }
Example 89
Project: riena-master File: Base64Test.java View source code |
public void testRegression() throws IOException {
final String encodeBASE64 = new BASE64Encoder().encode(DECODED2.getBytes());
final String encodeBase64 = new String(Base64.encode(DECODED2.getBytes()));
assertEquals(encodeBASE64, encodeBase64);
final String decodeBASE64 = new String(new BASE64Decoder().decodeBuffer(encodeBASE64));
final String decodeBase64 = new String(Base64.decode(encodeBase64.getBytes()));
assertEquals(decodeBASE64, decodeBase64);
}
Example 90
Project: selenium-client-factory-master File: SeleniumImpl.java View source code |
private InputStream openWithAuth(URL url) throws IOException { URLConnection con = url.openConnection(); //Handle long strings encoded using BASE64Encoder - see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6947917 BASE64Encoder encoder = new BASE64Encoder() { @Override protected int bytesPerLine() { return 9999; } }; String encodedAuthorization = encoder.encode((credential.getUsername() + ":" + credential.getKey()).getBytes()); con.setRequestProperty("Authorization", "Basic " + encodedAuthorization); return con.getInputStream(); }
Example 91
Project: web-sso-master File: KnightRSASecurityUtil.java View source code |
/** * åŠ å¯†æ•°æ?®æº? * @param source * @return */ public static String encrypt(String source) { generateKeyPair(); Key publicKey = null; ObjectInputStream inputStream = null; try { inputStream = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE)); publicKey = (Key) inputStream.readObject(); } catch (Exception e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } try { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] bytes = source.getBytes(); //æ‰§è¡ŒåŠ å¯†ç®—æ³• byte[] encodebyte = cipher.doFinal(bytes); BASE64Encoder encoder = new BASE64Encoder(); //对密钥继ç»base64å¯¹ç§°åŠ å¯†è¿”å›ž return encoder.encode(encodebyte); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; }
Example 92
Project: yacy_search_server-master File: Base64Order.java View source code |
public static void main(final String[] s) { // java -classpath classes de.anomic.kelondro.kelondroBase64Order final Base64Order b64 = new Base64Order(true, true); if (s.length == 0) { System.out.println("usage: -[ec|dc|es|ds|clcn] <arg>"); System.exit(0); } if ("-ec".equals(s[0])) { // generate a b64 encoding from a given cardinal System.out.println(b64.encodeLongSB(Long.parseLong(s[1]), 4)); } if ("-dc".equals(s[0])) { // generate a b64 decoding from a given cardinal System.out.println(b64.decodeLong(s[1])); } if ("-es".equals(s[0])) { // generate a b64 encoding from a given string System.out.println(b64.encodeString(s[1])); } if ("-ds".equals(s[0])) { // generate a b64 decoding from a given string System.out.println(b64.decodeString(s[1])); } if ("-cl".equals(s[0])) { // return the cardinal of a given string as long value with the enhanced encoder System.out.println(Base64Order.enhancedCoder.cardinal(s[1].getBytes())); } if ("-cn".equals(s[0])) { // return the cardinal of a given string as normalized float 0 .. 1 with the enhanced encoder System.out.println(((double) Base64Order.enhancedCoder.cardinal(s[1].getBytes())) / ((double) Long.MAX_VALUE)); } if ("-test".equals(s[0])) { System.out.println("Pid: " + ManagementFactory.getRuntimeMXBean().getName()); // do some checks // not real random to be able to reproduce the test Random r = new Random(0); try { // use the class loader to call sun.misc.BASE64Encoder, the sun base64 encoder // we do not instantiate that class here directly since that provokes a // "warning: sun.misc.BASE64Encoder is internal proprietary API and may be removed in a future release" Class<?> rfc1521Decoder_class = Class.forName("sun.misc.BASE64Decoder"); Object rfc1521Decoder = rfc1521Decoder_class.newInstance(); Method rfc1521Decoder_decodeBuffer = rfc1521Decoder_class.getMethod("decodeBuffer", String.class); Class<?> rfc1521Encoder_class = Class.forName("sun.misc.BASE64Encoder"); Object rfc1521Encoder = rfc1521Encoder_class.newInstance(); Method rfc1521Encoder_encode = rfc1521Encoder_class.getMethod("encode", byte[].class); System.out.println("preparing tests.."); // prepare challenges and results with rfc1521Encoder int count = 100000; String[] challenges = new String[count]; String[] rfc1521Encoded = new String[count]; for (int i = 0; i < count; i++) { int len = r.nextInt(10000); StringBuilder challenge = new StringBuilder(len); for (int j = 0; j < len; j++) challenge.append((char) (32 + r.nextInt(64))); challenges[i] = challenge.toString(); rfc1521Encoded[i] = (String) rfc1521Encoder_encode.invoke(rfc1521Encoder, UTF8.getBytes(challenges[i])); } // starting tests long start = System.currentTimeMillis(); for (boolean rfc1521Compliant : new boolean[] { false, true }) { System.out.println("starting tests, rfc1521Compliant = " + rfc1521Compliant + " ..."); String eb64, rfc1521; // encode with enhancedCoder, decode with standard RFC 1521 base64 for (int i = 0; i < count; i++) { if (rfc1521Compliant) { rfc1521 = Base64Order.standardCoder.encode(UTF8.getBytes(challenges[i])); } else { eb64 = Base64Order.enhancedCoder.encode(UTF8.getBytes(challenges[i])); rfc1521 = new String(eb64); while (rfc1521.length() % 4 != 0) rfc1521 += "="; rfc1521 = rfc1521.replace('-', '+').replace('_', '/'); } String rfc1521Decoded = UTF8.String((byte[]) rfc1521Decoder_decodeBuffer.invoke(rfc1521Decoder, rfc1521)); if (!rfc1521Decoded.equals(challenges[i])) System.out.println("Encode enhancedB64 + Decode RFC1521: Fail for " + challenges[i]); } // sun.misc.BASE64Encoder rfc1521Encoder = new sun.misc.BASE64Encoder(); for (int i = 0; i < count; i++) { // encode with enhancedCoder, decode with standard RFC 1521 base64 rfc1521 = new String(rfc1521Encoded[i]); if (rfc1521Compliant) { String standardCoderDecoded = UTF8.String(Base64Order.standardCoder.decode(rfc1521)); if (!standardCoderDecoded.equals(challenges[i])) System.out.println("Encode RFC1521 + Decode enhancedB64: Fail for " + rfc1521); } else { eb64 = new String(rfc1521); while (eb64.endsWith("=")) eb64 = eb64.substring(0, eb64.length() - 1); eb64 = eb64.replace('+', '-').replace('/', '_'); String enhancedCoderDecoded = UTF8.String(Base64Order.enhancedCoder.decode(eb64)); if (!enhancedCoderDecoded.equals(challenges[i])) System.out.println("Encode RFC1521 + Decode enhancedB64: Fail for " + eb64); } } } long time = System.currentTimeMillis() - start; System.out.println("time: " + (time / 1000) + " seconds, " + (1000 * time / count) + " ms / 1000 steps"); } catch (Throwable e) { e.printStackTrace(); } } }
Example 93
Project: elasticsearch-jetty-master File: RestConstraintSecurityHandlerTests.java View source code |
protected HttpTester request(String method, String url, String username, String password) { HttpTester request = new HttpTester(); request.setMethod(method); request.setURI(url); request.setVersion("HTTP/1.0"); BASE64Encoder enc = new sun.misc.BASE64Encoder(); String userPassword = username + ":" + password; request.addHeader("Authorization", "Basic " + enc.encode(userPassword.getBytes())); return request; }
Example 94
Project: alkacon-oamp-master File: CmsStringCrypter.java View source code |
/** * Encrypts the given value.<p> * * @param value the string which should be encrypted * @param password the passsword used for encryption, use the same password for decryption * @return the encrypted string of the value or null if something went wrong */ public static String encrypt(String value, String password) { // check if given value is valid if (CmsStringUtil.isEmptyOrWhitespaceOnly(value)) { if (LOG.isWarnEnabled()) { LOG.warn(Messages.get().getBundle().key(Messages.LOG_WARN_INVALID_ENCRYPT_STRING_1, value)); } return null; } try { // create key byte[] k = getKey(password); Key key = new SecretKeySpec(k, ENCRYPTION); Cipher cipher = Cipher.getInstance(ENCRYPTION); cipher.init(Cipher.ENCRYPT_MODE, key); // encrypt text byte[] cleartext = value.getBytes(FORMAT); byte[] ciphertext = cipher.doFinal(cleartext); // encode with base64 to be used as a url parameter BASE64Encoder base64encoder = new BASE64Encoder(); String base64encoded = base64encoder.encode(ciphertext); base64encoded = CmsStringUtil.substitute(base64encoded, "+", "-"); base64encoded = CmsStringUtil.substitute(base64encoded, "/", "_"); return base64encoded; } catch (Exception ex) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key(Messages.LOG_ERROR_ENCRYPT_0), ex); } } return null; }
Example 95
Project: Athena-Chat-master File: AuthenticationInterface.java View source code |
/**
* Compute the SHA-1 hash of a String
* @param toHash String to hash
* @return toHash hashed with SHA-1
* @throws Exception
*/
public static String computeHash(String toHash) throws Exception {
MessageDigest md = null;
try {
md = //step 2
MessageDigest.getInstance(//step 2
"SHA-1");
} catch (NoSuchAlgorithmException e) {
throw new Exception(e.getMessage());
}
try {
md.update(//step 3
toHash.getBytes(//step 3
"UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new Exception(e.getMessage());
}
//step 4
byte raw[] = md.digest();
//step 5
String hash = (new BASE64Encoder()).encode(raw);
//step 6
return hash;
}
Example 96
Project: carbon-registry-master File: SecureVaultUtil.java View source code |
public static String encryptValue(String plainTextPass) throws AxisFault { CipherInitializer ciperInitializer = CipherInitializer.getInstance(); byte[] plainTextPassByte = plainTextPass.getBytes(); try { Cipher cipher = ciperInitializer.getEncryptionProvider(); if (cipher == null) { if (cipher == null) { log.error("Either Configuration properties can not be loaded or No secret" + " repositories have been configured please check PRODUCT_HOME/repository/conf/security " + " refer links related to configure WSO2 Secure vault"); handleException(log, "Failed to load security key store information ," + "Configure secret-conf.properties properly by referring to https://docs.wso2.com/display/Carbon440/Encrypting+Passwords+with+Cipher+Tool", null); } } byte[] encryptedPassword = cipher.doFinal(plainTextPassByte); BASE64Encoder encoder = new BASE64Encoder(); String encodedValue = encoder.encode(encryptedPassword); return encodedValue; } catch (IllegalBlockSizeException e) { handleException(log, "Error encrypting password ", e); } catch (BadPaddingException e) { handleException(log, "Error encrypting password ", e); } return null; }
Example 97
Project: classlib6-master File: Manifest.java View source code |
public void doHashes(MessageHeader mh) throws IOException { // If unnamed or is a directory return immediately String name = mh.findValue("Name"); if (name == null || name.endsWith("/")) { return; } BASE64Encoder enc = new BASE64Encoder(); /* compute hashes, write over any other "Hash-Algorithms" (?) */ for (int j = 0; j < hashes.length; ++j) { InputStream is = new FileInputStream(stdToLocal(name)); try { MessageDigest dig = MessageDigest.getInstance(hashes[j]); int len; while ((len = is.read(tmpbuf, 0, tmpbuf.length)) != -1) { dig.update(tmpbuf, 0, len); } mh.set(hashes[j] + "-Digest", enc.encode(dig.digest())); } catch (NoSuchAlgorithmException e) { throw new JarException("Digest algorithm " + hashes[j] + " not available."); } finally { is.close(); } } }
Example 98
Project: cloudpier-adapters-master File: BeansUpdateEnvironment.java View source code |
/**
* Computes RFC 2104-compliant HMAC signature.
*
* @param data The data to be signed.
* @return The base64-encoded RFC 2104-compliant HMAC signature.
* @throws java.security.SignatureException
* when signature generation fails
*/
protected String generateSignature(String data) throws java.security.SignatureException {
String result;
try {
// get a hash key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(secretAccessKey.getBytes(), HASH_ALGORITHM);
// get a hasher instance and initialize with the signing key
Mac mac = Mac.getInstance(HASH_ALGORITHM);
mac.init(signingKey);
// compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(data.getBytes());
// base64-encode the hmac
// result = Encoding.EncodeBase64(rawHmac);
result = new BASE64Encoder().encode(rawHmac);
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
return result;
}
Example 99
Project: cloudpier-core-master File: BeansUpdateEnvironment.java View source code |
/**
* Computes RFC 2104-compliant HMAC signature.
*
* @param data The data to be signed.
* @return The base64-encoded RFC 2104-compliant HMAC signature.
* @throws java.security.SignatureException
* when signature generation fails
*/
protected String generateSignature(String data) throws java.security.SignatureException {
String result;
try {
// get a hash key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(secretAccessKey.getBytes(), HASH_ALGORITHM);
// get a hasher instance and initialize with the signing key
Mac mac = Mac.getInstance(HASH_ALGORITHM);
mac.init(signingKey);
// compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(data.getBytes());
// base64-encode the hmac
// result = Encoding.EncodeBase64(rawHmac);
result = new BASE64Encoder().encode(rawHmac);
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
return result;
}
Example 100
Project: com.opendoorlogistics-master File: ImageUtils.java View source code |
/** * Encode image to string * * @param image * The image to encode * @param type * jpeg, bmp, ... * @return encoded string */ public static String imageToBase64String(RenderedImage image, String type) { String ret = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ImageIO.write(image, type, bos); byte[] bytes = bos.toByteArray(); BASE64Encoder encoder = new BASE64Encoder(); ret = encoder.encode(bytes); ret = ret.replace(System.lineSeparator(), ""); } catch (IOException e) { throw new RuntimeException(); } return ret; }
Example 101
Project: common_utils-master File: RsaUtils.java View source code |
/** * åŠ å¯†æ–¹æ³• * * @param source æº?æ•°æ?® * @return * @throws Exception * @deprecated */ private static String encrypt(String source) throws Exception { generateKeyPair(); Key publicKey; ObjectInputStream ois = null; try { /** 将文件ä¸çš„公钥对象读出 */ ois = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE)); publicKey = (Key) ois.readObject(); } catch (Exception e) { throw e; } finally { ois.close(); } /** 得到Cipher对象æ?¥å®žçŽ°å¯¹æº?æ•°æ?®çš„RSAåŠ å¯† */ Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] b = source.getBytes(); /** æ‰§è¡ŒåŠ å¯†æ“?作 */ byte[] b1 = cipher.doFinal(b); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(b1); }