Encrypting Files in Local Storage

294 views
Skip to first unread message

savneet.em...@gmail.com

unread,
May 8, 2014, 1:48:06 AM5/8/14
to codenameone...@googlegroups.com
Hi,

I hope this is a quick and painless question.

I am building an app that needs to encrypt and decrypt files in local storage using AES 256 or higher or RSA.  I have read all of the posts in this forum and everything I could find elsewhere via Google.  It seems that the recommended approach for encryption is to use a BouncyCastle plugin that was specifically customized for CodenameOne projects and which is available as either a source code or binary download.  There are code samples on BouncyCastle's Website and elsewhere.  But, I have yet to find one that shows an simple example that will work in CodenameOne projects.  Some of the BouncyCastle "examples" don't use BouncyCastle's packages at all but rely instead on Java packages that are not available in CodenameOne projects such as java.Security.  Other examples use BouncyCastle classes but still include packages that are not available in CodenameOne projects.

The following two links have encryption and decryption code samples that are probably close to what I need.  But, I am not sure how to modify them.


Here's the code copied from the first link.  Notice that it is using java.io packages and java.security which are not available in CodenameOne.  Any assistance you can provide in adapting this or some other example would be greatly appreciated.

package com.as400samplecode;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.security.Security;
 
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.util.PublicKeyFactory;
 
import sun.misc.BASE64Decoder;
 
public class RSAEncryptFile {
 
    public static void main(String[] args)
    {
 
        String publicKeyFilename = null;
        String inputFilename = null;
        String encryptedFilename = null;
 
        RSAEncryptFile rsaEncryptFile = new RSAEncryptFile();
 
        if (args.length < 3)
        {
            System.err.println("Usage: java "+ rsaEncryptFile.getClass().getName()+
            " Public_Key_Filename Input_Filename Encrypted_Filename");
            System.exit(1);
        }
 
        publicKeyFilename = args[0].trim();
        inputFilename = args[1].trim();
        encryptedFilename = args[2].trim();
        rsaEncryptFile.encrypt(publicKeyFilename, inputFilename, encryptedFilename);
 
    }
 
    private void encrypt (String publicKeyFilename, String inputFilename, String encryptedFilename){
 
        try {
 
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
 
            String value = "";
            String key = readFileAsString(publicKeyFilename);
            BASE64Decoder b64 = new BASE64Decoder();
            AsymmetricKeyParameter publicKey =
                (AsymmetricKeyParameter) PublicKeyFactory.createKey(b64.decodeBuffer(key));
            AsymmetricBlockCipher e = new RSAEngine();
            e = new org.bouncycastle.crypto.encodings.PKCS1Encoding(e);
            e.init(true, publicKey);
 
            String inputdata = readFileAsString(inputFilename);
            byte[] messageBytes = inputdata.getBytes();
            int i = 0;
            int len = e.getInputBlockSize();
            while (i < messageBytes.length)
            {
                if (i + len > messageBytes.length)
                    len = messageBytes.length - i;
 
                byte[] hexEncodedCipher = e.processBlock(messageBytes, i, len);
                value = value + getHexString(hexEncodedCipher);
                i += e.getInputBlockSize();
            }
 
            System.out.println(value);
            BufferedWriter out = new BufferedWriter(new FileWriter(encryptedFilename));
            out.write(value);
            out.close();
            
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
 
    public static String getHexString(byte[] b) throws Exception {
        String result = "";
        for (int i=0; i < b.length; i++) {
            result +=
                Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
        }
        return result;
    }
 
    private static String readFileAsString(String filePath)
    throws java.io.IOException{
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(
                new FileReader(filePath));
        char[] buf = new char[1024];
        int numRead=0;
        while((numRead=reader.read(buf)) != -1){
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            buf = new char[1024];
        }
        reader.close();
        System.out.println(fileData.toString());
        return fileData.toString();
    }
 
}

Shai Almog

unread,
May 8, 2014, 2:11:28 AM5/8/14
to codenameone...@googlegroups.com, savneet.em...@gmail.com
Hi,
you should look at the bouncy castle J2ME samples which is what we used to build the version of BC. I don't have any RSA encryption code lying around here but I know some community members dealt with it so maybe someone has sample code for this.

Savneet S

unread,
May 8, 2014, 7:45:14 AM5/8/14
to Shai Almog, codenameone...@googlegroups.com
Thanks, Shai.

Can any rock star in the community provide a complete basic example of J2ME file encryption an decryption using bouncy castle or any other workable method? I have not been able to find one.

Ikenna Iloeje

unread,
May 19, 2014, 3:00:55 AM5/19/14
to codenameone...@googlegroups.com, savneet.em...@gmail.com
Hello, i also have need for encrypting json string sent to my php server from my CN1 app. Please can anyone provide a simple example for encrypting the json string i am sending to server? Simple string encryption and decryption example, please?

Chen Fishbein

unread,
May 19, 2014, 2:24:59 PM5/19/14
to codenameone...@googlegroups.com, savneet.em...@gmail.com

dan.s...@thrivemetrics.com

unread,
May 20, 2014, 12:02:14 AM5/20/14
to codenameone...@googlegroups.com, savneet.em...@gmail.com
Please see two attachments.

Note that the special character in the test input string correctly gets converted back to the same value and doesn't get turned into some other character.
Encryptor.java
EncryptionTest.java
Reply all
Reply to author
Forward
0 new messages