Link to home
Start Free TrialLog in
Avatar of code_123
code_123

asked on

BASE64Encoder



Hello All

I have this code

String s = null;
s = "somevalue";

BASE64Encoder encoder = new BASE64Encoder();
String encoded = encoder.encodeBuffer(s.getBytes());

return encoded;


The value returned has a carriage return, so when i insert this value into a db table and do a select where clause the value isn't picked up as the select statement looks like this

select * from table where encoded = 'fklgjfjglfjklgjf'

But if i do this

select * from table where encoded = 'fklgjfjglfjklgjf
'

It works

Can anyone tell me how i get rid of the carriage return ?

Many Thanks
Avatar of plork123
plork123



Try this

byte[] sUserIdBytes = s.getBytes();
            
BASE64Encoder encoder = new BASE64Encoder();
       
String encoded = encoder.encode(sUserIdBytes ) ;

return encoded ;
From your select statements it looks like the offending character is at the end of the string. In that case the simple solution would be something like:

String s = null;
s = "somevalue";

BASE64Encoder encoder = new BASE64Encoder();
String encoded = encoder.encodeBuffer(s.getBytes());

return encoded.substring(0,encoded.length()-1);
Avatar of CEHJ
Let's look at this a different way - firstly, why are you saving something as Base64?
Avatar of code_123

ASKER



what should i be saving it as then?
There are other options, but without knowing why you're using this method, it's hard to comment


I just want ot encypt a string - that's all, so pass a string into the method and return an encrypted version of is

e.g. normal string = mystring
encrypted string = hjgjkf898TWQ890585jkjk954534323dwe ......
Well Base64's purpose is not for encryption - it offers negligible protection. Do you want to encrypt it two-way or one-way?


one-way


But can you show me 2-way as well :)

If it's one-way, then you would be best off using MessageDigest with SHA1. Practicably uncrackable.

Two-way - see the following (and related links):

http://javaalmanac.com/egs/javax.crypto/DesString.html


do you have an example of messagedigest with sha1 ?
You can use this to give you a hash you can read (but not decrypt) and save in your db:



      public static String getDigest(String s) {
            try {
                  MessageDigest md = MessageDigest.getInstance("SHA1");
                  byte[] bytes = md.digest(s.getBytes());
                  return new BigInteger(1, bytes).toString(16);
            } catch (NoSuchAlgorithmException e) {
                  e.printStackTrace();
            }
            return null;
      }
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial



Cheers

Works much better

:-)