Work order management system

Author: admin  //  Category: byte, computer

Work order management system (OMS) is basically software that is capable of tracking all work request and support issues, right from user requested enhancements. The OMS normally would be an integrated system supporting the order entry, order management and order delivery. If you think the purpose of incorporating work order management software is only to avoid the work order managing pitfalls then you are wrong! It can help you in saving time, money and energy but the real benefit is mostly unknown to many of us.

Below mentioned are some of the benefits of work order management system:

  • Streamline data tracking
  • Streamline invoicing and improve billing accuracy
  • Improve inventory tracking
  • Automate payroll calculations

In general order management systems are not only beneficial in reducing costs; it ensures the proper use of your software to avoid the pitfalls in managing your work orders! So, this would be pretty simple for you to manage the order with the software!

OBEX Protocol for Samsung GSM devices specification

Author: admin  //  Category: byte

Written by:
Khrystenko Artem,
Software Developer of Device Team.

Introduction
Main protocol commands format
The sequence of commands
Commands examples
References

Introduction

This article describes the protocol of data exchange that is the modification of the well-known OBEX protocol used in the GSM Samsung phones from the SHP family. The described modification of this protocol lets you write data to the phone and also get and save them.

Samsung Corporation made the new line of phones from SHP family and implemented the support of OBEX protocol in them that had not been used in the phones of this company before. Tries to use the common OBEX protocol did not succeed. This problem was solved by means of sniffing the Samsung PC Studio 3.0 utility. The obtained results are given in the main part of the article.

This article will be useful for those who develop utilities for writing/reading information from the phones. The described protocol modification will solve the problem of communicating with the device.

First we consider three main types of the protocol commands. Then we pay our attention to the sequence of the commands sent to connect with the device, read data and finish the session. Then I will give some examples for the main commands. At the end of the article some summary will be given.

Main protocol commands format

All protocol commands can be divided into 2 types:

AKN-packages. They are packages to confirm the data receiving and request the next part of the extended package. Data packages. They are initialization, acquiring, closing etc. There can be Request and Answer packages.

AKN package is one block with 3 bytes length: 0×83 0×00 0×03.

Request package has the following structure:

Size (bytes)

Meaning

Description

1

Package ID

0×80

Select the answering device, obtain the properties and establish connection

0×81

Finish the connection session

0×82

Write an object

0×83

Read an object

0×84

Reserved

0?85

Select the default directory on the receiving side

0?FF

Cancel current operation

2

Package size

The size of the whole package (from the zero byte and to the end)

Data blocks

Some number of data blocks that depends on the context of the command containing them.
Format:

Size (bytes)

Meaning

Description

1

Type

Set the type of the data in the block

2

Size

The size of the whole data block (from the zero byte and to the end)

N-3

Data

Some data depending on the type specified by the first byte

The description of the Answer packages is given in the table below.

Size (bytes)

Value

Description

1

Package ID

0×90

Successful but not completed (received package is a part of the extended package)

0xA0

Successful and completed

0xC3

Access denied

0xC4

Not found

0xC9

Conflict

2

Package size

The size of the whole package (from the zero byte and to the end)

Data blocks

Some number of data blocks that depends on the context of the command containing them.
Format:

Size
(bytes)

Meaning

Description

1

Type

Set the type of the data in the block

2

Size

The size of the whole data block (from the zero byte and to the end)

N-3

Data

Some data depending on the type specified by the first byte

The sequence of commands

As any standard communication protocol modified OBEX consists of the sequence of requests and answers. In general the communication session can be divided into 3 phases:

Initialization Acquiring data Closing the session

Table with the session description is given below.

Request

41 54 2B 53 59 4E 43 4D 4C 3D 4D 4F 42 45 58 53
54 41 52 54 0D 0A

AT+SYNCML=MOBEXS

Answer

41 54 2B 53 59 4E 43 4D 4C 3D 4D 4F 42 45 58 53
54 41 52 54 0D 4F 4B 0D 0A

AT+SYNCML=MOBEXS
TART.OK..

Request

80 00 0F 11 00 FF FF 46 00 08 4D 4F 42 45 58

?….  F..MOBEX

Answer

A0 00 14 12 00 05 78 CB 00 00 00 01 4A 00 08 4D
4F 42 45 58

?…..x?….J..M
OBEX

Request

A series of requests and answers for acquiring data
Note: if the first byte of the package is equal to 0×90 then it is so-called extended package and then the sending of AKN-package (0×83 0×00 0×03) is required, after it the device will give us the other parts of the package.

Answer

Request

81 00 08 CB 00 00 00 01

?..?….

Answer

A0 00 03

?..

Initialization phase

Acquiring phase

Closing phase

Commands examples

Let’s consider some examples of the data acquisition. They will be the examples of working with the file system.

Obtaining the list of subfolders of the folder(m-obex/fs/folder_listing)

Request

83 00 29 CB 00 00 00 01 42 00 1C 6D 2D 6F 62 65 ?.)E….B..m-obe
78 2F 66 73 2F 66 6F 6C 64 65 72 5F 6C 69 73 74 x/fs/folder_list
69 6E 67 00 01 00 05 2F 00 ing…./.

Size (byte)

Value

Description

1

0×83

Reading

2

0×00 0×29

Package size

1

0xCB

Data block type

4

0×00 0×00 0×00 0×01

Reserved

1

0×42

Data block type (text)

2

0×00 0x1C

Block size

N-3

m-obex/fs/folder_listing

Block data (command name)

1

0×01

Block type (list)

2

0×00 0×05

Block size

N-3

0x2F 0×00

Block data
Note: “/” for the root,  “/<directory name>” for the other folders

Answer
A0 00 FC 42 00 1B 6D 2D 6F 62 65 78 2F 66 73 2F .uB..m-obex/fs/
66 6F 6C 64 65 72 5F 6C 69 73 74 69 6E 67 C3 00 folder_listingA.
00 00 D6 49 00 D9 41 75 64 69 6F 2C 30 2C 31 31 ..OI.UAudio,0,11
31 30 30 31 30 31 30 2C 32 30 30 34 3A 30 33 3A 1001010,2004:03:
30 31 20 30 31 3A 30 33 3A 30 30 5C 72 5C 6E 47 01 01:03:00\r\nG
72 61 70 68 69 63 73 2C 30 2C 31 31 31 30 30 31 raphics,0,111001
30 31 30 2C 32 30 30 34 3A 30 33 3A 30 31 20 30 010,2004:03:01 0
31 3A 30 33 3A 30 30 5C 72 5C 6E 56 69 64 65 6F 1:03:00\r\nVideo
2C 30 2C 31 31 31 30 30 31 30 31 30 2C 32 30 30 ,0,111001010,200
34 3A 30 33 3A 30 31 20 30 31 3A 30 33 3A 30 30 4:03:01 01:03:00
5C 72 5C 6E 4D 75 73 69 63 2C 30 2C 31 31 31 30 \r\nMusic,0,1110
30 31 30 31 30 2C 32 30 30 34 3A 30 33 3A 30 31 01010,2004:03:01
20 30 31 3A 30 33 3A 30 30 5C 72 5C 6E 4F 74 68 01:03:00\r\nOth
65 72 20 46 69 6C 65 73 2C 30 2C 31 er Files,0,1
31 31 30 30 31 30 31 30 2C 32 30 30 34 3A 30 33 11001010,2004:03
3A 30 31 20 30 31 3A 30 33 3A 30 30 5C 72 5C 6E :01 01:03:00\r\n

Size

Value

Description

1

0xA0

Successful operation

2

0×00 0x0F

Package size

1

0×42

Block type

2

0×00 0x1C

Block size

N-3

m-obex/fs/folder_listing(0×00)

Block data

1

0xCB

Block type

4

0×00 0×00 0×00 0xD6

Reserved

1

0×49

Block type

2

0×00 0xD9

Block size

N-3

<DATA>

Block data
Note: the list items are separated with the pair of symbols “\r\n”

Each element of the list is the folder description: [Name][Size(always 0)][Attributes][Modified][Created].

So in the example of these two commands you can see the general structure of the package in the modified OBEX protocol.

In conclusion I want to mention that the records in the phone book as well as the calendar are represented in VCard as it was in the previous versions of the OBEX protocols.

References

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

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

http://www.ixbt.com/mobile/review/obex.shtml

Symmetric Cryptography in Java

Author: admin  //  Category: byte

Symmetric cryptography in Java

Introduction

As you know data security is a significant aspect of any enterprise application. Starting from password encryption to any data exchange, cryptography has been in use for all kinds of purpose. However there are two kinds of cryptography, one is symmetric and another is asymmetric. In case of symmetric cryptography, a secret key is used for all kinds of encryption and decryption. This secret key is shared by all the members who want to participate in the encryption and decryption process. There are several algorithms for the symmetric cryptography. DES( Data Encryption Standard) is one of them. In case of normal login screen of web based application, implementation of DES algorithm is used for password encryption.

Technicalities

Java cryptography provides suitable and flexible framework for the use of symmetric cryptography. DES algorithm is commonly known as symmetric algorithm. In case of symmetric cryptography, the secret key is used in a plain text file and this file is shared between the members. This file is used to retrieve the secret key for all kinds of encryption and decryption. In this regards I can provide you an example that think of a situation where the two lovers receive their love letters in encrypted format so that no body can read it. They have a common key called the DES secret key. They use the secret key to decrypt the contents of the encrypted love letters at their end. It means that the secret key is generated once and shared between the members. For more details of DES algorithm please refer to the java docs and JCE framework provided by Sun. In this article I will provide an example of how to use the implementation of DES algorithm.

Complete example

The following is the utility class for the cryptography management. The class name is

“KeyUtil.java”.

package com.dds.core;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import javax.crypto.Cipher;

import javax.crypto.CipherInputStream;

import javax.crypto.CipherOutputStream;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import javax.crypto.spec.SecretKeySpec;

/**This is a utility class for all kinds

* of useful methods related to symmetric

* cryptography. This class only provides

* the use of DES algorithm.You can use any

* other symmetric algorithm similarly.

* @author Debadatta Mishra( PIKU )

*

*/

public class KeyUtil {

/**

* Name of the algorithm

*/

private static String algorithm = “DES”;

/**This method is used to obtain the

* Secret key as a String. It is useful

* you can store the String in a file

* for all kinds of encryption and

* decryption.

* @return the SecretKey as String

*/

public static String generateSecretKey() {

String secretKeyString = null;

try {

KeyGenerator keyGen = KeyGenerator.getInstance(algorithm);

SecretKey secretKey = keyGen.generateKey();

byte[] secretKeyBytes = secretKey.getEncoded();

secretKeyString = new sun.misc.BASE64Encoder()

.encode(secretKeyBytes);

} catch (Exception e) {

e.printStackTrace();

}

return secretKeyString;

}

/**This method is used to obtain the SecretKey

* object by passing the secret key as string.

* @param secretKeyString of type String

* @return object of {@link SecretKey}

*/

private static SecretKey getKeyInstance(String secretKeyString) {

SecretKey secretKey = null;

try {

byte[] b2 = new sun.misc.BASE64Decoder()

.decodeBuffer(secretKeyString);

secretKey = new SecretKeySpec(b2, algorithm);

} catch (Exception e) {

e.printStackTrace();

}

return secretKey;

}

/**This method is used to encrypt the same file.

* This method is useful when you are encrypting

* the contents of a file. There is no need to

* create another file with the encrypted contents.

* @param filePath of type String indicating the path of the file

* @param keyString of type String indicating the secret key

*/

public static void encryptFile(String filePath, String keyString) {

try {

SecretKey key = getKeyInstance(keyString);

Cipher ecipher = Cipher.getInstance(algorithm);

ecipher.init(Cipher.ENCRYPT_MODE, key);

InputStream in = new FileInputStream(filePath);

byte[] fileBytes = new byte[in.available()];

in.read(fileBytes);

in.close();

OutputStream out = new FileOutputStream(filePath);

out = new CipherOutputStream(out, ecipher);

out.write(fileBytes);

out.close();

} catch (Exception e) {

e.printStackTrace();

}

}

/**This method is used to decrypt the same file.

* This method is useful when you are decrypting

* the contents of a file. There is no need to

* create another file with the decrypted contents.

* @param filePath of type String indicating the path of the file

* @param keyString of type String indicating the secret key

*/

public static void decryptFile(String filePath, String keyString) {

try {

SecretKey key = getKeyInstance(keyString);

Cipher ecipher = Cipher.getInstance(algorithm);

ecipher.init(Cipher.DECRYPT_MODE, key);

InputStream in = new FileInputStream(filePath);

byte[] fileBytes = new byte[in.available()];

in.read(fileBytes);

in.close();

OutputStream out = new FileOutputStream(filePath);

out = new CipherOutputStream(out, ecipher);

out.write(fileBytes);

out.close();

} catch (Exception e) {

e.printStackTrace();

}

}

/**This method is used to encrypt the contents

* of a file and writing to another file. This

* method is useful when you want to maintain the

* original contents and encrypting the contents

* and giving to another person.

* @param in of type {@link InputStream}

* @param out of type {@link OutputStream}

* @param keyString of type String indicating the SecretKey

*/

public static void encryptFile(InputStream in, OutputStream out,

String keyString) {

byte[] buf = new byte[1024];

try {

SecretKey key = getKeyInstance(keyString);

Cipher ecipher = Cipher.getInstance(algorithm);

ecipher.init(Cipher.ENCRYPT_MODE, key);

// Bytes written to out will be encrypted

out = new CipherOutputStream(out, ecipher);

// Read in the cleartext bytes and write to out to encrypt

int numRead = 0;

while ((numRead = in.read(buf)) >= 0) {

out.write(buf, 0, numRead);

}

out.close();

} catch (Exception e) {

e.printStackTrace();

}

}

/**This method is used to decrypt the contents

* of a file and writing to another file. This

* method is useful when you want to decrypt

* the contents and writing to a another file.

* @param in of type {@link InputStream}

* @param out of type {@link OutputStream}

* @param keyString of type String indicating the SecretKey

*/

public static void decryptFile(InputStream in, OutputStream out,

String keyString) {

byte[] buf = new byte[1024];

try {

SecretKey key = getKeyInstance(keyString);

Cipher dcipher = Cipher.getInstance(algorithm);

dcipher.init(Cipher.DECRYPT_MODE, key);

in = new CipherInputStream(in, dcipher);

int numRead = 0;

while ((numRead = in.read(buf)) >= 0) {

out.write(buf, 0, numRead);

}

out.close();

} catch (Exception e) {

e.printStackTrace();

}

}

/**This method is used to encrypt the String.

* @param contents of type String

* @param keyString of type String indicating the Secret key as String

* @return a String encrypted contents

*/

public static String getEncryptedContents(String contents, String keyString) {

String encryptedString = null;

try {

byte[] contentBytes = contents.getBytes();

SecretKey key = getKeyInstance(keyString);

Cipher ecipher = Cipher.getInstance(algorithm);

ecipher.init(Cipher.ENCRYPT_MODE, key);

byte[] encryptedBytes = ecipher.doFinal(contentBytes);

encryptedString = new sun.misc.BASE64Encoder()

.encode(encryptedBytes);

} catch (Exception e) {

e.printStackTrace();

}

return encryptedString;

}

/**This method is used to decrypt the String.

* @param contents of type String

* @param keyString of type String indicating the Secret key as String

* @return a String encrypted contents

*/

public static String getDecryptedContents(String contents, String keyString) {

String decryptedString = null;

try {

byte[] contentBytes = new sun.misc.BASE64Decoder()

.decodeBuffer(contents);

SecretKey key = getKeyInstance(keyString);

Cipher ecipher = Cipher.getInstance(algorithm);

ecipher.init(Cipher.DECRYPT_MODE, key);

byte[] encryptedBytes = ecipher.doFinal(contentBytes);

decryptedString = new String(encryptedBytes);

} catch (Exception e) {

e.printStackTrace();

}

return decryptedString;

}

}

The above class provides several useful methods for encryption and decryption. Please refer the java docs provided for each method. Generally in many applications, you may have to use either for a file or for a String. In the above class , I have provided two methods for file encryption and decryption. In certain situation, it is required that you have to encrypt the contents of the file. More specifically I can provide you an example, think about a file called “sample.txt”. You have to encrypt the contents of the file “Sample.txt” so that after encryption when you are opening the file, it becomes unreadable. It may also be required to transfer the file to network. Sometime a requirement comes that there is file called “Sample.txt”, you have to encrypt the contents of the file and to create a new file called “Sample_en.txt”. In this case you have two files, one is the original one as well as the encrypted file. Now refer to the following subordinate classes for the use.

Class name: KeyGenerator.java

package com.dds.core;

import java.io.File;

import java.io.FileOutputStream;

import java.io.OutputStream;

import java.util.Properties;

/**

* This class is used to generate the secrete key and

* stores the secret key in a file called secret.key.

* @author Debadatta Mishra(PIKU)

*

*/

public class KeyGenerator {

/**This method is used to obtain the

* path of the file secret.key.

* @return path of Key

*/

private static String getKeyFilePath() {

String keyPath = null;

try {

String keyDirPath = System.getProperty(“user.dir”) + File.separator

+ “key”;

File keyDir = new File(keyDirPath);

if (!keyDir.exists())

keyDir.mkdirs();

keyPath = keyDirPath + File.separator + “secretkey.key”;

} catch (Exception e) {

e.printStackTrace();

}

return keyPath;

}

/**

* This method is used to store the

* secret key in a file.

*/

public static void storeKey() {

try {

Properties keyProp = new Properties();

OutputStream out = new FileOutputStream(getKeyFilePath());

keyProp.put(“key”, KeyUtil.generateSecretKey());

keyProp

.store(out,

“Secret key information, do not modify the key.”);

} catch (Exception e) {

e.printStackTrace();

}

}

}

This class is used to generate the Secret key and to store in a file so that the secret key can be retrieved as and when required. Let us see another class where you can read the secret key file to get the secret key.

Class name: KeyReader.java

package com.dds.core;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

import java.util.Properties;

/**This is a utility class to read the

* contents of the secret.key file.

* @author Debadatta Mishra(PIKU)

*

*/

public class KeyReader {

/**This method is used to obtain the

* key String which is stored in the

* file secret.key.

* @return the key String

*/

public static String getSecretKey() {

String secretKeyString = null;

try {

String keyDirPath = System.getProperty(“user.dir”) + File.separator

+ “key”;

String keyPath = keyDirPath + File.separator + “secretkey.key”;

Properties keyProp = new Properties();

InputStream in = new FileInputStream(keyPath);

keyProp.load(in);

secretKeyString = keyProp.getProperty(“key”);

} catch (Exception e) {

e.printStackTrace();

}

return secretKeyString;

}

}

The above class is used to read the secret key.

I provide below all the test harness classes for the above classes. The first test harness class is “KeyGeneratorTest.java”.

import com.dds.core.KeyGenerator;

/**This is a test harness class to generate

* the secret key and store in a file.

* @author Debadatta Mishra(PIKU)

*

*/

public class KeyGeneratorTest {

public static void main(String[] args) {

KeyGenerator.storeKey();

}

}

This class is used to generate the secret key.

The next test harness class is “StringEncryptionTest.java”.

import com.dds.core.KeyReader;

import com.dds.core.KeyUtil;

/**This test harness class is used to

* encrypt and decrypt the String.

* @author Debadatta Mishra(PIKU)

*

*/

public class StringEncryptionTest {

public static void main(String[] args) {

String originalString = “Hello World”;

String secretKeyString = KeyReader.getSecretKey();

String encryptedStringContents = KeyUtil.getEncryptedContents(

originalString, secretKeyString);

System.out.println(“Original String——” + originalString);

System.out.println(“Encrypted String—–” + encryptedStringContents);

/*

* Now get back to your originalString by decryption

*/

String decryptedString = KeyUtil.getDecryptedContents(

encryptedStringContents, secretKeyString);

System.out.println(“Decrypted String—–” + decryptedString);

}

}

The above class is used to encrypt and decrypt a String. It may be useful for for your password and some other String of characters. Let us see the class for file encryption.

Class Name :  FileEncryptionTest.java

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import com.dds.core.KeyReader;

import com.dds.core.KeyUtil;

/**This is the test harness class for the

* encryption and decryption of the file.

* @author Debadatta Mishra(PIKU)

*

*/

public class FileEncryptionTest {

public static void main(String[] args) throws Exception {

String filePath = “C:/output.txt”;

String secretKeyString = KeyReader.getSecretKey();

/*

* Encrypt the fileContents and write to the same file

*/

KeyUtil.encryptFile(filePath, secretKeyString);

/*

* Decrypt the file contents and write to the same file

*/

KeyUtil.decryptFile(filePath, secretKeyString);

/*

* Encrypt the file contents and write to another

* file which contains the encrypted contents.

*/

String encryptedFilePath = “C:/en.txt”;

InputStream in = new FileInputStream(filePath);

OutputStream out = new FileOutputStream(encryptedFilePath);

KeyUtil.encryptFile(in, out, secretKeyString);

/*

* Decrypt the file contents and write to an another file.

*/

in = new FileInputStream(encryptedFilePath);

out = new FileOutputStream(filePath);

KeyUtil.decryptFile(in, out, secretKeyString);

}

}

The above class provides several ways you can encrypt and decrypt the file.

Please follow the following sequence to execute the above classes.

Please create the appropriate package structure and copy the corresponding classes inside the package.

First run the class “KeyGeneratorTest.java” . You will find a file called “secret.key” where the secret key is tored.

Next run the class “StringEncryptionTest.java”.

Create a text file with some contents and place in a directory. Then run the class “FileEncryptionTest.java” to encrypt or decrypt the file.

Conclusion

I hope that you will enjoy my article for the symmetric cryptography. For asymmetric cryptography please refer to the link http://www.articlesbase.com/information-technology-articles/asymmetric-cryptography-in-java-438155.html. If you find any problems or errors, please feel free to send me a mail in the address debadattamishra@aol.com . This article is only meant for those who are new to java development. This article does not bear any commercial significance. Please provide me the feedback about this article.

How To Develop Your Own Boot Loader

Author: admin  //  Category: byte

We will describe what is going after you turn on a computer; how the system is loading. As the practical example we will consider how you can develop your own boot loader which is actually the first point of the system booting process.

Author:
Alexandr Kolesnyk,
Junior Software Developer of ApriorIT Inc.

Who may be interested

Most of all I’ve written this article for those who have been always interested in the way the different things work. It is for those developers who usually create their applications in high-level languages such as C, C++ or Java, but faced with the necessity to develop something at low-level. We will consider low-level programming on the example of working at system loading.

We will describe what is going after you turn on a computer; how the system is loading. As the practical example we will consider how you can develop your own boot loader which is actually the first point of the system booting process.

What is Boot Loader

Boot loader is a program situated at the first sector of the hard drive; and it is the sector where the boot starts from. BIOS automatically reads all content of the first sector to the memory just after the power is turned on, and jump to it. The first sector is also called Master Boot Record. Actually it is not obligatory for the first sector of the hard drive to boot something. This name has been formed historically because developers used to boot their operating systems with such mechanism.

Be ready to go deeper

In this section I will tell about knowledge and tools you need to develop your own boot loader and also remind some useful information about system boot.

So what language you should know to develop Boot Loader

On the first stage on the computer work the control of hardware is performed mainly by means of BIOS functions known as interruptions. The implementation of interruptions is given only in Assembler – so it is great if you know it at least a little bit. But it’s not the necessary condition. Why? We will use the technology of “mixed code” where it is possible to combine high-level constructions with low-level commands. It makes our task a little simpler.

In this article the main development languages is C++. But if you have brilliant knowledge of C then it will be easy to learn required C++ elements. In general even the C knowledge will be enough but then you will have to modify the source code of the examples that I will descried here.

If you know Java or C# well unfortunately it won’t help for our task. The matter is that the code of Java and C# languages that is produced after compilation is intermediate. The special virtual machine is used to process it (Java Machine for Java, and .NET for C#) which transform intermediate code into processor instructions. After that transformation it can be executed. Such architecture makes it impossible to use mixed code technology – and we are going to use it to make our life easier, so Java and C# don’t work here.

So to develop the simple boot loader you need to know C or C++ and also it would be good if you know something about Assembler – language into which all high-level code is transformed it the end.

What compiler you need

To use mixed code technology you need at least two compilers: for Assembler and C/C++, and also the linker to join object files (.obj) into the one executable.

Now let’s talk about some special moments. There are two modes of processor functioning: real mode and safe mode. Real mode is 16-bit and has some limitations. Safe mode is 32-bit and is fully used in OS work. When it starts processor works in 16-bit mode. So to build the program and obtain executable file you will need the compiler and linker of Assembler for 16-bit mode. For C/C++ you will need only the compiler that can create object files for 16-bit mode.

The modern compilers are made for 32-bit applications only so we won’t able to use them.

I tried a number of free and commercial compilers for 16-bit mode and choose Microsoft product. Compiler along with the linker for Assembler, C, C++ are included into the Microsoft Visual Studio 1.52 package and also can be downloaded from the official site of the company. Some details about compilers we need are given below.

ML 6.15 – Assembler compiler by Microsoft for 16-bit mode;

LINK 5.16 – the linker that can create .com files for 16-bit mode;

CL – ?, ?++ compiler for 16-bit mode.

You can also use some alternative variants:

DMC – free compile for Assembler, C, C++ for 16 and 32-bit mode by Digital Mars;

LINK – free linker for DMC compiler;

There are also some products by Borland:

BCC 3.5 – ?, ?++ compiler that can create files for 16-bit mode;

TASM – Assembler compiler for 16-bit mode;

TLINK – linker that can create .com files for 16-bit mode.

All code examples in this article were built with the Microsoft tools.

How system boots

In order to solve our task we should recall how the system is booting.

Let’s consider briefly how the system components are interacting when the system is booting (see Fig.1).

Fig.1 – “How it boots”

After the control has been passed to the address 0000:7C00, Master Boot Record (MBR) starts its work and triggers the Operating System boot. You can learn more about MBR structure for example here – http://en.wikipedia.org/wiki/Master_boot_record.

Let’s code

In the next sections we will be directly occupied with the low-level programming – we will develop our own boot loader.

Program architecture

Boot loader that we are developing is for the training only. Its tasks are just the following:

Correct loading to the memory by 0000:7C00 address. Calling the BootMain function that is developed in the high-level language. Show “”Hello, world…”, from low-level” message on the display.

Program architecture is described on the Fig.2 that is followed by the text description.

Fig.2. – Program architecture description

The first entity is StartPoint that is developed purely in Assembler as far as high-level languages don’t have the necessary instructions. It tells compiler what memory model should be used, and what address the loading to the RAM should be performed by after the reading from the disk. It also corrects processor registers and passes control to the BootMain that is written in high-level language.

Next entity– BootMain – is an analogue of main that is in its turn the main function where all program functioning is concentrated.

CDisplay and CString classes take care of functional part of the program and show message on the screen. As you can see from the Fig.2 CDisplay class uses CStringclass in its work.

Development environment

Here I use the standard development environment Microsoft Visual Studio 2005 or 2008. You can use any other tools but I made sure that these two with some settings made the compiling and work easy and handy.

First we should create the project of Makefile Project type where the main work will be performed (see Fig.3).

File->New\Project->General\Makefile Project

Fig.3 – Create the project of Makefile type

BIOS interruptions and screen clearing

To show our message on the screen we should clear it first. We will use special BIOS interruption for this purpose.

BIOS proposes a number of interruptions for the work with computer hardware such as video adapter, keyboard, disk system. Each interruption has the following structure:

int [number_of_interrupt];

where number_of_interrupt is the number of interruption

Each interruption has the certain number of parameters that should be set before calling it. The ah processor register is always responsible for the number of function for the current interruption, and the other registers are usually used for the other parameters of the current operation. Let’s see how the work of int 10h interruption is perforemed in Assembler. We will use the 00 function that changes the video mode and clears screen:

mov al, 02h ; setting the graphical mode 80×25(text)
mov ah, 00h ; code of function of changing video mode
int 10h ; call interruption

We will consider only those interruptions and functions that will be used in our application. We will need:

int 10h, function 00h &ndash; performs changing of video mode and clears
; screen;
int 10h, function 01h &ndash; sets the cursor type;
int 10h, function 13h &ndash; shows the string on the screen;

«Mixed code»

Compiler for C++ supports the inbuilt Assembler i.e. when writing code in igh-level language you can use also low level language. Assembler Instructions that are used in the high level code are also called asm insertions. They consist of the key word __asm and the block of the Assembler instructions in braces:

__asm ; key word that shows the beginning of the asm insertion
{ ; block beginning

&hellip; ; some asm code
} ; end of the block

To demonstrate mixed code let’s use the previously mentioned Assembler code that performed the screen clearing and combine it with C++ code.

void ClearScreen()
{
__asm
{
mov al, 02h ; setting the graphical mode 80×25(text)
mov ah, 00h ; code of function of changing video mode
int 10h ; call interruption
}
}

CString implementation

CString class is designed to work with strings. It includes Strlen() method that obtains pointer to the string as the parameter and returns the number of symbols in that string.

// CString.h

#ifndef __CSTRING__
#define __CSTRING__

#include “Types.h”

class CString
{
public:
static byte Strlen(
const char far* inStrSource
);
};

#endif // __CSTRING__

// CString.cpp

#include “CString.h”

byte CString::Strlen(
const char far* inStrSource
)
{
byte lenghtOfString = 0;

while(*inStrSource++ != ‘\0′)
{
++lenghtOfString;
}
return lenghtOfString;
}

CDisplay implementation

CDisplay class is designed for the work with the screen. It includes several methods:

1) TextOut() – it prints the string on the screen.
2) ShowCursor() – it manages the cursor representation on the screen: show, hide.
3) ClearScreen() – it changes the video mode and thus clears screen.

// CDisplay.h

#ifndef __CDISPLAY__
#define __CDISPLAY__

//
// colors for TextOut func
//

#define BLACK 0×0
#define BLUE 0×1
#define GREEN 0×2
#define CYAN 0×3
#define RED 0×4
#define MAGENTA 0×5
#define BROWN 0×6
#define GREY 0×7
#define DARK_GREY 0×8
#define LIGHT_BLUE 0×9
#define LIGHT_GREEN 0xA
#define LIGHT_CYAN 0xB
#define LIGHT_RED 0xC
#define LIGHT_MAGENTA 0xD
#define LIGHT_BROWN 0xE
#define WHITE 0xF

#include “Types.h”
#include “CString.h”

class CDisplay
{
public:
static void ClearScreen();

static void TextOut(
const char far* inStrSource,
byte inX = 0,
byte inY = 0,
byte inBackgroundColor = BLACK,
byte inTextColor = WHITE,
bool inUpdateCursor = false
);

static void ShowCursor(
bool inMode
);
};

#endif // __CDISPLAY__

// CDisplay.cpp

#include “CDisplay.h”

void CDisplay::TextOut(
const char far* inStrSource,
byte inX,
byte inY,
byte inBackgroundColor,
byte inTextColor,
bool inUpdateCursor
)
{
byte textAttribute = ((inTextColor) | (inBackgroundColor << 4));
byte lengthOfString = CString::Strlen(inStrSource);

__asm
{
push bp
mov al, inUpdateCursor
xor bh, bh
mov bl, textAttribute
xor cx, cx
mov cl, lengthOfString
mov dh, inY
mov dl, inX
mov es, word ptr[inStrSource + 2]
mov bp, word ptr[inStrSource]
mov ah, 13h
int 10h
pop bp
}
}
void CDisplay::ClearScreen()
{
__asm
{
mov al, 02h
mov ah, 00h
int 10h
}
}

void CDisplay::ShowCursor(
bool inMode
)

{
byte flag = inMode ? 0 : 0×32;

__asm
{
mov ch, flag
mov cl, 0Ah
mov ah, 01h
int 10h
}
}

Types.h implementation

Types.h is the header file that includes definitions of the data types and macros.

// Types.h

#ifndef __TYPES__
#define __TYPES__

typedef unsigned char byte;
typedef unsigned short word;
typedef unsigned long dword;
typedef char bool;

#define true 0×1
#define false 0×0

#endif // __TYPES__

BootMain.cpp implementation

BootMain() is the main function of the program that is the first entry point (analogue of main()). Main work is performed here.

// BootMain.cpp

#include “CDisplay.h”

#define HELLO_STR “\”Hello, world…\”, from low-level…”

extern “C” void BootMain()
{
CDisplay::ClearScreen();
CDisplay::ShowCursor(false);

CDisplay::TextOut(
HELLO_STR,
0,
0,
BLACK,
WHITE,
false
);

return;
}

StartPoint.asm implementation

;————————————————————
.286 ; CPU type
;————————————————————
.model TINY ; memory of model
;———————- EXTERNS —————————–
extrn _BootMain:near ; prototype of C func
;————————————————————
;————————————————————
.code
org 07c00h ; for BootSector
main:
jmp short start ; go to main
nop

;———————– CODE SEGMENT ———————–
start:
cli
mov ax,cs ; Setup segment registers
mov ds,ax ; Make DS correct
mov es,ax ; Make ES correct
mov ss,ax ; Make SS correct
mov bp,7c00h
mov sp,7c00h ; Setup a stack
sti
; start the program
call _BootMain
ret

END main ; End of program

Let’s assemble everything Creation of COM file

Now when the code is developed we need to transform it to the file for the 16-bit OS. Such files are .com files. We can start each of compilers (for Assembler and C, C++) from the command line, transmit necessary parameters to them and obtain several object files as the result. Next we start linker to transform all .obj files to the one executable file with .com extension. It is working way but it’s not very easy.

Let’s automate the process. In order to do it we create .bat file and put commands with necessary parameters there. Fig.4 represents the full process of application assembling.

Fig.4 – Process of program compilation
Build.bat

Let’s put compilers and linker to the project directory. In the same directory we create .bat file and fill it accordingly to the example (you can use any directory name instead of VC152 where compilers and linker are situated):

.\VC152\CL.EXE /AT /G2 /Gs /Gx /c /Zl *.cpp

.\VC152\ML.EXE /AT /c *.asm

.\VC152\LINK.EXE /T /NOD StartPoint.obj bootmain.obj cdisplay.obj cstring.obj

del *.obj

Assembly automation

As the final stage in this section we will describe the way how to turn Microsoft Visual Studio 2005, 2008 into the development environment with any compiler support. Go to the Project Properties: Project->Properties->Configuration Properties\General->Configuration Type.

Configuration Properties tab includes three items: General, Debugging, NMake. Go to NMake and set the path to the build.bat in the Build Command Line and Rebuild Command Line fields – Fig.5.

Fig.5 –NMake project settings

If everything is correct then you can compile in the common way pressing F7 or Ctrl + F7. At that all attendant information will be shown in the Output window. The main advantage here is not only the assembly automation but also navigation thru the code errors if they happen.

Testing and Demonstration

This section will tell how to see the created boot loader in action, perform testing and debug.

How to test boot loader

You can test boot loader on the real hardware or using specially designed for such purposes virtual machine – VmWare. Testing on the real hardware gives you more confidence that it works while testing on the virtual machine makes you confident that it just can work. Surely we can say that VmWare is great method for testing and debug. We will consider both methods.

First of all we need a tool to write our boot loader to the virtual or physical disk. As far as I know there a number of free and commercial, console and GUI applications. I used Disk Explorer for NTFS 3.66 (version for FAT that is named Disk Explorer for FAT) for work in Windows and Norton Disk Editor 2002 for work in MS-DOS.

I will describe only Disk Explorer for NTFS 3.66 because it is the simplest method and suits our purposes the most.

Testing with the virtual machine VmWare

Creation of the virtual machine

We will need VmWare program version 5.0, 6.0 or higher. To test boot loader we will create the new virtual machine with minimal disk size for example 1 Gb. We format it for NTFS file system. Now we need to map the formatted hard drive to VmWare as the virtual drive. To do it:

File->Map or Disconnect Virtual Disks…

After that the window appears. There you should click Map button. In the next appeared window you should set the path to the disk. Now you can also chose the letter for the disk- see Fig.6.

Fig.6 – Parameters of virtual disk mapping

Don’t forget to uncheck the “Open file in read-only mode (recommended)” checkbox. When checked it indicates that the disk should be opened in read-only mode and prevent all recording attempts to avoid data corruption.

After that we can work with the disk of virtual machine as with the usual Windows logical disk. Now we should use Disk Explorer for NTFS 3.66 and record boot loader by the physical offset 0.

Working with Disk Explorer for NTFS

After program starts we go to our disk (File->Drive). In the window appeared we go to the Logical Drives section and chose disk with the specified letter (in my case it is Z) – see Fig.7.

Fig.7 – choosing disk in Disk Explorer for NTFS

Now we use menu item View and As Hex command. It the appeared window we can see the information on the disk represented in the 16-bit view, divided by sectors and offsets. There are only 0s as soon as the disk is empty at the moment. You can see the first sector on the Fig.8.

Fig.8 – Sector 1 of the disk

Now we should write our boot loader program to this first sector. We set the marker to position 00 as it is shown on the Fig.8. To copy boot loader we use Edit menu item, Paste from file command. In the opened window we specify the path to the file and click Open. After that the content of the first sector should change and look like it’s shown on the Fig.9 – if you haven’t changed anything in the example code, of course.

You should also write signature 55AAh by the 1FE offset from the sector beginning. If you don’t do it BIOS will check the last two bytes, won’t find the mentioned signature and will consider this sector as not the boot one and won’t read it to the memory.

To switch to the edit mode press F2 and write the necessary numbers –55AAh signature. To leave edit mode press Esc.

Now we need to confirm data writing.

Fig.9 – Boot Sector appearance

To apply writing we go to Tools->Options. Window will appear; we go to the Mode item and chose the method of writing – Virtual Write and click Write button – Fig.10.

Fig.10 – Choosing writing method in Disk Explorer for NTFS

A great number of routine actions are finished at last and now you can see what we have been developing from the very beginning of this article. Let’s return to the VwWare to disconnect the virtual disk (File->Map or Disconnect Virtual Disks… and click Disconnect).

Let’s execute the virtual machine. We can see now how from the some depth, from the kingdom of machine codes and electrics the familiar string appears ““Hello, world…”, from low-level…” – see Fig.11.

Fig.11 – “Hello world…”

Testing on the real hardware

Testing on the real hardware is almost the same as on the virtual machine except the fact that if something doesn’t work you will need much more time to repair it than to create the new virtual machine. To test boot loader without the threat of existent data corruption (everything can happen), I propose to use flash drive, but first you should reboot your PC, enter BIOS and check if it supports boot from the flash drive. If it does than everything is ok. If it does not than you have to limit your testing to virtual machine test only.

The writing of boot loader to the flash disk in Disk Explorer for NTFS 3.66 is the same to the process for virtual machine. You just should choose the hard drive itself instead of its logical section to perform writing by the correct offset – see Fig.12.

Fig.12 – Choosing physical disk as the device

Debug

If something went wrong – and it usually happens – you need some tools to debug your boot loader. I should say at once that it is very complicated, tiring and time-eating process. You will have to grasp in the Assembler machine codes – so good knowledge of this language is required. Any way I give a list of tools for this purpose:

TD (Turbo Debugger) – great debugger for 16-bit real mode by Borland.

CodeView – good debugger for 16-bit mode by Microsoft.

D86 – good debugger for 16-bit real mode developed by Eric Isaacson – honored veteran of development for Intel processor in Assembler.

Bocsh – program-emulator of virtual machine that includes debugger of machine commands.

Information Sources

Assembly Language for Intel-Based Computers” by Kip R. Irvine is the great book that gives good knowledge of inner structure of the computer and development in Assembler. You ca also find information about installation, configuration and work with the MASM 6.15 compiler.

This link will guide you to the BIOS interruption list: http://en.wikipedia.org/wiki/BIOS_interrupt_call

Conclusion

In this article we have considered what is boot loader, how BIOS works, and how system components interact when system boots. Practical part gave the information about how to develop your own simple boot loader. We demonstrated the mixed code technology and process of automation of assembly with Microsoft Visual Studio 2005, 2008.

Of course it is just a small piece comparing with the huge theme of low-level programming, but if you get interested of this article – it’s great.

Download Boot Loader sources

Encryption Using Rsa Algorithm in Java

Author: admin  //  Category: byte

Encryption using RSA algorithm in java

Introduction

In this article I will provide you an approach of using RSA algorithm for long String. As you know that RSA algorithm is limited 117 bytes, long strings can not be encrypted or decrypted. However it is possible to break the bytes into several chunks and then to encrypt or decrypt the contents. This algorithm is used for asymmetric cryptography. For asymmetric cryptography, you can click this link.

Technicalities

In this article I provide below the complete example for encryption and decryption of long strings. If you use the method of Cipher class ie.doFinal( byte[] bytesString), it will throw exception that it can be encrypted for more than 117 bytes for RSA.  But in the real application, you may not be sure about the length of the String you want to encrypt or decrypt. In this case you have to break the bytes and then to encrypt it. Please refer to the

Following complete example.

Complete example

Class name : SecurityUtil.java

package com.dds.core.security;

import java.security.KeyFactory;

import java.security.KeyPair;

import java.security.KeyPairGenerator;

import java.security.PrivateKey;

import java.security.PublicKey;

import java.security.Security;

import java.security.spec.EncodedKeySpec;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import sun.misc.BASE64Decoder;

import sun.misc.BASE64Encoder;

import com.sun.crypto.provider.SunJCE;

/**This is a utility class which provides

* convenient method for security. This

* class provides the way where you can

* encrypt and decrypt the String having

* more than 117 bytes for RSA algorithm

* which is an asymmetric one.

* @author Debadatta Mishra(PIKU)

*

*/

public class SecurityUtil {

/**

* Object of type {@link KeyPair}

*/

private KeyPair keyPair;

/**

* String variable which denotes the algorithm

*/

private static final String ALGORITHM = “RSA”;

/**

* varibale for the keysize

*/

private static final int KEYSIZE = 1024;

/**

* Default constructor

*/

public SecurityUtil() {

super();

Security.addProvider(new SunJCE());

}

/**

* This method is used to generate

* the key pair.

*/

public void invokeKeys() {

try {

KeyPairGenerator keypairGenerator = KeyPairGenerator

.getInstance(ALGORITHM);

keypairGenerator.initialize(KEYSIZE);

keyPair = keypairGenerator.generateKeyPair();

} catch (Exception e) {

e.printStackTrace();

}

}

/**This method is used to obtain the String

* representation of the PublicKey.

* @param publicKey of type {@link PublicKey}

* @return PublicKey as a String

*/

public String getPublicKeyString(PublicKey publicKey) {

return new BASE64Encoder().encode(publicKey.getEncoded());

}

/**This method is used to obtain the String

* representation of the PrivateKey.

* @param privateKey of type {@link PrivateKey}

* @return PrivateKey as a String

*/

public String getPrivateKeyString(PrivateKey privateKey) {

return new BASE64Encoder().encode(privateKey.getEncoded());

}

/**This method is used to obtain the

* {@link PrivateKey} object from the

* String representation.

* @param key of type String

* @return {@link PrivateKey}

* @throws Exception

*/

public PrivateKey getPrivateKeyFromString(String key) throws Exception {

PrivateKey privateKey = null;

try {

KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);

EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(

new BASE64Decoder().decodeBuffer(key));

privateKey = keyFactory.generatePrivate(privateKeySpec);

} catch (Exception e) {

e.printStackTrace();

}

return privateKey;

}

/**This method is used to obtain the {@link PublicKey}

* from the String representation of the Public Key.

* @param key of type String

* @return {@link PublicKey}

* @throws Exception

*/

public PublicKey getPublicKeyFromString(String key) throws Exception {

PublicKey publicKey = null;

try {

KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);

EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(

new BASE64Decoder().decodeBuffer(key));

publicKey = keyFactory.generatePublic(publicKeySpec);

} catch (Exception e) {

e.printStackTrace();

}

return publicKey;

}

/**This method is used to obtain the

* encrypted contents from the original

* contents by passing the {@link PublicKey}.

* This method is useful when the byte is more

* than 117.

* @param text of type String

* @param key of type {@link PublicKey}

* @return encrypted value as a String

* @throws Exception

*/

public String getEncryptedValue(String text, PublicKey key)

throws Exception {

String encryptedText;

try {

byte[] textBytes = text.getBytes(“UTF8″);

Cipher cipher = Cipher.getInstance(“RSA/ECB/PKCS1Padding”);

cipher.init(Cipher.ENCRYPT_MODE, key);

int textBytesChunkLen = 100;

int encryptedChunkNum = (textBytes.length – 1) / textBytesChunkLen

+ 1;

// RSA returns 128 bytes as output for 100 text bytes

int encryptedBytesChunkLen = 128;

int encryptedBytesLen = encryptedChunkNum * encryptedBytesChunkLen;

System.out.println(“Encrypted bytes length——-”

+ encryptedBytesChunkLen);

// Define the Output array.

byte[] encryptedBytes = new byte[encryptedBytesLen];

int textBytesChunkIndex = 0;

int encryptedBytesChunkIndex = 0;

for (int i = 0; i

if (i

encryptedBytesChunkIndex = encryptedBytesChunkIndex

+ cipher.doFinal(textBytes, textBytesChunkIndex,

textBytesChunkLen, encryptedBytes,

encryptedBytesChunkIndex);

textBytesChunkIndex = textBytesChunkIndex

+ textBytesChunkLen;

} else {

cipher.doFinal(textBytes, textBytesChunkIndex,

textBytes.length – textBytesChunkIndex,

encryptedBytes, encryptedBytesChunkIndex);

}

}

encryptedText = new BASE64Encoder().encode(encryptedBytes);

} catch (Exception e) {

throw e;

}

return encryptedText;

}

/**This method is used to decrypt the contents.

* This method is useful when the size of the

* bytes is more than 117.

* @param text of type String indicating the

* encrypted contents.

* @param key of type {@link PrivateKey}

* @return decrypted value as a String

*/

public String getDecryptedValue(String text, PrivateKey key) {

String result = null;

try {

byte[] encryptedBytes = new BASE64Decoder().decodeBuffer(text);

Cipher cipher = Cipher.getInstance(“RSA/ECB/PKCS1Padding”);

cipher.init(Cipher.DECRYPT_MODE, key);

int encryptedByteChunkLen = 128;

int encryptedChunkNum = encryptedBytes.length

/ encryptedByteChunkLen;

int decryptedByteLen = encryptedChunkNum * encryptedByteChunkLen;

byte[] decryptedBytes = new byte[decryptedByteLen];

int decryptedIndex = 0;

int encryptedIndex = 0;

for (int i = 0; i

if (i

decryptedIndex = decryptedIndex

+ cipher.doFinal(encryptedBytes, encryptedIndex,

encryptedByteChunkLen, decryptedBytes,

decryptedIndex);

encryptedIndex = encryptedIndex + encryptedByteChunkLen;

} else {

decryptedIndex = decryptedIndex

+ cipher.doFinal(encryptedBytes, encryptedIndex,

encryptedBytes.length – encryptedIndex,

decryptedBytes, decryptedIndex);

}

}

result = new String(decryptedBytes).trim();

} catch (Exception e) {

e.printStackTrace();

}

return result;

}

/**This method is used obtain the

* {@link PublicKey}

* @return {@link PublicKey}

*/

public PublicKey getPublicKey() {

return keyPair.getPublic();

}

/**This method is used to obtain

* the {@link PrivateKey}

* @return {@link PrivateKey}

*/

public PrivateKey getPrivateKey() {

return keyPair.getPrivate();

}

}

The above class provides several useful methods for generation of Private key , Public Key and encryption of String and decryption of String.

Please refer to the following subordinate classes for the above class.

Class name : KeyGenerator.java

package com.dds.core.security;

import java.io.File;

import java.io.FileOutputStream;

import java.io.OutputStream;

import java.security.PrivateKey;

import java.security.PublicKey;

import java.util.Properties;

/**This class is used to generate the

* Private and Public key and stores

* them in files.

* @author Debadatta Mishra(PIKU)

*

*/

public class KeyGenerator {

/**This method is used to obtain the

* path of the keys directory where

* Private and Public key files are

* stored.

* @return path of the keys directory

*/

private static String getKeyFilePath() {

String keyDirPath = null;

try {

keyDirPath = System.getProperty(“user.dir”) + File.separator

+ “keys”;

File keyDir = new File(keyDirPath);

if (!keyDir.exists())

keyDir.mkdirs();

} catch (Exception e) {

e.printStackTrace();

}

return keyDirPath;

}

/**

* This method is used to generate the

* Private and Public keys.

*/

public static void generateKeys() {

Properties publicProp = new Properties();

Properties privateProp = new Properties();

try {

OutputStream pubOut = new FileOutputStream(getKeyFilePath()

+ File.separator + “public.key”);

OutputStream priOut = new FileOutputStream(getKeyFilePath()

+ File.separator + “private.key”);

SecurityUtil secureUtil = new SecurityUtil();

secureUtil.invokeKeys();

PublicKey publicKey = secureUtil.getPublicKey();

PrivateKey privateKey = secureUtil.getPrivateKey();

String publicString = secureUtil.getPublicKeyString(publicKey);

String privateString = secureUtil.getPrivateKeyString(privateKey);

publicProp.put(“key”, publicString);

publicProp.store(pubOut, “Public Key Info”);

privateProp.put(“key”, privateString);

privateProp.store(priOut, “Private Key Info”);

} catch (Exception e) {

e.printStackTrace();

}

}

}

The above class is used to generate the Public and Private keys. It generates and stores them in different files called Public.key and Private.key. Please refer the test harness class for the above class.

Class name: TestKeyGenerator

import com.dds.core.security.KeyGenerator;

/**This is a testharness class

* for the KeyGenerator class.

* @author Debadatta Mishra(PIKU)

*

*/

public class TestKeyGenerator {

public static void main(String[] args) {

KeyGenerator.generateKeys();

}

}

If you run the above class, you will find a directory called keys in your root path of your application folder. In this folder you will find two files one is for Private Key information and another is for Public Key.

There is another class which is used to obtain the Private key and Public key information stored in the files.

Class name: KeyReader.java

package com.dds.core.security;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

import java.security.PublicKey;

import java.util.Properties;

/**This class is used to read the

* keys from the file.

* @author Debadatta Mishra(PIKU)

*

*/

public class KeyReader {

/**This method is used to obtain the

* string value of the Public Key

* from the file.

* @return String of {@link PublicKey}

*/

public static String getPublicKeyString() {

String publicString = null;

try {

Properties prop = new Properties();

String publicKeyPath = System.getProperty(“user.dir”)

+ File.separator + “keys” + File.separator + “public.key”;

InputStream in = new FileInputStream(publicKeyPath);

prop.load(in);

publicString = prop.getProperty(“key”);

} catch (Exception e) {

e.printStackTrace();

}

return publicString;

}

/**This method is used to obtain the

* String of Private Key from the file.

* @return String of private key

*/

public static String getPrivateKeyString() {

String publicString = null;

try {

Properties prop = new Properties();

String publicKeyPath = System.getProperty(“user.dir”)

+ File.separator + “keys” + File.separator + “private.key”;

InputStream in = new FileInputStream(publicKeyPath);

prop.load(in);

publicString = prop.getProperty(“key”);

} catch (Exception e) {

e.printStackTrace();

}

return publicString;

}

}

This is a utility class to read the Public and Private keys from the files.

Now refer to the test harness class which makes encryption and decryption of String.

import java.security.PrivateKey;

import java.security.PublicKey;

import com.dds.core.security.KeyReader;

import com.dds.core.security.SecurityUtil;

/**

* This is a test harness class for encryption and decryption.

*

* @author Debadatta Mishra(PIKU)

*

*/

public class TestEncryption {

public static void main(String[] args) {

String privateKeyString = KeyReader.getPrivateKeyString();

SecurityUtil securityUtil = new SecurityUtil();

String publicKeyString = KeyReader.getPublicKeyString();

try {

PublicKey publicKey = securityUtil

.getPublicKeyFromString(publicKeyString);

PrivateKey privateKey = securityUtil

.getPrivateKeyFromString(privateKeyString);

String originalValue = “provide some very long string”;

String encryptedValue = securityUtil.getEncryptedValue(

originalValue, publicKey);

System.out.println(“EncryptedValue—–” + encryptedValue);

String decryptedValue = securityUtil.getDecryptedValue(

encryptedValue, privateKey);

System.out.println(“Original Value——” + decryptedValue);

} catch (Exception e) {

e.printStackTrace();

}

}

}

This test harness class is used to encrypt and decrypt the long string contents. You can also use the same method for file encryption and decryption. First you have to read the contents of a file as String and then you can apply method to encrypt it.

Conclusion

I hope that you will enjoy my article for this asymmetric cryptography for RSA. For asymmetric cryptography please refer to the link http://www.articlesbase.com/information-technology-articles/asymmetric-cryptography-in-java-438155.html. If you find any problems or errors, please feel free to send me a mail in the address debadattamishra@aol.com . This article is only meant for those who are new to java development. This article does not bear any commercial significance. Please provide me the feedback about this article

Unicode Primer for the Uninitiated: Internationalization Article

Author: admin  //  Category: byte

Among our friends and clients at Lingoport.com, we regularly see ranges of confusion, to complete lack of awareness of what Unicode is. So for the less- or under-informed, perhaps this article will help. The advent of Unicode is a key underpinning for global software applications and websites so that they can support worldwide language scripts. So it’s a very important standard to be aware of, whether you’re in localization, an engineer or a business manager.

Unicode Growth

Firstly, Unicode is a character set standard used for displaying and processing language data in computer applications. The Unicode character set is the entire world’s set of characters, including letters, numbers, currencies, symbols and the like, supporting a number of character encodings to make that all happen. Before your eyes glaze over, let me explain what character encoding means. You have to remember that for a computer, all information is represented in zeros and ones (i.e. binary values). So if you think of the letter A in the ASCII standard of zeros and ones it would look like this: 1000001. That is, a 1 then five zeros and a 1 to make a total of 7 bits. This binary representation for A is called A’s code point, and this mapping of zeros and ones to characters is called the character encoding. In the early days of computing, unless you did something very special, ASCII (7 bits per character) was how your data got managed. The problem is that ASCII doesn’t leave you enough zeros and ones to represent extended characters, like accents and characters specific to non-English alphabets, such as you find in European languages. You certainly can’t support the complex characters that make up Chinese, Korean and Japanese languages. These languages require 8-bit (single-byte) or 16-bit (double-byte) character encodings. One important note on all of these single- and double-byte encodings is that they are a superset of 7-bit ASCII encoding, which means that English code points will always be the same regardless the encoding.

The Bad Old Days

In the early computing days, specific character single- and double-byte encodings were developed to support various languages. That was very bad, as it meant that software developers needed to build a version of their application for every language they wanted to support that used a different encoding. You’d have the Japanese version, the Western European language version, the English-only version and so on. You’d end up with a hoard of individual software code bases, each needing their own testing, updating and ongoing maintenance and support, which is very expensive, and pretty near impossible for businesses to realistically support without serious digressions among the various language versions over time. You don’t see this problem very often for newly developed applications, but there are plenty of holdovers. We see it typically when a new client has turned over their source code to a particular country partner or marketing agent which was responsible for adapting the code to multiple languages. The worst case I saw was in 2004 when a particular client, who I will leave unmentioned, had a legacy product with 18 separate language versions and had no real idea any longer the level of functionality that varied from language to language. That’s no way to grow a corporate empire!

ISO Latin

A single-byte character set that we often see in applications is ISO Latin 1, which is represented in various encoding standards such as ISO-8859-1 for UNIX, Windows-1252 for Windows and MacRoman on guess what platform. This character set supports characters used in Western European languages such as French, Spanish, German, and U.K. English. Since each character requires only a single byte, this character set provides support for multiple languages, while avoiding the work required to support either Unicode or a double-byte encoding. Trouble is that still leaves out much of the world. For example, to support Eastern European languages you need to use a different character set, often referred to as Latin 2, which provides the characters that are uniquely needed for these languages. There are also separate character sets for Baltic languages, Turkish, Arabic, Hebrew, and on and on. When having to internationalize software for the first time, sometimes companies will start with just supporting ISO Latin 1 if it meets their immediate marketing requirements and deal with the more extensive work of supporting other languages later. The reason is that it’s likely these software applications will need major reworking of the encoding support in their database and functions, methods and classes within their source code to go beyond ISO Latin support, which means more time and more money – often cascading into later releases and foregone revenues. However, if the software company has truly global ambitions, they will need to take that plunge and provide Unicode support. I’ll argue that if companies are supporting global customers, and even not doing a bit of translation/localization for the interface, they still need to support Unicode so they can provide processing of their customer’s global data.

Unicode

We come back to Unicode, which as we mentioned above, is a character set created to enable support of any written language worldwide. Now you might find a language or two lacking Unicode support for its script but that is becoming extremely isolated. For instance, currently Javanese, Loma, and Tai Viet are among scripts not yet supported. Arcane until you need them I suppose. I remember a few years ago when we were developing a multi-lingual site which needed support for Khmer and Armenian, and we were thankful that Unicode had just added their support a few months prior. If you have a marketing requirement for your software to support Japanese or Chinese, think Unicode. That’s because you will need to move to a double-byte encoding at the very least, and as soon as you go through the trouble to do that, you might as well support Unicode and get the added benefit of support for all languages.

UTF-8

Once you’ve chosen to support Unicode, you must decide on the specific character encoding you want to use, which will be dependent on the application requirements and technologies. UTF-8 is one of the commonly used character encodings defined within the Unicode Standard, which uses a single byte for each character unless it needs more, in which case it can expand up to 4 bytes. People sometimes refer to this as a variable-width encoding since the width of the character in bytes varies depending upon the character. The advantage of this character encoding is that all English (ASCII) characters will remain as single-bytes, saving data space. This is especially desirable for web content, since the underlying HTML markup will remain in single-byte ASCII. In general, UNIX platforms are optimized for UTF-8 character encoding. Concerning databases, where large amounts of application data are integral to the application, a developer may choose a UTF-8 encoding to save space if most of the data in the database does not need translation and so can remain in English (which requires only a single byte in UTF-8 encoding). Note that some databases will not support UTF-8, specifically Microsoft’s SQL Server.

UTF-16

UTF-16 is another widely adopted encoding within the Unicode standard. It assigns two bytes for each character whether you need it or not. So the letter A is 00000000 01000001 or 9 zeros, a one, followed by 5 zeros and a one. If more than 2 bytes are needed for a character, four bytes can be combined, however you must adapt your software to be capable of handling this four-byte combination. Java and .Net internally process strings (text and messages) as UTF-16.

For many applications, you can actually support multiple Unicode encodings so that for example your data is stored in your database as UTF-8 but is handled within your code as UTF-16, or vice versa. There are various reasons to do this, such as software limitations (different software components supporting different Unicode encodings), storage or performance advantages, etc.. But whether that’s a good idea is one of those “it depends” kinds of questions. Implementing can be tricky and clients pay us good money to solve this.

Microsoft’s SQL Server is a bit of a special case, in that it supports UCS-2, which is like UTF-16 but without the 4-byte characters (only the 16-bit characters are supported).

GB 18030

There’s also a special-case character set when it comes to engineering for software intended for sale in China (PRC), which is required by the Chinese Government. This character set is GB 18030, and it is actually a superset of Unicode, supporting both simplified and traditional Chinese. Similarly to UTF-16, GB 18030 character encoding allows 4 bytes per character to support characters beyond Unicode’s “basic” (16-bit) range, and in practice supporting UTF-16 (or UTF-8) is considered an acceptable approach to supporting GB 18030 (the UCS-2 encoding just mentioned is not, however).

Now all of this considered, a converse question might be, what happens when you try to make your application support complex scripts that need Unicode, and the support isn’t there? Depending upon your system, you get anything from garbled and meaningless gibberish where data or messages become corrupted characters or weird square boxes, or the application crashes forcing a restart. Not good.

If your application supports Unicode, you are ready to take on the world.

Asymmetric Cryptography in Java

Author: admin  //  Category: byte

Security plays a significant role in our day to day life. So far software applications are concerned, security of data is required for authentication and for several validations. Normally while developing the applications, we use the concept of cryptography for password encryption and decryption. Some applications require more security, so they go for high end security system like trusted security certificates. The security mainly focuses on the integrity of the data at the several ends.

Technicalities For data security Java Cryptography provides a suitable framework to implement several kinds of cryptography. However there are basically two types of cryptography. Once is Symmetric Cryptography and Asymmetric Cryptography. When both the ends communicate the secured data with a common key for encryption and decryption, it is called the Symmetric Cryptography. In this case a shared key is used by both the parties to encrypt and decrypt the data. However there is a problem relating to exchange of key for symmetric cryptography. To overcome this problem java provides another approach for the cryptography called Asymmetric Cryptography. In case of Asymmetric cryptography, there will be two keys unlike one key in case of symmetric cryptography. One key is called Private key and other is called Public key. These two keys are generated together and can be used for encryption and decryption. In this case the Public key is used by anyone who wishes to communicate securely with the owner of the Private key. The Private key is used by the main owner and the owner gives the Public key so that they can decrypt the data. In this article I will give you the example on Asymmetric cryptography. You can find more tutorials and concept on Sun’s JCE(Java Cryptography Extension). In my next article, I will provide you the example on Symmetric cryptography.

Complete Example This example is only meant for learning and not for any specific use. You can take the piece of code to test in your system to learn the above concept.

The following class is used to create the Public key and Private key. This class contains generic methods to generate the Public and Private key. If you run the testharness class, you will find the two files called “Public.key” and “Private.key”. Please go through the java docs mentioned in the methods.

Class Name : – KeyCreator.java

package com.dds.security;

import java.io.FileOutputStream;

import java.io.IOException;

import java.security.KeyPair;

import java.security.KeyPairGenerator;

import java.security.PrivateKey;

import java.security.PublicKey;

/**This class is used to generate the Private and Public key file.

* The Public.key file and Private.key file will be generated in the

* current directory.

* @author Debadatta Mishra(PIKU)

*

*/

public class KeyCreator

{

/**

* Object of type {@link PublicKey}

*/

private PublicKey publicKey = null;

/**

* Object of type {@link PrivateKey}

*/

private PrivateKey privateKey = null;

/**Default constructor.

* Here KeyPair object is initialized and

* thereby public key and private key objects

* are created.

* @throws Exception

*/

public KeyCreator() throws Exception

{

super();

/*

* The following line is used to

* generate the Public and Private

* key.

*/

KeyPair keyPair = KeyPairGenerator

.getInstance(“RSA”)

.generateKeyPair();

publicKey = keyPair.getPublic();

privateKey = keyPair.getPrivate();

}

/**Method to return the {@link PublicKey}

* @return the {@link PublicKey}

*/

public PublicKey getPublicKey() {

return publicKey;

}

/**Method to return the {@link PrivateKey}

* @return the {@link PrivateKey}

*/

public PrivateKey getPrivateKey() {

return privateKey;

}

/**Method used to write the Public or Private

* key file.

* @param filename of type String indicating

* the name of Public or Private key

* @param contents of the key

*/

public void writeKey(String filename, byte[] contents)

{

try

{

FileOutputStream fos = new FileOutputStream(filename);

fos.write(contents);

fos.flush();

fos.close();

}

catch (IOException e)

{

e.printStackTrace();

}

}

}

The following class is used to read the “Public.key” and “Private.key” generated by the above program. If you are the owner you can have the “Private.key” file based upon which you have to encrypt the data and give your “Public.key” file to other end who wants to decrypt the data. In this following class, you can read both the “Public.key” and “Private.key” files.

Class Name:- KeyReader.java

package com.dds.security;

import java.io.ByteArrayOutputStream;

import java.io.FileInputStream;

import java.io.IOException;

import java.security.KeyFactory;

import java.security.PrivateKey;

import java.security.PublicKey;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

/**

* This class is used to read the Private and Public key

* files generated using the Java’s Asysmmetric Security

* system.

* @author Debadatta Mishra(PIKU)

*

*/

public class KeyReader

{

/**

* Object of type {@link KeyFactory}

*/

private KeyFactory keyFactory = null;

/**

* Default constructor to initialize the

* keyFactory.

*/

public KeyReader()

{

super();

try

{

keyFactory = KeyFactory.getInstance(“RSA”);

}

catch( Exception e )

{

e.printStackTrace();

}

}

/**This method is used to read the bytes from the file.

* The file can be a Public key file or a Private key

* file. In this file, you have stored the security key,

* based upon which encryption and decryption can be

* performed.

* @param fileName of type String indicating the file name

* @return the bytes from the file

* @throws Exception

*/

private byte[] getKeyData( String fileName ) throws Exception

{

FileInputStream fis = new FileInputStream(fileName);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

int b;

try

{

while ((b = fis.read()) != -1)

{

baos.write(b);

}

fis.close();

baos.flush();

baos.close();

} catch (IOException e) {

e.printStackTrace();

}

return baos.toByteArray();

}

/**This method is used to return the object of type

* {@link PrivateKey}. In this method you have to pass

* the file name of the Private.key file.

* @param filename of type String indicating the

* file name.

* @return the object of type {@link PrivateKey}

* @throws Exception

*/

public PrivateKey getPrivateKey( String filename ) throws Exception

{

PrivateKey privateKey = null;

try

{

byte[] keydata = getKeyData(filename);

PKCS8EncodedKeySpec encodedPrivateKey = new PKCS8EncodedKeySpec(keydata);

privateKey = keyFactory.generatePrivate(encodedPrivateKey);

}

catch( Exception e )

{

e.printStackTrace();

}

return privateKey;

}

/**This method is used to return the object of type

* {@link PublicKey}. In this method you have to pass

* the file name of the Public.key file.

* @param filename of type String indicating the

* file name.

* @return the object of type {@link PublicKey}

* @throws Exception

*/

public PublicKey getPublicKey( String filename ) throws Exception

{

PublicKey publicKey = null;

try

{

byte[] keydata = getKeyData(filename);

X509EncodedKeySpec encodedPublicKey = new X509EncodedKeySpec(keydata);

publicKey = keyFactory.generatePublic(encodedPublicKey);

}

catch( Exception e )

{

e.printStackTrace();

}

return publicKey;

}

}

The following class is a utility class which is used to encrypt and decrypt the data.

ClassName :- SecurityUtil.java

package com.dds.security;

import java.security.PrivateKey;

import java.security.PublicKey;

import javax.crypto.Cipher;

/**This is a utility class to provide

* encryption and decryption based upon

* the key. The key can be your either

* Public or Private .

* @author Debadatta Mishra(PIKU)

*

*/

public class SecurityUtil

{

/**

* Object of type {@link Cipher}

*/

private static Cipher cipher = null;

/*

* The following static is used to

* initialize the Cipher object

*/

static

{

try

{

cipher = Cipher.getInstance(“RSA”);

}

catch( Exception e )

{

e.printStackTrace();

}

}

/**Method used to encrypt the string and return as bytes.

* Here the input parameter will be your Private key.

* You have to encrypt the string using your private

* key at your end.

* @param messsageBytes , it is the bytes from the

* string to encrypt

* @param privateKey of type {@link PrivateKey}

* @return encrypted bytes

* @throws Exception

*/

public static byte[] getEncryptedBytes( byte[] messsageBytes , PrivateKey privateKey) throws Exception

{

byte[] encryptedBytes = null;

cipher.init(Cipher.ENCRYPT_MODE , privateKey );

encryptedBytes = cipher.doFinal(messsageBytes);

return encryptedBytes;

}

/**Method used to decrypt the string and return as bytes.

* Here the input parameter will be your Public key.

* You have to decrypt the string using your Public

* key at the destination end.

* @param messsageBytes , it is the bytes from the

* string to encrypt

* @param publicKey of type {@link PublicKey}

* @return decrypted bytes

* @throws Exception

*/

public static byte[] getDecryptedBytes( byte[] messsageBytes , PublicKey publicKey)throws Exception

{

byte[] decryptedBytes = null;

cipher.init(Cipher.DECRYPT_MODE , publicKey );

decryptedBytes = cipher.doFinal( messsageBytes );

return decryptedBytes;

}

}

The following is test harness class to test the functionality of the above program. Please go through the comments and java docs of the above and below programs.

Class Name :- SecurityTestHarness.java

package com.security.testharness;

import java.security.PrivateKey;

import java.security.PublicKey;

import com.dds.security.KeyCreator;

import com.dds.security.KeyReader;

import com.dds.security.SecurityUtil;

/**This is a test harness class used to

* encrypt and decrypt the string based

* upon the Public and Private key.

* This class also helps to test how

* Public and Private key can be created.

* @author Debadatta Mishra(PIKU)

*

*/

public class SecurityTestHarness

{

public static void main(String[] args)

{

try

{

/*

* The following lines will generate the

* PublicKey and PrivateKey files.

*/

KeyCreator keyCreator = new KeyCreator();

PublicKey publicKey = keyCreator.getPublicKey();

PrivateKey privateKey = keyCreator.getPrivateKey();

/*

* Generate two files named Public.key and Private.key

*/

keyCreator.writeKey(“Public.key”, publicKey.getEncoded());

keyCreator.writeKey(“Private.key”, privateKey.getEncoded());

/*

* Get the public and private key

*/

KeyReader keyReader = new KeyReader();

PublicKey publicKey2 = keyReader.getPublicKey(“Public.key”);

System.out.println(“Public Key—-”+publicKey2);

PrivateKey privateKey2 = keyReader.getPrivateKey(“Private.key”);

System.out.println(“Private Key—-”+privateKey2);

String str = “Hi, Hello World, Welcome to the World of Java”;

byte[] stringBytes = str.getBytes();

byte[] encryptedBytes = SecurityUtil.getEncryptedBytes(

stringBytes, privateKey2);

String encryptedString = new String(encryptedBytes);

System.out.println(“EncryptedString—-”+encryptedString);

byte[] decryptedBytes = SecurityUtil.getDecryptedBytes(encryptedBytes, publicKey2);

System.out.println(“Decrypted String—-”+new String(decryptedBytes));

}

catch( Exception e )

{

e.printStackTrace();

}

}

}

To test the above programs, please create the appropriate package as mentioned in the program. You can also create your own package and modify the package name in the above programs. You can all the code in your favorable java editor.

Conclusion I hope that you will enjoy my article. If you find any problems or errors, please feel free to send me a mail in the address debadattamishra@aol.com . This article is only meant for those who are new to java development. This article does not bear any commercial significance. Please provide me the feedback about this article.