Simple Encrypter and Decrypter Class

G

Gurunath M.

I am posting a simple Enc and Dec class, which i was googling for a
long time but didnt find.

Hope this will help some one.


import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class EncrypterDecrypter
{

private static final String UNICODE_FORMAT = "UTF8";



public String encrypt( String unencryptedString ) throws
EncryptionException
{
if ( unencryptedString == null || unencryptedString.trim().length()
== 0 )
throw new IllegalArgumentException(
"Unencrypted string cant be null or empty" );

try
{
byte[] keyAsBytes = unencryptedString.getBytes( UNICODE_FORMAT );
BASE64Encoder base64encoder = new BASE64Encoder();
return base64encoder.encode( keyAsBytes );
}
catch (Exception e)
{
throw new EncryptionException( e );
}
}

public String decrypt( String encryptedString ) throws
EncryptionException
{
if ( encryptedString == null || encryptedString.trim().length() <=
0 )
throw new IllegalArgumentException( "Encrypted string cant be null
or empty" );

try
{

BASE64Decoder base64decoder = new BASE64Decoder();

byte[] uncr = base64decoder.decodeBuffer( encryptedString );

return toStr( uncr );
}
catch (Exception e)
{
throw new EncryptionException( e );
}
}

private static String toStr( byte[] bytes )
{
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < bytes.length; i++)
{
stringBuffer.append( (char) bytes );
}
return stringBuffer.toString();
}

public static class EncryptionException extends Exception
{
public EncryptionException( Throwable t )
{
super( t );
}
}

public static void main (String s[]) throws Exception
{
EncrypterDecrypter ed = new EncrypterDecrypter();

if (s.length != 2)
{
log(" Not enough parameters ");
log(" Usage : \n java EncrypterDecrypter 1 <string> \n \t or \n
java EncrypterDecrypter 2 <string> \n \t 1 -> Encryption 2->
Decryption");
System.exit(0);
}

int action = -1;
String str = null;

try
{
action = Integer.parseInt(s[0]);
}
catch(Exception e)
{
log (" Invalid input provided for first param");
System.exit(0);
}

log(" Action to be taken :"+ action);

switch(action)
{
case 1:
String encr = ed.encrypt(s[1]);
log(" Encrypted String "+ s[0]+" is : "+ encr);
break;

case 2:
String decr = ed.decrypt(s[1]);
log(" Decrypted String of "+ s[1]+" is : "+ decr);
break;

case 9:
String enc = ed.encrypt(s[1]);
log(" Encrypted String : "+ enc);
String dec = ed.decrypt(enc);
log(" Decrypted String : "+ dec);
break;

default:
log(" Wrong parameter value passed, please check ... ");
break;

}

}

public static void log(String s)
{
System.out.println(s);
}
}
 
L

Lew

Gurunath said:
I am posting a simple Enc and Dec class, which i [sic] was googling for a
long time but didnt find.


Hope this will help some one.


import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

You shouldn't use sun.* internal packages. There are standard Java API and
Apache Commons classes that will do this. Also, Base64 is not "encryption".

<http://java.sun.com/products/javamail/javadocs/javax/mail/internet/MimeUtility.html>
<http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html>

Please do not use TAB characters to indent Usenet code posts; it makes them
hard to read. Use spaces, a maximum of four per indent level.

Comments and questions (which differ) inline:
public class EncrypterDecrypter
{

private static final String UNICODE_FORMAT = "UTF8";



public String encrypt( String unencryptedString ) throws
EncryptionException
{
if ( unencryptedString == null || unencryptedString.trim().length()
== 0 )

Why would you trim a string slated for encryption?
throw new IllegalArgumentException(
"Unencrypted string cant be null or empty" );

I suggest that spelling be correct in published code's published messages.
try
{
byte[] keyAsBytes = unencryptedString.getBytes( UNICODE_FORMAT );
BASE64Encoder base64encoder = new BASE64Encoder();
return base64encoder.encode( keyAsBytes );
}
catch (Exception e)

Catching 'Exception' is an antipattern here.
{
throw new EncryptionException( e );
}
}

public String decrypt( String encryptedString ) throws
EncryptionException
{
if ( encryptedString == null || encryptedString.trim().length() <=
0 )
throw new IllegalArgumentException( "Encrypted string cant be null
or empty" );

Why declare a checked exception if you aren't going to use it?
try
{

BASE64Decoder base64decoder = new BASE64Decoder();

byte[] uncr = base64decoder.decodeBuffer( encryptedString );

return toStr( uncr );
}
catch (Exception e)
{
throw new EncryptionException( e );
}
}

private static String toStr( byte[] bytes )

You don't control the character encoding, which means that the "encryption"
and "decryption" aren't symmetrical, you go through a lot of trouble to avoid
using the constructor 'String(byte[])', and you use 'StringBuffer' instead of
'StringBuilder', all mistakes.
{
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < bytes.length; i++)
{
stringBuffer.append( (char) bytes );
}
return stringBuffer.toString();
}

public static class EncryptionException extends Exception
{
public EncryptionException( Throwable t )
{
super( t );
}
}

public static void main (String s[]) throws Exception


'main()' never throws a checked exception - why are you declaring that it does?
{
EncrypterDecrypter ed = new EncrypterDecrypter();

if (s.length != 2)
{
log(" Not enough parameters ");

's' could be longer than 2.
log(" Usage : \n java EncrypterDecrypter 1 <string> \n \t or \n
java EncrypterDecrypter 2 <string> \n \t 1 -> Encryption 2->
Decryption");
System.exit(0);
}

int action = -1;
String str = null;

try
{
action = Integer.parseInt(s[0]);
}
catch(Exception e)
{
log (" Invalid input provided for first param");
System.exit(0);
}

log(" Action to be taken :"+ action);

Use of an 'int' for 'action' is not optimal. Use an enum.
switch(action)
{
case 1:
String encr = ed.encrypt(s[1]);
log(" Encrypted String "+ s[0]+" is : "+ encr);
break;

case 2:
String decr = ed.decrypt(s[1]);
log(" Decrypted String of "+ s[1]+" is : "+ decr);
break;

case 9:
String enc = ed.encrypt(s[1]);
log(" Encrypted String : "+ enc);
String dec = ed.decrypt(enc);
log(" Decrypted String : "+ dec);
break;

default:
log(" Wrong parameter value passed, please check ... ");
break;

}

}

public static void log(String s)
{
System.out.println(s);

This isn't logging. There are two standard logging libraries, one from the
Java API and the other from Apache; use one of those.

HTH.
 
R

Roedy Green

I am posting a simple Enc and Dec class, which i was googling for a
long time but didnt find.

Base64 in not an encryptor. It is an armourer. It is trivially easy
for anyone to undo. See http://mindprod.com/jgloss/base64.html

For encryption, you need JCE. see http://mindprod.com/jgloss/jce.html

I have written a very light weight encryption package that uses
public/private key encryption that does not require JCE, so works on
old JDKs too. see http://mindprod.com/products.html#TRANSPORTER
--
Roedy Green Canadian Mind Products
http://mindprod.com

Responsible Development is the style of development I aspire to now. It can be summarized by answering the question, “How would I develop if it were my money?” I’m amazed how many theoretical arguments evaporate when faced with this question.
~ Kent Beck (born: 1961 age: 49) , evangelist for extreme programming.
 
L

Lew

Roedy said:
I have written a very light weight [sic] encryption package that uses
public/private key encryption that does not require JCE, so works on
old JDKs too. see <http://mindprod.com/products.html#TRANSPORTER>

They'd have to be pretty darned old! JCE came in with Java 1.4, over
eight years and two obsolescent Java versions ago.

That in no wise diminishes the contribution or value of Roedy's
library. One might even prefer it when using less hoary versions of
Java.
 
R

Roedy Green

There are
1001 free implementations of Base64 out there.

see http://mindprod.com/jgloss/base64.html for some of them.

I wrote one myself.

I have not run across any comparison of their speed or quality.
--
Roedy Green Canadian Mind Products
http://mindprod.com

Responsible Development is the style of development I aspire to now. It can be summarized by answering the question, “How would I develop if it were my money?” I’m amazed how many theoretical arguments evaporate when faced with this question.
~ Kent Beck (born: 1961 age: 49) , evangelist for extreme programming.
 
A

Arne Vajhøj

Roedy said:
I have written a very light weight [sic] encryption package that uses
public/private key encryption that does not require JCE, so works on
old JDKs too. see<http://mindprod.com/products.html#TRANSPORTER>

They'd have to be pretty darned old! JCE came in with Java 1.4, over
eight years and two obsolescent Java versions ago.

JCE was available as a separate download for 1.3.1, so no JCE means
10 years old.

Arne
 
R

Roedy Green

Also, you appear to encrypt messages by blocks with RSA, with ECB
chaining, aka "no chaining at all". This combines the weaknesses of
ill-used symmetric ciphers with the slowness and waste of space of RSA.
If you used a symmetric encryption with RC4, with a random secret key
which is then ecrypted with RSA, then you would have something much
stronger, faster, with more compact messages, and it would not use more
code.

I did this a long time ago to get an understanding of how
public/private key encryption worked probably before JCE came out or
at least before it was bundled. I intended it for short messages,
such as a credit card number so I was not too worried about speed or
fluffiness.

That is why I did not use a more complex hybrid of RSA and symmetric
ciphers. Key generation is very slow. For short messages, my scheme is
thus faster since it does not need to generate a session key.

Someone might use the Transporter today because they can control all
the code. JCE is a large, complex black box you are just supposed to
trust. How do you know JCE does not contain deliberate trap doors put
there at the insistence of the Homeland security people?

Your knowledge is considerably better than mine. I would have to
research a fair bit to even understand what you are asking me to do. I
have so many projects in my queue just now, I would not get to that
one for years. If you would like to fix it, I would be happy to
publish it.


--
Roedy Green Canadian Mind Products
http://mindprod.com

Don’t worry about people stealing an idea; if it’s original, you’ll have to shove it down their throats.
~ Howard Aiken (born: 1900-03-08 died: 1973-03-14 at age: 73)
 
M

Mike Amling

Roedy said:
I did this a long time ago to get an understanding of how
public/private key encryption worked probably before JCE came out or
at least before it was bundled. I intended it for short messages,
such as a credit card number so I was not too worried about speed or
fluffiness.
...
Your knowledge is considerably better than mine. I would have to
research a fair bit to even understand what you are asking me to do. I
have so many projects in my queue just now, I would not get to that
one for years. If you would like to fix it, I would be happy to
publish it.

Thomas Pornin is right. I would go further, and suggest using AES and
one of the good modes. And ECC has some advantages over RSA, one of
which is that once the parameters are set up, generating public/private
key pairs is must faster.
Just telling people "see
http://mindprod.com/products.html#TRANSPORTER" with no caveats about its
weaknesses only encourages bad security.
I also wrote open-source encryption code in Java. I dare say it's
more sophisticated than yours. But I don't publicize it to people who
may not be able to appreciate the conditions under which it can be used
securely.

--Mike Amling
 
R

Roedy Green

The point is that publishing some crypto code without any warning about
its potential weaknesses has a high potential for being harmful. That's
the problem with cryptography: you cannot test the security. Even if it
compiles and runs, you cannot know whether it is weak or not. I suggest
adding a "warning" section on the subject.

There are a number of warnings in the file transporter.use.

I have added this paragraph:

Design Philosophy

A major concern for anyone using any form of encryption is trusting
the author not to hide any trap doors in the code to snoop. He also
has to trust government and military experts not to withhold some
secret technique to crack a proffered encryption algorithm or
information about their advanced hardware abilities to crack codes
(e.G. some sort of quantum cracking). The problem is modern
cryptography is highly complex. What I have done is pare the
encryption logic down to the bone so that it would be simple enough
for the average Java programmer to understand line by line, and ensure
himself the program does exactly what it claims to. I used the
mathematically Spartan RSA algorithm. This means the program is
missing features like hybrid symmetric key, AES and chaining that
would have increased its speed and resistance to cracking. I have
also posted the source for anyone to examine. There are thus more
eyes looking for anything improper, possibly accidental. To verify my
code, you would also want to verify Java's secret key generator. If
in any way it were not secure, the whole encryption scheme would be a
house of cards. If you are a diplomat and need 100% unreachably, you
should probably not be using commercial software. Your people should
write your own one-time-pad software. The Soviets used a one-time
paper one time pad system successfully for years.

see http://mindprod.com/project/uncrackableencryption.html
 
A

Arne Vajhøj

The proper place is in the product where it could stay up date.

I think most users would prefer that the "This is really useless
for serious use" disclaimer on the download page not something
that they may or may not dig out after download.

And there are really no update problem. An unsafe encryption
solution will never become safe by magic.

And if you do a new implementation, then that should not be
mixed up with the old one anyway.

Arne
 
A

Arne Vajhøj

This is not sensible. The NSA suggested changes to DES and SHA-0
which were later found to block certain attacks not publicly known at
the time, but obviously known to the NSA. Similarly GCHQ were aware
of public key cryptography before it became publicly known.

If Govenment security agencies know something they will keep it close
to their chests until it becomes publicly known.

True.

And in any way it is completely pointless.

What NSA may and may not know should not have any impact
on the choice of algorithm, because you can only act based
on information that you have.

Arne
 
A

Arne Vajhøj

There are a number of warnings in the file transporter.use.

I have added this paragraph:

Design Philosophy

A major concern for anyone using any form of encryption is trusting
the author not to hide any trap doors in the code to snoop. He also
has to trust government and military experts not to withhold some
secret technique to crack a proffered encryption algorithm or
information about their advanced hardware abilities to crack codes
(e.G. some sort of quantum cracking). The problem is modern
cryptography is highly complex. What I have done is pare the
encryption logic down to the bone so that it would be simple enough
for the average Java programmer to understand line by line, and ensure
himself the program does exactly what it claims to. I used the
mathematically Spartan RSA algorithm. This means the program is
missing features like hybrid symmetric key, AES and chaining that
would have increased its speed and resistance to cracking. I have
also posted the source for anyone to examine. There are thus more
eyes looking for anything improper, possibly accidental. To verify my
code, you would also want to verify Java's secret key generator. If
in any way it were not secure, the whole encryption scheme would be a
house of cards. If you are a diplomat and need 100% unreachably, you
should probably not be using commercial software. Your people should
write your own one-time-pad software. The Soviets used a one-time
paper one time pad system successfully for years.

see http://mindprod.com/project/uncrackableencryption.html

Crap.

It does not really emphasize the point that the users are better
off using standard stuff from JCE than your stuff.

And all the military/diplomat stuff is irrelevant.

Arne
 
R

Roedy Green

This is not sensible. The NSA suggested changes to DES and SHA-0
which were later found to block certain attacks not publicly known at
the time, but obviously known to the NSA. Similarly GCHQ were aware
of public key cryptography before it became publicly known.

If Govenment security agencies know something they will keep it close
to their chests until it becomes publicly known.

I am saying you MUST trust your toolmaker if you use their tools. I am
not saying it is foolish to trust. Creating your own tools creates its
own set of serious problems.

On the other paw, you can make fairly accurate estimates on how
difficult it is to crack a given algorithm with a certain technology,
but you are just guessing at how safe it is to trust some organisation
including its ability to block infiltration. You are also just
guessing on what secret and advanced technology those with very large
budgets have.

The actual threat is probably less than perceived for direct attacks
and lower than perceived for betrayal.

Use of open source is probably the best approach. Even if you don't
detect the back door, or inadvertent/deliberate flaw, there is a good
chance someone else will.

If you were the US military, or the US government, would it not make
sense to offer tools that appeared secure but that allowed you to read
everyone else's messages. There is certainly motivation to do that.
They have even done that explicitly and openly in past.
 
A

Arne Vajhøj

I am saying you MUST trust your toolmaker if you use their tools.

Not really.

Good encryption stuff uses public known algorithms that have been
reviewed by researchers worldwide.

And implementation can (read: should) be available in source form
for review by developers worldwide.
Use of open source is probably the best approach. Even if you don't
detect the back door, or inadvertent/deliberate flaw, there is a good
chance someone else will.

If you were the US military, or the US government, would it not make
sense to offer tools that appeared secure but that allowed you to read
everyone else's messages. There is certainly motivation to do that.
They have even done that explicitly and openly in past.

Reference?

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top