Wednesday, January 26, 2011

How to Read RSA Encrypted File to Encoded Image -Java BlackBerry Develpment

 /**
     * @param path
     * @return encoded base64 string String encodeToBase64(String path)
     * @throws IOException
     * @throws CryptoUnsupportedOperationException 
     * @throws CryptoTokenException 
     * @throws CryptoException 
     */
    public static EncImage encodeToBase64(String path) throws IOException, CryptoException, CryptoTokenException, CryptoUnsupportedOperationException {
    EncImage encImage =  new EncImage();
    FileConnection fileConToRead = null;
    InputStream inputStream=null;


    try {
        fileConToRead = (FileConnection) Connector.open("file://" + path, Connector.READ);
        int size = (int) fileConToRead.fileSize();
        inputStream = fileConToRead.openInputStream();
        byte bytes[] = new byte[size];
        inputStream.read(bytes, 0, size);

        // If RSA enables
        if (Main.isRSAEncrypted) {
        CryptoRSA cryptoRSA = new CryptoRSA();
        bytes = cryptoRSA.decrypt(bytes);
        }
        
        EncodedImage image = EncodedImage.createEncodedImage(bytes, 0, bytes.length);
        encImage.setImageHeight(image.getHeight());
        encImage.setImageWidth(image.getWidth());

        byte encodedBytes[] = Base64.encodeBase64(bytes);
        encImage.setEncodesString(new String(encodedBytes));

    } finally {
        try {
        // try to close the FileConnection
        fileConToRead.close();
        inputStream.close();
        } catch (IOException e) {
        //finally connection assigns to null
        }
        // connection set to null
        fileConToRead = null;
        inputStream=null;

    }
    return encImage;
    }

1 comment: