How to encrypt and decrypt data using Advanced Encryption Standard(AES) Java BlackBerry Pragramming

sample code provides information on how to encrypt and decrypt data using the most common symmetric key algorithm, Advanced Encryption Standard


package com.DataStore;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javacard.security.CryptoException;
import net.rim.device.api.crypto.AESDecryptorEngine;
import net.rim.device.api.crypto.AESEncryptorEngine;
import net.rim.device.api.crypto.AESKey;
import net.rim.device.api.crypto.BlockDecryptor;
import net.rim.device.api.crypto.BlockEncryptor;
import net.rim.device.api.crypto.CryptoTokenException;
import net.rim.device.api.crypto.CryptoUnsupportedOperationException;
import net.rim.device.api.crypto.PKCS5FormatterEngine;
import net.rim.device.api.crypto.PKCS5UnformatterEngine;
import net.rim.device.api.crypto.RandomSource;
import net.rim.device.api.crypto.SHA1Digest;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.util.Arrays;
import net.rim.device.api.util.DataBuffer;

public class CryptoRSA {

    private String keyMessage = "Data sent between a BlackBerry device and the BlackBerry Enterprise Server is encrypted using Triple DES (Date Encryption Standard) or AES (Advanced Encrption Standard). This is performed automatically and does not require application implementation to use it.There are cases where encrypting data can be required, such as secure communication with an external application using the BlackBerry Mobile Data Server. Communication between the BlackBerry and BlackBerry Mobile Data Server would be automatically encrypted but communication between the BlackBerry Mobile Data Server and an application server would not unless implemented in the BlackBerry application.";

    public byte[] encrypt(byte[] data ) throws CryptoException, IOException, CryptoTokenException, CryptoUnsupportedOperationException
    {
    AESKey key = new AESKey( keyMessage.getBytes() );
    // Now, we want to encrypt the data.
    // First, create the encryptor engine that we use for the actual
    AESEncryptorEngine engine = new AESEncryptorEngine( key );

    // Since we cannot guarantee that the data will be of an equal block
    // length we want to use a padding engine (PKCS5 in this case).
    PKCS5FormatterEngine fengine = new PKCS5FormatterEngine( engine );

    // Create a BlockEncryptor to hide the engine details away.
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    BlockEncryptor encryptor = new BlockEncryptor( fengine, output );

    // Now we need to do is write our data to the output stream.
    // But before doing so, let's calculate a hash on the data as well.
    // A digest provides a one way hash function to map a large amount
    // of data to a unique 20 byte value (in the case of SHA1).
    SHA1Digest digest = new SHA1Digest();
    digest.update( data );
    byte[] hash = digest.getDigest();
    // Now, write out all of the data and the hash to ensure that the
    // data was not modified in transit.
    encryptor.write( data );
    encryptor.write( hash );
    encryptor.close();
    output.close();

    // Now, the encrypted data is sitting in the ByteArrayOutputStream.
    // We simply want to retrieve it.
    return output.toByteArray();
    }

    public byte[] decrypt(byte[] ciphertext ) throws CryptoException, IOException, CryptoTokenException, CryptoUnsupportedOperationException
    {
    // First, create the AESKey again.
    AESKey key = new AESKey( keyMessage.getBytes() );

    // Now, create the decryptor engine.
    AESDecryptorEngine engine = new AESDecryptorEngine( key );
    // Since we cannot guarantee that the data will be of an equal block length
    // we want to use a padding engine (PKCS5 in this case).
    PKCS5UnformatterEngine uengine = new PKCS5UnformatterEngine( engine );

    // Create the BlockDecryptor to hide the decryption details away.
    ByteArrayInputStream input = new ByteArrayInputStream( ciphertext );
    BlockDecryptor decryptor = new BlockDecryptor( uengine, input );

    // Now, read in the data. Remember that the last bytes represent
    // the SHA1 hash of the decrypted data.
    byte[] temp = new byte[ 100 ];
    DataBuffer buffer = new DataBuffer();

    for( ;; ) {
        int bytesRead = decryptor.read( temp );
        buffer.write( temp, 0, bytesRead );

        if( bytesRead < 100 ) {
        // We ran out of data.
        break;
        }
    }

    byte[] plaintextAndHash = buffer.getArray();
    int plaintextLength = plaintextAndHash.length - SHA1Digest.DIGEST_LENGTH;
    byte[] plaintext = new byte[ plaintextLength ];

    System.arraycopy( plaintextAndHash, 0, plaintext, 0, plaintextLength );
   
    return plaintext;
    }
}

How to use PersistentStore to store objects in BlackBerry Java programming

Here in this post we will see how to store customer data using PersistentStore.
In my DataObject class used to store customer data. it has 2 parameters customer ID and some string property it may be name address or any other parameter. Also you can change those parameters according to your requirements. we are suing vector to store those pairs in runtime. Hope this will useful for you
============================================
package com.DataStore;

import java.util.Vector;
import net.rim.device.api.util.Persistable;

public final class DataObject implements Persistable
{

    private Vector elements;
    public static final int CLIENT_ID = 0;

    public DataObject()
    {
    elements = new Vector(1);
    int capacity = elements.capacity();
    for (int i = 0; i < capacity; ++i)
    {
        elements.addElement(new String(""));
    }
    }

    /**
     * @param id
     * @return String
     * String getElement(int id)
     */
    public String getElement(int id)
    {
    return (String) elements.elementAt(id);
    }

    public void setElement(int id, String value)
    {
    elements.setElementAt(value, id);
    }
}

==============================================
package com.DataStore;

import java.util.Vector;

import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
public class DataHandler {

    private static Vector data;
    private static PersistentObject store;

    static
    {
    store =    PersistentStore.getPersistentObject(1);

    synchronized (store) {
        if (store.getContents() == null) {
        store.setContents(new Vector());
        store.commit();
        }
    }

    data = (Vector) store.getContents();

    }

    /**
     * @param info
     * static void saveObject(DataObject info)
     */
    public static void saveObject(DataObject info)
    {
    data.addElement(info);
    synchronized (store) {
        store.setContents(data);
        store.commit();
    }
    }

    /**
     * @return String
     * static String getClient()
     */
    public static String getClient() {

    synchronized (store) {
        data = (Vector) store.getContents();
        if (!data.isEmpty()) {
        DataObject info = (DataObject) data.lastElement();
        return info.getElement(DataObject.CLIENT_ID);
        }
        else
        {
        //If data is empty here we return empty string
        return "";
        }
    }
    }
}

Simplest way to Display Pregressing bar - BlackBerry Java programming

You can create the instance of the  ProgressBar and you can pass the time out and display messages to progressing bar.

import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.GaugeField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.DialogFieldManager;
import net.rim.device.api.ui.container.PopupScreen;

public class ProgressBar extends Thread 
{
    private int maximum, timeout;
    private boolean useful;
    private PopupScreen popup;
    private GaugeField gaugeField;
    public ProgressBar(String title, int maximum, int timeout)
    {
        this.maximum = maximum;
        this.timeout = timeout;
        DialogFieldManager manager = new DialogFieldManager();
        popup = new PopupScreen(manager);
        gaugeField = new GaugeField(null, 1, maximum, 1, GaugeField.NO_TEXT);
        manager.addCustomField(new LabelField(title));
        manager.addCustomField(gaugeField);
    }

    public void run() 
    {
        useful = true;
        UiApplication.getUiApplication().invokeLater(new Runnable() 
        {
            public void run() 
            {
                UiApplication.getUiApplication().pushScreen(popup);
               
            }
        });

        int iterations = 0;
        while (useful)
        {
            try 
            {
                Thread.sleep(timeout);
            } 
            catch (Exception e) 
            {
               
            }
            if (++iterations > maximum)
            {
                useful =false;
                UiApplication.getUiApplication().invokeLater(new Runnable() 
                {
                    public void run() 
                    {
                        Dialog.alert("Successfully  Completed");
                         System.exit(0);
                    }
                });
               
                iterations = 1;
            }
            gaugeField.setValue(iterations);
        }

        if (popup.isDisplayed()) 
        {
            UiApplication.getUiApplication().invokeLater(new Runnable() 
            {
                public void run() 
                {
                    UiApplication.getUiApplication().popScreen(popup);
                }
            });
        }
    }

    public synchronized void remove() 
    {
        useful = false;
    }
}

How to do POSTRequest (in a secured way) in BlackBerry Mobile device

If you need to do a secured post operation with server we can use Authentication token from the server side that obtained when we log into system. And do the server side implementation to check the authentication token per each request coming from the user(client). Its better if we can delete that token periodically. And ask user to re login if that key is expired.Here in this post i will show how to send request with the authentication token. Remember that we need to set APN unless we configured device properly. Here is the separate post on how to Get APN key without worrying about the service provider that we used(Which contains most of service providers in united states and Canada). If you operator not available there add it following format. Later i will add server side code also.

<MCC,MNC>APN-KEY</MCC,MNC>
Here is the example
<310,160>wap.voicestream.com</310,160>

Here is the code for process post request to server


/**
     * @param serviceUrl
     * @param authToken
     * @param requestData
     * @return String
     * @throws IOException
     * @throws ServerException
     * static String processPOSTRequest(String serviceUrl,String authToken, String requestData)
     */
    public static String processPOSTRequest(String serviceUrl,String authToken, String requestData) throws IOException,ServerException {

    HttpConnection httpConnection = null;
    OutputStream streamOutput = null;
    InputStream inputStream = null;
    StringBuffer strBuffer = new StringBuffer();
    String response = "";

    try {
 //Here getAPN() method gives you APN key for particular network operator
 //I have written separate blog post on getting APN key for any operator
        httpConnection = (HttpConnection) Connector.open(serviceUrl.concat(getAPN()), Connector.READ_WRITE);
        httpConnection.setRequestMethod(HttpConnection.POST);
        httpConnection.setRequestProperty("Content-Length", Integer.toString(requestData.length()));
        httpConnection.setRequestProperty("Content-Type", "text/xml");
        if (authToken.length() > 0) {
        httpConnection.setRequestProperty("Authorization",Base64OutputStream.encodeAsString(authToken
                .getBytes("UTF-8"), 0, authToken
                .getBytes("UTF-8").length, false, false));
        }
        streamOutput = httpConnection.openOutputStream();

        streamOutput.write(requestData.getBytes(), 0, requestData
            .getBytes().length);
        streamOutput.flush();

        int responseCode = httpConnection.getResponseCode();

        if (responseCode != 200) {
        ServerException getErrorExceptions = new ServerException(
            responseCode, httpConnection.getResponseMessage());
        throw getErrorExceptions;
        }

        inputStream = httpConnection.openInputStream();

        int character;

        while (-1 != (character = inputStream.read())) {
        strBuffer.append((char) character);
        }

        response =  strBuffer.toString();

    } finally {
        try {
        streamOutput.close();
        inputStream.close();
        httpConnection.close();
        } catch (Exception e) {
        //not related to user error if this exception happens due to
        //unavailability then connection assigns to null and then implicitly removes it
        }
        httpConnection = null;
        inputStream = null;
        streamOutput = null;
    }

    return response;
    }

How to detect transparent pixel in java and how change transparent pixels

In images we represent each pixel represent by 32 bits.Bit assignment is doing as follows. Normally in Buffered images if we used type TYPE_INT_ARGB we do this way.See the image shown below.

 

So you can see if we need to detect alpha part we have to consider bits 31 to 24 so we need to shift right side by 24 bits then color related bits will go out. Then we will have only Alpha bits at location 7 to 0 then we will do and operation with 0xFF (that means 11111111) so we will get only 0 to 7 bits.
Same way you can use to detect red ,blue and green components by shifting 0,8,16.

Next we will see how we can do this by programme using java language.Here below you can see how to load gif transparent image and how to store it after modification to transparent pixels.
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

public class test {
    public static void main() {
        // Get Image
        ImageIcon icon = new ImageIcon("/home/sanjeewa/Desktop/xparent.gif");
        Image image = icon.getImage();
        // Create empty BufferedImage, sized to Image
        BufferedImage buffImage =
                new BufferedImage(
                        image.getWidth(null),
                        image.getHeight(null),
                        BufferedImage.TYPE_INT_ARGB);
        Graphics g = buffImage.createGraphics();
        g.drawImage(image, 0, 0, null);
        //Dispose the Graphics
        g.dispose();
        //Here 2 for loops used for iterate through each and every pixel in image
        for (int i = 0; i < buffImage.getWidth(); i++) {
            for (int j = 0; j < buffImage.getHeight(); j++) {
                //signed bit shift right
                /*
                How to extract different color components
                blue = pix & 0xFF;
                green = (pix>>8) & 0xFF;
                red = (pix>>16) & 0xFF;
                alpha = (pix>>24) & 0xFF;
                 */
                int alpha = (buffImage.getRGB(i, j) >> 24) & 0xff;
                if (alpha == 0) {
                   //Now we will have pixel with Alpha 0 (Transparent pixel)
                   //As example If you need to fill transparent pixels with white color
                   //use this code 
                   //buffImage.setRGB(i, j, Color.white.getRGB());
                   buffImage.setRGB(i, j, 0);
                } else {

                }
            }
        }
        try {
             //Write back modified file to file system
            String file_name = "/home/sanjeewa/Desktop/sss.png";
            File file = new File(file_name);
            ImageIO.write(buffImage, "png", file);
        } catch (Exception e) {
        }
    }
}

How to do Load test against web service - Using java bench

write web service  and upload it to some web server

Then generate wsdl by type address as follows
http://appserver.cloud-test.wso2.com:9766/services/t/yyy.yyy/testB?wsdl

use soapui to generate soap message
Create new project and give wsdl to it





Then
get the request text
Copy it into request.xml file located inside the folder jababench folder

Then use the following command in command line to execute

java -jar benchmark.jar -p request.xml -n 100 -c 10 -k -H "SOAPAction: readResource" -T "text/xml; charset=UTF-8" http://appserver.cloud-test.wso2.com:9766/services/t/yyy.yyy/testB

usage: HttpBenchmark [options] [http://]hostname[:port]/path
-v Set verbosity level - 4 and above prints response
content, 3 and above prints information on headers, 2 and above prints
response codes (404, 200, etc.), 1 and above prints warnings and info.
-H
Add arbitrary header line, eg. 'Accept-Encoding:
gzip' inserted after all normal header lines. (repeatable)
-n Number of requests to perform for the benchmarking
session. The default is to just perform a single request which usually
leads to non-representative benchmarking results.
-T Content-type header to use for POST data.
-c Concurrency while performing the benchmarking
session. The default is to just use a single thread/client.
-h Display usage information.
-i Do HEAD requests instead of GET.
-k Enable the HTTP KeepAlive feature, i.e., perform
multiple requests within one HTTP session. Default is no KeepAlive
-p File containing data to POST.

here
http://appserver.cloud-test.wso2.com:9766/services/t/yyy.yyy/testB is my service endpoint
SOAPAction: readResource is my operation name
inside wsdl you will find operation name=readResource
here we used soap 1.1 wsdl then we must use -T "text/xml

then run your test
you will see following output









How to write xsd file (Enrich mediator) and use it with eclipse IDE

In general, a schema is an abstract representation of an object's characteristics and relationship. XSD specifies how to formally describe the elements in an Extensible Markup Language (XML) document.
Here i will briefly describe how to write simple XSD and use it with eclipse ide.

first we will consider simple xml file

<enrich xmlns:p="http://ws.apache.org/ns/synapse" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<p:source clone="false" type="custom" xpath="/default/xpath"/>
<p:target action="replace" type="custom" xpath="/default/xpath"/>
</p:enrich>

Here is the XSd file to describe that XML file. Save this file as enrich.xsd

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
           targetNamespace="http://ws.apache.org/ns/synapse"
           xmlns="http://ws.apache.org/ns/synapse">
<xs:element name="enrich">
    <xs:complexType>
        <xs:sequence>       
    <xs:element name="source">
        <xs:annotation>
            <xs:documentation source="description">
                Source Configuration
            </xs:documentation>
        </xs:annotation>
                <xs:complexType>         
                    <xs:attribute name="clone" minOccurs="1" maxOccurs="1">
                        <xs:annotation>
                        <xs:documentation>
                             Weather message can be cloned or use as a reference during the enriching
                         </xs:documentation>
                        </xs:annotation>
                        <xs:restriction base="xs:string">
                     <xs:enumeration value="true"/>
                    <xs:enumeration value="false"/>
                 </xs:restriction>
                         </xs:attribute>
             <xs:attribute name="type" minOccurs="1" maxOccurs="1">
                         <xs:annotation>
                         <xs:documentation>
                            Type that the mediator use from the original message to enrich the modified message that pass through the mediator
                         </xs:documentation>
                         </xs:annotation>
                 <xs:restriction base="xs:string">
             <xs:enumeration value="custom"/>
                         <xs:enumeration value="envelope"/>
                        <xs:enumeration value="body"/>
                 <xs:enumeration value="property"/>
                        <xs:enumeration value="inline"/>
                 </xs:restriction>
                         </xs:attribute>
            <xs:attribute name="xpath" type="xs:string" use="optional"/>
            <xs:attribute name="property" type="xs:string" use="optional"/>
         </xs:complexType>          
        </xs:element>      
    <xs:element name="target">
            <xs:annotation>
                <xs:documentation source="description">
                Target Configuration
                </xs:documentation>
            </xs:annotation>
            <xs:complexType>
        <xs:attribute name="action" minOccurs="1" maxOccurs="1">
                    <xs:annotation>
                        <xs:documentation>
                            The relevant action can be applied to outgoing message.
                        </xs:documentation>                    </xs:annotation>
                <xs:restriction base="xs:string">
                        <xs:enumeration value="replace"/>
                       <xs:enumeration value="child"/>
                <xs:enumeration value="sibiling"/>
            </xs:restriction>
                </xs:attribute>
        <xs:attribute name="type" minOccurs="1" maxOccurs="1">
                    <xs:annotation>
                        <xs:documentation>
                           Type of enriching the outgoing message.
                        </xs:documentation>
                    </xs:annotation>
                <xs:restriction base="xs:string">
                        <xs:enumeration value="envelope"/>
                       <xs:enumeration value="body"/>
                <xs:enumeration value="property"/>
                       <xs:enumeration value="custom"/>
            </xs:restriction>
                </xs:attribute>
        <xs:attribute name="xpath" type="xs:string" use="optional"/>
        <xs:attribute name="property" type="xs:string" use="optional"/>
    </xs:complexType>
    </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>  
</xs:schema>
If you need to find more about enrich mediator you can visit
http://wso2.org/project/esb/java/3.0.1/docs/mediators/enrich.html


If you need more examples of xsd's written for various uses visit
https://svn.apache.org/repos/asf/synapse/trunk/java/repository/schema/mediators/filter/

Then we will see how we can use this with eclipse IDE
01.Open eclipse IDE
02.From window menu goto preferences
   Window>Preferences
   Then you will see image shown below



03.from the menu appearing you must select xml catalog as shown below


04.Then add xml catalog entry as shown in the figure shown in figure
05.browse your xsd file and save it
06.create new eclipse project and add new XML file
   from menu New > XML
07.Create new xml as shown in the below images.

   create xml from xml schema

select xml category and then point the xml



  Than you will get new xml file as shown below

Now you have created it successfully.

Empowering the Future of API Management: Unveiling the Journey of WSO2 API Platform for Kubernetes (APK) Project and the Anticipated Alpha Release

  Introduction In the ever-evolving realm of API management, our journey embarked on the APK project eight months ago, and now, with great a...