Base64 encoded String
Is there any support in Java to do base64 encoding on a String (I'm using Java 6)?
fredrikl wrote:
Is there any support in Java to do base64 encoding on a String (I'm using Java 6)?Did you do any research?
[http://www.google.com/search?q=java+base64+example]
Similar Messages
-
How to convert a base64 encoded string to binary?
Hi, gurus,
I want to convert a base64 encoded string (a image which is read from a xml file)
into a normal binary string and then upload to archive link.
could you pls give me some hints on that?
br.
junthank you for your quick reply!
my real requirement is to extract an image(it 's said it's encoded using base64?) from a xml file and upload it sap archive linke,
following is the xml content, does that mean i need to convert all the chars in the
<mime_content> pair to your fm, that will be convert to binary string?
<MIME_CONTENT xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/" href="" xfa:contentType="image/jpg"
>/9j/4AAQSkZJRgABAAEAYABgAAD//gAfTEVBRCBUZWNobm9sb2dpZXMgSW5jLiBWMS4wMQD/2wCE
AAgFBgcGBQgHBgcJCAgJDBQNDAsLDBgREg4UHRkeHhwZHBsgJC4nICIrIhscKDYoKy8xMzQzHyY4
PDgyPC4yMzEBCAkJDAoMFw0NFzEhHCExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEx
MTExMTExMTExMTExMTExMf/EAaIAAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKCwEAAwEBAQEB
AQEBAQAAAAAAAAECAwQFBgcICQoLEAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEU
MoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2Rl
ZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK
0tPU1dbX2Nna4eLj5OXm5jp6vHy8/T19vf4foRAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYS
QVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNU
VVZXWFl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vFkeiXGk6doOvFLoRR7LqSARIFk3huDnOS3/fRoA9XOvhGbxH4OQ6XpQv9Yt5I1hZQPMRM/OA
T24oAj1bxb4rvtEvNPT4daqjXFs8Ic3URALKVz+tAGn4HtNW8I/CKyt59KlutUs7dj9hjZSzMzkh
c9OjDP40AeSv4H8Z2aGe68Nzardalok1vLhogLWaSVivB7qoXp69aAO0D3h3XrLxaNQ1Xw2jW9
vocOn5Z0PnSoVy+F9cE8/nQB7BQAUAFABQAUAFABQAUAFABQAUAFAH//2Q==</MIME_CONTENT
> -
Converting Base64 encoded String to String object
Hi,
Description:
I have a Base64 encoded string and I am using this API for it,
[ http://ws.apache.org/axis/java/apiDocs/org/apache/axis/encoding/Base64.html]
I am simply trying to convert it to a String object.
Problem:
When I try and write the String, ( which is xml ) as a XMLType to a oracle 9i database I am getting a "Cannot map Unicode to Oracle character." The root problem is because of the conversion of the base64 encoded string to a String object. I noticed that some weird square characters show up at the start of the string after i convert it. It seems like I am not properly converting to a String object. If i change the value of the variable on the fly and delete these little characters at the start, I don't get the uni code error. Just looking for a second thought on this.
Code: Converting Base64 Encoded String to String object
public String decodeToString( String base64String )
byte[] decodedByteArray = Base64.decode( base64String );
String decodedString = new String( decodedByteArray, "UTF-8");
}Any suggestions?To answer bigdaddy's question and clairfy a bit more:
Constraints:
1. Using a integrated 3rd party software that expects a Base64 encoded String and sends back a encoded base64 String.
2. Using JSF
3. Oracle 10g database and storing in a XMLType column.
Steps in process.
1. I submit my base64 encoded String to this 3rd party software.
2. The tool takes the encoded string and renders a output that works correctly. The XML can be modified dynamically using this tool.
3. I have a button that is binded to my jsf backing bean. When that button is clicked, the 3rd party tool sets a backing bean string value with the Base64 String representing the updated XML.
4. On the backend in my jsf backing bean, i attempt to decode it to string value to store in the oracle database as a XML type. Upon converting the byte[] array to a String, i get this conversion issue.
Possibly what is happen is that the tool is sending me a different encoding that is not UTF-8. I thought maybe there was a better way of doing the decoding that i wasn't looking at. I will proceed down that path and look at the possibility that the tool is sending back a different encoding then what it should. I was just looking for input on doing the byte[] decoding.
Thanks for the input though.
Edited by: haju on Apr 9, 2009 8:41 AM -
UIImage to Base64 Encoded String does not matched with PHP Encoded String
Hi, I have converted an image to base64 string using the following
UIImage* pic = [UIImage imageNamed:@"closeBtn.png"];
NSData* pictureData = UIImagePNGRepresentation(pic);
[Base64 initialize];
NSString * encodedString = [Base64 encode:pictureData];
The result obtained by this method and by converting the same image to base64 string in PHP or ASP is different. I am comparing the base64 string (testData) with online generated string from URL http://www.dailycoding.com/Utils/Converter/ImageToBase64.aspx
Please help ASAPKeith:
I am converting the PNG Image.Actually i want to post a image to PHP server via JSON. for that i am converting the image into base64 string and then sending JSON via HTTP. but when server receives a image data , it cannot convert and save it properl (blank image with 0x0 dimensions). I have compared the Base64 String created from xCode with some online conversion tools. and results are different. I have even tried with JPG images as well.
How can I get the Same Encoded String as PHP or ASP code can have? -
How to do Base64 encoding?
I would like to know if the Java API provides a method to do Base64 encoding. I've been searching and not finding anything similar. If not, is there a readily available piece of code in public domain that does this?
Ok how about this pure Java API solution.
Yours for free free free, no unintened theft. Completely portable per the Java promise. This code sets no preferences! The class just extends AbstractPreferences to get access to the put and get and over rides them. The super still calls the Base64 to do the encoding and decoding. This extension intercepts the encoded/decoded strings and makes them visible. TaDa Java API supports, has, allows, does base64 encoding, for the clever anyway.
package yourpackage;
public class YourPreferences extends java.util.prefs.AbstractPreferences {
//keep the key state
private java.util.Hashtable encodedStore = new java.util.Hashtable();
/** Creates a new instance of YourPreferences*/
public YourPreferences(java.util.prefs.AbstractPreferences prefs, java.lang.String string) {
super(prefs, string);
//main acts as a driver i.e. used to test this class not required by this class
public static void main(java.lang.String[] args ){
java.util.prefs.AbstractPreferences myprefs = new yourpackage.YourPreferences(null, "");
java.lang.String stringToEncode = "Aladdin:open sesame";
java.lang.String key = "Aladdin:open sesame";
java.lang.String key_ = "KEYisNOTtheSAMEasTHEstring";
try{
java.lang.String encoded = ((yourpackage.YourPreferences)myprefs).encodeBase64(stringToEncode);
java.lang.System.out.println("ENCODED STRING TO: " + encoded);
java.lang.String base64 = (java.lang.String)((yourpackage.YourPreferences)myprefs).encodedStore.get(key);
java.lang.String decoded = ((yourpackage.YourPreferences)myprefs).decodeBase64("newkey",base64);
java.lang.System.out.println("DECODED STRING TO: " + decoded);
java.lang.String encoded_ = ((yourpackage.YourPreferences)myprefs).encodeBase64(key_,"ALONGSTRANGESTRINGTHATMAKESNOSENCEATALLBUTCANBEENCODEDANYWAYREGARDLESS");
java.lang.System.out.println("ENCODED STRING TO: " + encoded_);
java.lang.String base64_ = (java.lang.String)((yourpackage.YourPreferences)myprefs).encodedStore.get(key_);
java.lang.String decoded_ = ((yourpackage.YourPreferences)myprefs).decodeBase64(key_,base64_);
java.lang.System.out.println("DECODED STRING TO: " + decoded_);
java.lang.System.out.println("\n");
java.util.Enumeration enum = ((yourpackage.YourPreferences)myprefs).encodedStore.keys();
java.lang.String enumKey = null;
while(enum.hasMoreElements()){
enumKey = (java.lang.String)enum.nextElement();
java.lang.System.out.print(enumKey);
java.lang.System.out.println(" : " +((yourpackage.YourPreferences)myprefs).encodedStore.get(enumKey).toString());
}catch(java.io.UnsupportedEncodingException uee){
uee.printStackTrace();
}catch(java.io.IOException ioe){
ioe.printStackTrace();
public java.lang.String encodeBase64(java.lang.String key, java.lang.String raw)throws java.io.UnsupportedEncodingException{
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
java.io.PrintWriter pw = new java.io.PrintWriter(
new java.io.OutputStreamWriter(baos,"UTF8"));
pw.write(raw.toCharArray());
pw.flush();//ya know
byte[] rawUTF8 = baos.toByteArray();
this.putByteArray(key, rawUTF8);
return (java.lang.String)this.encodedStore.get(key);
public java.lang.String encodeBase64(java.lang.String raw)throws java.io.UnsupportedEncodingException{
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
java.io.PrintWriter pw = new java.io.PrintWriter(
new java.io.OutputStreamWriter(baos,"UTF8"));
pw.write(raw.toCharArray());
pw.flush();//ya know
byte[] rawUTF8 = baos.toByteArray();
this.putByteArray(raw, rawUTF8);
return (java.lang.String)this.encodedStore.get(raw);
public java.lang.String decodeBase64(java.lang.String key, java.lang.String base64String)
throws java.io.UnsupportedEncodingException, java.io.IOException{
byte[] def = {(byte)'D',(byte)'E',(byte)'F'};//not used at any point
this.encodedStore.put(key,base64String);
char[] platformChars = null;
byte[] byteResults = null;
byteResults = this.getByteArray(key, def);
java.io.InputStreamReader isr = new java.io.InputStreamReader(
new java.io.ByteArrayInputStream(byteResults),"UTF8");
platformChars = new char[byteResults.length];
isr.read(platformChars);
return new java.lang.String(platformChars);
//intercept key lookup and return our own base64 encoded string to super
public String get(String key, String def) {
return (java.lang.String)this.encodedStore.get(key);
//intercepts put captures the base64 encoded string and returns it
public void put(String key, String value){
this.encodedStore.put(key, value);//save the encoded string
//dummy implementation as AbstractPreferences is extended to get acces to protected
//methods and to overide put(String,String) and get(String,String)
protected java.util.prefs.AbstractPreferences childSpi(String name) {return null;}
protected String[] childrenNamesSpi() throws java.util.prefs.BackingStoreException {return null;}
protected void flushSpi() throws java.util.prefs.BackingStoreException {}
protected String getSpi(String key) {return null;}
protected String[] keysSpi() throws java.util.prefs.BackingStoreException {return null;}
protected void putSpi(String key, String value) {}
protected void removeNodeSpi() throws java.util.prefs.BackingStoreException {}
protected void removeSpi(String key) {}
protected void syncSpi() throws java.util.prefs.BackingStoreException {} -
Replace value in CLOB containing 2400-3000 bytes of Base64 encoded text
Hi,
I need to replace a part of a base64 encoded string stored in a CLOB.
Basically what I need to do is to:
- Get data from CLOB
- Base64 decode
- Replace a part of the string
- Base64 encode
- Put data back into CLOB
I have tried using the UTL_ENCODE.BASE64_ENCODE (and DECODE). These functions uses and supplies RAW-values, so to convert to RAW I did UTL_RAW.CAST_TO_RAW (and _VARCHAR2 to go back).
I've found that the RAW-type is limited to 2000 bytes (http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96624/03_types.htm#10764), but the messages I'm trying to modify is from about 2400 to about 3000 bytes.
Is there any way around this problem?
Thanks in advance,
JanThe link you provided states, pl sql variable can be up to 32767 bytes , only database column can be up to 2000 bytes. For processing you describe, i suggest, you are interested only in plsql raw variables, not in the database columns ( which are clob's).
Best regards
Maxim -
Need to Base64 encode a String but How?
Hi everone:
I have to Base64 encode and decode a String, but I haven't found any method or API to do it. Does anybody know where to find it? Some ideas about how to?
Thank you all.
Jose.Hi everone:
I have to Base64 encode and decode a String, but I
haven't found any method or API to do it. Does anybodyOh, one thing struck me, why do you need to Base64 encode character data? Normally Base64 is used to encode binary data. If you can represent the bytes as a UTF-8 encoded String, and all components can handle UTF-8, then you should be fine without Base64.
know where to find it? Some ideas about how to?
Thank you all.
Jose. -
Problem with My Base64 Encoding CLOB Routine.
I have written a program which reads an xml file into the database
and makes it Base64encoded.
This needs to work on 10g and above
If the read length specified in the code below is greater than the length of the xml_file, then I get the expected result(output).
However if the read length is less than the length of the file, then I get a lot of '==' in the file and as a result, incorrect encoding which means that the file will not be readable through the application.
I'm pretty sure I'm reading the blob lengths correctly, and the problem is somehow related to the base64 encoding.Any help appreciated
[create or replace profile_dir as &profile_dir;
create global temporary table load_xml
(profile_text clob)
on commit delete rows;
create or replace
procedure encode_xml_clobs(p_file_in in varchar2,
p_clob_out out nocopy clob )
as
pragma autonomous_transaction;
dest_clob CLOB;
src_clob BFILE := BFILENAME('PROFILE_DIR', p_file_in);
dst_offset number := 1 ;
src_offset number := 1 ;
lang_ctx number := DBMS_LOB.DEFAULT_LANG_CTX;
warning number;
-- processing declarations for encoding base64 --
v_xml_string varchar2(32767);
v_string varchar2(32767);
v_start_pos number := 0;
v_read_length number := 1000;
v_final_start_pos number;
v_clob_length number;
type clob_array_type is table of clob index by binary_integer;
clob_array clob_array_type;
v_index number :=0;
-- Declarations for converting base64encoded string to a clob
v_encoded_length number;
v_temp_clob clob;
BEGIN
-- THE FOLLOWING BLOCK OF CODE WILL ATTEMPT TO INSERT / WRITE THE CONTENTS
-- OF AN XML FILE TO A CLOB COLUMN. IN THIS CASE, WE WILL USE THE NEW
-- DBMS_LOB.LoadCLOBFromFile() API WHICH *DOES* SUPPORT MULTI-BYTE
-- CHARACTER SET DATA.
-- load_xml should be a Global temporary table with on commit delete rows
INSERT INTO load_xml(profile_text)
VALUES( empty_clob())
RETURNING profile_text INTO dest_clob;
-- OPENING THE SOURCE BFILE IS MANDATORY
DBMS_LOB.OPEN(src_clob, DBMS_LOB.LOB_READONLY);
DBMS_LOB.LoadCLOBFromFile(
DEST_LOB => dest_clob
, SRC_BFILE => src_clob
, AMOUNT => DBMS_LOB.GETLENGTH(src_clob)
, DEST_OFFSET => dst_offset
, SRC_OFFSET => src_offset
, BFILE_CSID => DBMS_LOB.DEFAULT_CSID
, LANG_CONTEXT => lang_ctx
, WARNING => warning
DBMS_LOB.CLOSE(src_clob);
-- DBMS_OUTPUT.PUT_LINE('Loaded XML File using DBMS_LOB.LoadCLOBFromFile: (ID=1');
-- file now successfully loaded
select dbms_lob.GETLENGTH(profile_text)
into v_clob_length
from load_xml;
-- File now loaded in temporary table
-- we now need to take the clob , convert it to varchar2
v_read_length :=64;
v_xml_string := '';
while v_start_pos <= v_clob_length
loop
v_index := v_index + 1;
v_string := '';
--dbms_output.put_line('Start_pos=>'||(v_start_pos+1)||' Read Length=>'||v_read_length);
--encode base64
select utl_raw.cast_to_varchar2(
utl_encode.base64_encode(
utl_raw.cast_to_raw(dbms_lob.substr(profile_text,least(v_read_length,v_clob_length-v_start_pos),v_start_pos+1))
into v_string
from load_xml;
--dbms_output.put_line(v_string);
v_start_pos := v_start_pos+v_read_length;
clob_array(v_index) := v_string;
end loop;
p_clob_out := clob_array(1);
for i in 2 .. v_index
loop
dbms_lob.append(p_clob_out,clob_array(i));
end loop;
commit;
END;Base64 encoding encodes every 3 bytes of input data into 4 bytes of output data. It uses equal signs to indicate nodata and only at the end of the encoded sequence. Try chaning your v_read_length parameter to a multiple of 3 e.g. 960 or 1008 instead of the current 1000. I'm using multiples of 48 because the utl_encode.base64_encode function adds a linebreak for every 48 bytes of input data (64 bytes of output). If you use a value that's not divisible by 48 you will still get a legitimate encoding as long as it's divisible by 3, but you will get some lines longer than others when you append them together.
-
Base64 Encoding in SOA 11.1.1.5.0
Hi All,
For writing a String to a Flat File(Opaque Schema) using FileAdapter the string needs to be converted to Base64 Encoding
I am not able to Encode the string to base64 in BPEL 11g.
JDEVELOPER VERSION.Studio Edition Version 11.1.1.5.0
SOA Suite Version 11.1.1.5.0
I tried with BPEL1.1 specification and BPEL2.0 specification with no luck
Steps carried out
a) Created a variable "input1" with String type
b) Assigned a custom message to input1 variable
c) In Java Embedding activity wrote the below snippet
String input = (String)getVariableData("input1");
addAuditTrailEntry(input);
String encodeData = oracle.soa.common.util.Base64Encoder.encode(input);
addAuditTrailEntry(encodeData);
I am getting different errors while using BPEL 1.1 spec and 2.0 spec
BPEL 1.1 Spec
Jdeveloper doesnt compile.
Error is Error: SCAC-50012
BPEL 2.0 Spec
Jdeveloper compile's but while deploying am getting the below error
Error deploying BPEL suitcase.
error while attempting to deploy the BPEL component file "/dtrb5o/admin/soa_domain/mserver/soa_domain/servers/soa_server1/dc/soa_04c5e5c5-eeb1-49da-841a-c793206a0285";
the exception reported is:java.lang.RuntimeException: failed to compile execlets of BPELProcess1
This error contained an exception thrown by the underlying deployment module.
Verify the exception trace in the log (with logging level set to debug mode).
+[05:40:21 PM] Check server log for more details.+
+[05:40:21 PM] Error deploying archive sca_Base64_2_rev1.0.jar to partition "default" on server soa_server1 [] +
+[05:40:21 PM] #### Deployment incomplete. ####+
+[05:40:21 PM] Error deploying archive file:/C:/JdevHome/Users/c_anishi/mywork/BPELApplication/Base64_2/deploy/sca_Base64_2_rev1.0.jar +
+(oracle.tip.tools.ide.fabric.deploy.common.SOARemoteDeployer)+
The SOA RunTime Library is already added to the project. I even tried explicitly adding fabric-common.jar and fabric-runtime.jar to the project library with no luck
Please let me know if any one has acheived the base64 encoding in 11.1.1.5.0Check this out,
http://yatanveersingh.blogspot.com/2011/08/how-to-call-java-method-inside-bpel.html
-Yatan -
Convert canvas.toDataURL('image/jpeg') to java.sql.Blob.
I am using oracle adf so I am able to action a backing bean from javascript and pass in parameters as a map. I pass in the canvas.toDataURL('image/jpeg') which I then try to decode in my bean. Using BASE64Decoder and the converting the bytearray to a file I can see the image is corrupted as I can't open the file thus converting the bytearray to blob is also a waste.
Has anyone any ideas on base64 encoding from canvas.toDataURL to file or Blob?Use Case:
A jsf page that enables a user to take photos using the HTML5 canvas feature - interact with webcam -, take photos and upload to profile
1. I have created the jsf page with the javascript below; this pops up as a dialog and works okay and onclick an upload image, triggers the snapImage javascript function below and sends the imgURL parameter to the serverside managedbean
<!-- java script-->
function snapImage(event){
var canvas = AdfPage.PAGE.findComponent('canvas');
AdfCustomEvent.queue(event.getSource(),"getCamImage",{imgURL:canvas.toDataURL('image/jpeg'),true);
event.cancel();
<!-- bean -->
public void getCamImage(ClientEvent ce){
String url=(String)ce.getAttributes().get("imgURL");
decodeBase64URLToBlob(url);
private BlobDomain decodeBaseB4URLToBlob(String url64){
BASE64Decoder de=new BASE64Decoder();
byte[] bytes=de.decode(url64);
File file=new File("abc.jpg");
InputStream in = new ByteArrayInputStream(bytes);
BufferedImage bImageFromConvert = ImageIO.read(in);
in.close();
ImageIO.write(bImageFromConvert, "jpg", file);
return createBlobDomainFromFile(file);
----problem---
Accessing the generated jpeg file shows the image is corrupted, probably missing bytes or encode/decoder issues.and the blob image after uploading to database is saved as a binary stream which ondownload doesnt render as an image or anything i know of.
Is there anyways of achieving the conversion without errors? -
Yet another Base64 encoder / decoder
Hi, I would like introduce a different Base64 encoding scheme which yields slightly more compact results when encoding international characters.
This is an implementation of BASE64UTF9 encoder and decoder.
Common practice converts Java strings to UTF8 before Base64 encoding.
UTF8 is not so space efficient in representing non-ASCII characters.
While UTF9 is impractical as raw data in most 8 bit machines, it fits
well within Base64 streams since 3 symbols can represent 2 UTF9 nonets.
In this implementation, a modified UTF9 (flipped bit 9) is chosen to
ensure nonet '0x000' never appear but maybe be inserted if needed.
This implementation is also coded in such a way that it is possible to
use Base100 encoding. When run from command line, it will perform a
test with random strings and display encoding compactness compared to
to other existing schemes.
public class B64utf9 {
private static final String look =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
//"\u0010\u0011\u0012\u0013\u0014!\"#$%&'()*+,-./ 0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
private static final int BASE = look.length();
private static final int SYMB = (int)java.lang.Math.pow(BASE, 1.5) / 2;
public static String decode(String str) {
long j = 1, k = 0, q = 0;
StringBuffer buf = new StringBuffer();
for(int p = 0; p < str.length(); p++) {
k += look.indexOf(str.charAt(p)) * j;
for(j *= BASE; j >= SYMB * 2; j /= SYMB * 2) {
q = q * SYMB + k % SYMB;
if(k % (SYMB * 2) >= SYMB) {
buf.append((char)q);
q = 0;
k /= SYMB * 2;
return buf.toString();
public static String encode(String str) {
long j = 1, k = 0;
StringBuffer buf = new StringBuffer();
for(int p = 0; p < str.length(); p++) {
long r, q = str.charAt(p);
for(r = 1; r * SYMB <= q; r *= SYMB);
for(; r > 0; r /= SYMB) {
k += ((q / r) % SYMB + (r > 1 ? 0 : SYMB)) * j;
for(j *= SYMB * 2; j >= BASE; j /= BASE) {
buf.append(look.charAt((int)k % BASE));
k /= BASE;
if(j > 1) buf.append(look.charAt((int)k));
return buf.toString();
public static void main(String arg[]) throws Exception {
java.util.Random rnd = new java.util.Random();
for(double q = 1; q < 9; q++) {
int x = 0, y = 0, z = 0;
int r = (int)java.lang.Math.pow(Character.MAX_VALUE, 1 / q);
for(int p = 0; p < 999; p++) {
StringBuffer buf = new StringBuffer();
while(rnd.nextInt(99) > 0) {
char k = 1;
// varying ASCII density
for(int j = 0; j < q; j++)
k *= rnd.nextInt(r);
buf.append(k);
String str = buf.toString();
// regression
if(!decode(encode(str)).equals(str))
System.out.println(str);
// count encoded length
x += encode(str).length();
y += new sun.misc.BASE64Encoder().encode(str.getBytes("utf8")).length();
z += new sun.misc.BASE64Encoder().encode(str.getBytes("gb18030")).length();
System.out.println(x +","+ y +","+ z);
}{code}Good idea! Sometimes it depends on what you want to encode too, however.
I suppose there is a case where general purpose compression does not work very well - random generated data.
Here's how I tested it:
class Count {
private static String enc(String src, String set) throws Exception {
return new String(src.getBytes(set), "iso-8859-1");
private static byte[] dec(byte[] src, String set) throws Exception {
return new String(src, set).getBytes("iso-8859-1");
public static void main(String[] arg) throws Exception {
java.util.Random rnd = new java.util.Random();
int x = 0, y = 0;
for(int k = 0; k < 99; k++) {
byte[] raw = new byte[rnd.nextInt(99)];
for(int z = 0; z < raw.length; z++)
raw[z] = (byte)(rnd.nextInt(256));
String str = new String(raw, "utf16");
byte[] b6u = str.getBytes("x-base64utf9");
byte[] gz2 = enc(enc(str, "utf8"), "x-gzip").getBytes("x-base64");
x += b6u.length;
y += gz2.length;
if(!str.equals(new String(b6u, "x-base64utf9")))
System.out.println(str);
if(!str.equals(new String(dec(dec(gz2, "x-base64"), "x-gzip"), "utf8")))
System.out.println(str);
System.out.println(x +","+ y);
}The above code does not include my my encoders, I put my encoders code as nio.charset package and can be downloaded from [SF.|http://sourceforge.net/project/showfiles.php?group_id=248737]
PS: sorry about the confusion, please allow me to clarify that the UTF9 encoder is not interchangeable with existing Base64 encoders. There is a compatible (hopefully) encoder in my package, however. -
I have a String representation of an hexadecimal number such
that :
var s:String = "5300ca"; // 0x53, 0x00, 0xca
I want to cut this string into 3 bytes (0x53, 0x00, 0xca) to
use base64 encoding (3 x 8 bits returns 4 characters with base64
encoding). Here is my code :
import mx.utils.*;
import flash.utils.*;
var byte1:int = parseInt("0x53");
var byte2:int = parseInt("0x00");
var byte3:int = parseInt("0xca");
var b:ByteArray = new ByteArray();
b.writeMultiByte(String.fromCharCode(byte1) +
String.fromCharCode(byte2) + String.fromCharCode(byte3), "utf-16");
var base64Encoder:Base64Encoder = new Base64Encoder();
base64Encoder.encodeBytes(b);
var result:String = base64Encoder.drain(); // result = "Uw=="
The result string is "Uw==" whereas it should be "UwDK"
according to the normalized base64-encoding !
Is it a bug in the base-64 encoding ?Very important because this limitation is very blocking
according to me. Nobody has an answer ? -
Illegal character in Base64 encoded data
Hi,
I'm trying to get a print out the public key as a String, which I am getting it in as a base64 encoded, but I get error:
Exception in thread "main" java.lang.IllegalArgumentException: Illegal character in Base64 encoded data.
Code below:
public static void main(String[] args) {
File pubKeyFile = new File("C:\\usercert.pem");
StringBuffer buffer = new StringBuffer();
try {
FileInputStream fis = new FileInputStream(pubKeyFile);
try {
InputStreamReader isr = new InputStreamReader(fis, "UTF8");
Reader in = new BufferedReader(isr);
int ch;
while((ch = in.read()) > -1) {
buffer.append((char)ch);
in.close();
String key = buffer.toString();
System.out.println("key is: " + key);
//This is where the code fails:
String keyDecode = Base64.decodeString(key);
System.out.println("key ecode is: " + keyDecode);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}Hi ejp,
It's a rsa public, the usercert.pem looks like below,
so since it's not an x509 certificate not sure if I
can read it using a
java.security.cert.CertificateFactory?
Basically I just want to print the public and private
key out as a String. Any help is appreciated.
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCg8yo6rDhsNiwUfV
R37HgF4bWq
oG13Nd9XLT+Z0VLzCkWJZOdzGNQnnm7ujoQ8gbxeDvIo9RG5I3eZte
BwD91Nf6P/
E9lvJQDL2Qnz4EXH/CVW9DeEfvY1UJN9kc6q6KkYEPWssvVvlDOp2s
lbEKZCJtaP
vVuGCAqfaps8J0FjOQIDAQAB
-----END PUBLIC KEY-----
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import sun.misc.BASE64Decoder;
public class MakeRSAPublicKeyFromPEM
public static void main(String[] args) throws Exception
final String publickeyAsString =
"-----BEGIN PUBLIC KEY-----\n"+
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCg8yo6rDhsNiwUfVR37HgF4bWq\n"+
"oG13Nd9XLT+Z0VLzCkWJZOdzGNQnnm7ujoQ8gbxeDvIo9RG5I3eZteBwD91Nf6P/\n"+
"E9lvJQDL2Qnz4EXH/CVW9DeEfvY1UJN9kc6q6KkYEPWssvVvlDOp2slbEKZCJtaP\n"+
"vVuGCAqfaps8J0FjOQIDAQAB\n"+
"-----END PUBLIC KEY-----\n";
final BASE64Decoder decoder = new BASE64Decoder();
final byte[] publicKeyAsBytes = decoder.decodeBuffer(publickeyAsString.replaceAll("-+.*?-+",""));
final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyAsBytes);
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
final RSAPublicKey publicKey = (RSAPublicKey)keyFactory.generatePublic(publicKeySpec);
System.out.println("Modulus ........... " + publicKey.getModulus());
System.out.println("Public exponent ... " + publicKey.getPublicExponent());
} -
Hi
I use the auclair base64 class to encode and decode base64 locally and it works great.
But when I send the string to my server and back (aspx), I cannot decode it I have the 2030 error from flash.
When I compare the encoded string from both end they look the same.
I make sure it is fully loaded before attempting the decode.
Is this a common bug or I'm I wrong somewhere?
Thanks
I use the latest air.The -d switch on the openssl base64 command enables debugging; it's the short version of the --debug switch. Probably not what you're after, either. The -D switch would be more typical, that's the short version of --decode switch, and probably what you had intended.
The -i (--input) and -o (--output) switches allow you to specify input and output files, which is one way to pass a whole lot of data into that command.
Do you have an example of some of the text that you're working with? -
Hi there
I am writing an adobe air app in html/javascript and I am trying to base64 encode an image so I can add it to and XML RPC request. I have tried many methods and nothings seems to work.
I see that actionscript has a Base64Encoder class that look like it would work, is there any way to utilize this in javascript?
Thanks,
JordanReading it in as an ASCII string loses information - you're much better off reading it in byte-for-byte. Then you can send it as the serializeable of your choice (even a BigInteger would work).
Maybe you are looking for
-
I need help dividing an image into two equal parts in Adobe Illustrator CC--ASAP!!!
I need help dividing a single, already created image into 2 equal parts...Am getting nowhere so far
-
Orace 11g CRS installation ( windows server 2008 64 bit ) Error
Hi , Installing Orace 11g R1 Clusterware on two nodes RAC1,RAC2 on windows environment . Configured the Public , Private , VIP connections on both of the nodes by updating the host.txt file with . Following the network configurations settigs .. C:\wi
-
Hello all, i run adcfgclone.pl in apps Tier for clone, but facing issue. please advise. Do you want to preserve the port values from the source system on the target system (y/n) [y] ?:n Clone Context uses the same port pool mechanism as the Rapid Ins
-
Condition type has to executed only when other condition type is availabl
Scenario: We have two freight condition types YHD1 & YHD6. This YHD6 condition type is a Percentage type calculation and dependent of YHD1 value, for example YHD1: 30 EUR then the condition value is 30 EUR YHD6: 10 % then the condition value is 3 EU
-
My Mac's Built in iSight is not showing all the options for the camera
On Flash bashed chat rooms such as Stickam and Tinychat, my camera doesn't respond but when I right click>settings >Camera the drop down box only shows one option (Built-in iSight) when it usually shows three (Built in iSight, USB Class Video and Som