views:

2898

answers:

7

What I need is to encrypt string which will show up in 2D barcode (PDF-417) so when someone get an idea to scan it will get nothing readable.

Other requirements are - that should not be complicated, it would not consist of RSA, PKI infrstructure, key pairs etc. It must be simple enough to get rid off of the people snooping arround, and easy for decrypt for other companies interrested in getting that data. They call us, we tell them the standard or give them some simple key which than can be used for decryption.

Probably those companies could use different technologies so it would be good to stick to some standard which is not tied to some special platform or technology.

What do you suggest? Is there some java class doing encrypt() decrypt() without much complication in achieving high security standards ?

A: 

Increment all characters in the string by one.

Thorbjørn Ravn Andersen
+2  A: 

Here are some links you can read what Java supports

Encrypting/decrypting a data stream.

This example demonstrates how to encrypt (using a symmetric encryption algorithm such as AES, Blowfish, RC2, 3DES, etc) a large amount of data. The data is passed in chunks to one of the encrypt methods: EncryptBytes, EncryptString, EncryptBytesENC, or EncryptStringENC. (The method name indicates the type of input (string or byte array) and the return type (encoded string or byte array). The FirstChunk and LastChunk properties are used to indicate whether a chunk is the first, middle, or last in a stream to be encrypted. By default, both FirstChunk and LastChunk equal true -- meaning that the data passed is the entire amount.

JCERefGuide

Java Encryption Examples

Markus Lausberg
+1  A: 

Affine ciphers seem strong enough to deter a casual hacker but simple enough to implement.

http://en.wikipedia.org/wiki/Affine_cipher

Jeremy Powell
+1  A: 

If the string is simple enough, you can try a simple Base64 encoding/decoding scheme. I'm sure there's an implementation of this out there somewhere for free use.

Yuval
Base64 encoding is not encryption, its also easy to spot that it is base64.
Rich Seller
True, but for the simplest of cases (and encoding a string into a barcode certainly falls into this category) it can be a simple and useful method. I hardly think, and I believe the asker meant this too, that heavy-weight encryption is needed here.
Yuval
yes... no need for heavy-weight encryption. I think that first XOR-ing and then Base64 on text would be good enough.
ante.sabo
+3  A: 

I'd recommend to use some standard symmetric cypher that is widely available like DES, 3DES or AES. While that is not the most secure algorithm, there are loads of implementations and you'd just need to gibe the key to anyone that is supposed to decrypt the information in the barcode. javax.crypto.Cipher is what you want to work with here.

Let's assume the bytes to encrypt are in

bytes[] input;

Next, you'll nees key and initialization vector bytes byte[] keyBytes; byte[] ivBytes;

Now you can initialize the Cipher for the algorithm that you select...

// wrap key data in Key/IV specs to pass to cipher
SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
// create the cipher with the algorithm you choose
// see javadoc for Cipher class for more info, e.g.
Cipher cipher = Cipher.newInstance("DES/CBC/PKCS5Padding");

Encryption would go like this

cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
byte[] encypted = new byte[cipher.getOutputSize(input.length)];
int enc_len = cipher.update(input, 0, input.length, encypted, 0);
enc_len += cipher.doFinal(encypted, enc_len);

... and decryption like this

cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte[] decrypted = new byte[cipher.getOutputSize(enc_len)];
int dec_len = cipher.update(encrypted, 0, enc_len, decrypted, 0);
dec_len += cipher.doFinal(decrypted, dec_len);
VoidPointer
A: 

ok, here is the code I will use. Please advice if you consider it not to be ok for some reason. I am using Sun's Base64Encoder/Decoder which is to be found in Sun's JRE, to avoid yet another JAR in lib. That's dangerous from point of using OpenJDK or some other's JRE. Besides that, is there another reason I should consider using Apache commons lib with Encoder/Decoder?

public class EncryptUtils {
   public static final String DEFAULT_ENCODING="UTF-8"; 
   static BASE64Encoder enc=new BASE64Encoder();
   static BASE64Decoder dec=new BASE64Decoder();

   public static String base64encode(String text){
      try {
         String rez = enc.encode( text.getBytes( DEFAULT_ENCODING ) );
         return rez;         
      }
      catch ( UnsupportedEncodingException e ) {
         return null;
      }
   }//base64encode

   public static String base64decode(String text){

         try {
            return new String(dec.decodeBuffer( text ),DEFAULT_ENCODING);
         }
         catch ( IOException e ) {
           return null;
         }

      }//base64decode

      public static void main(String[] args){
       String txt="some text to be encrypted" ;
       String key="key phrase used for XOR-ing";
       System.out.println(txt+" XOR-ed to: "+(txt=xorMessage( txt, key )));
       String encoded=base64encode( txt );       
       System.out.println( " is encoded to: "+encoded+" and that is decoding to: "+ (txt=base64decode( encoded )));
       System.out.print( "XOR-ing back to original: "+xorMessage( txt, key ) );

      }

      public static String xorMessage(String message, String key){
       try {
          if (message==null || key==null ) return null;

         char[] keys=key.toCharArray();
         char[] mesg=message.toCharArray();

         int ml=mesg.length;
         int kl=keys.length;
         char[] newmsg=new char[ml];

         for (int i=0; i<ml; i++){
            newmsg[i]=(char)(mesg[i]^keys[i%kl]);
         }//for i
         mesg=null; keys=null;
         return new String(newmsg);
      }
      catch ( Exception e ) {
         return null;
       }  
      }//xorMessage

}//class
ante.sabo
A: 

thanks ive made this class using your code maybe someone finds it userfull

object crypter

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


public class ObjectCrypter {

private Cipher deCipher;
private Cipher enCipher;
private SecretKeySpec key;
private IvParameterSpec ivSpec;


public ObjectCrypter(byte[] keyBytes,   byte[] ivBytes) {
    // wrap key data in Key/IV specs to pass to cipher


     ivSpec = new IvParameterSpec(ivBytes);
    // create the cipher with the algorithm you choose
    // see javadoc for Cipher class for more info, e.g.
    try {
         DESKeySpec dkey = new  DESKeySpec(keyBytes);
          key = new SecretKeySpec(dkey.getKey(), "DES");
         deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
         enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
public byte[] encrypt(Object obj) throws InvalidKeyException, InvalidAlgorithmParameterException, IOException, IllegalBlockSizeException, ShortBufferException, BadPaddingException {
    byte[] input = convertToByteArray(obj);
    enCipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);

    return enCipher.doFinal(input);




//  cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
//  byte[] encypted = new byte[cipher.getOutputSize(input.length)];
//  int enc_len = cipher.update(input, 0, input.length, encypted, 0);
//  enc_len += cipher.doFinal(encypted, enc_len);
//  return encypted;


}
public Object decrypt( byte[]  encrypted) throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException, ClassNotFoundException {
    deCipher.init(Cipher.DECRYPT_MODE, key, ivSpec);

    return convertFromByteArray(deCipher.doFinal(encrypted));

}



private Object convertFromByteArray(byte[] byteObject) throws IOException,
        ClassNotFoundException {
    ByteArrayInputStream bais;

    ObjectInputStream in;
    bais = new ByteArrayInputStream(byteObject);
    in = new ObjectInputStream(bais);
    Object o = in.readObject();
    in.close();
    return o;

}



private byte[] convertToByteArray(Object complexObject) throws IOException {
    ByteArrayOutputStream baos;

    ObjectOutputStream out;

    baos = new ByteArrayOutputStream();

    out = new ObjectOutputStream(baos);

    out.writeObject(complexObject);

    out.close();

    return baos.toByteArray();

}


}
sherif