/** * Encodes a String into a base 64 String. The resulting encoding is chunked at 76 bytes. * <p> * * @param s String to encode. * * @return encoded string. */ public static String encode( String s ) { byte[] sBytes = s.getBytes(); sBytes = encode( sBytes ); s = new String( sBytes ); return s; }
/** * Encrypts and returns the encrypted string for the given message. * * @param message the pass phrase that is to be encrypted. * @return the encrypted string for the given message. */ static String encrypt(String message) { java.security.MessageDigest d =null; try { d = java.security.MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { return null; } d.reset(); d.update(message.getBytes()); return new String(Base64Encoder.encode(d.digest())); }
/** * Prepares an url connection for authentication if necessary. * * @param connection the connection to be prepared * * @return the prepared conection */ public static URLConnection prepareForAuthentication( final URLConnection connection ) { NullArgumentException.validateNotNull( connection, "url connection cannot be null" ); if( connection.getURL().getUserInfo() != null ) { // Need to decode username/password because it may contain encoded characters (http://www.w3schools.com/tags/ref_urlencode.asp) // A common encoding is to provide a username as an email address like user%40domain.org String decodedUserInfo = decode( connection.getURL().getUserInfo() ); String base64Encoded = Base64Encoder.encode( decodedUserInfo ); // sun bug 6459815: Long passwords cause Basic Auth to fail with a java.net.Authenticator base64Encoded = base64Encoded.replaceAll( "\n", "" ); connection.setRequestProperty( "Authorization", "Basic " + base64Encoded ); } return connection; }