About Me

My photo
India
Hey there, lovely people! I'm Hemant Menaria, and I'm passionate about programming. Having completed my MCA in 2011, I've delved into the world of coding with fervor. I believe in sharing knowledge, making complex concepts easy to grasp for everyone. JAVA, PHP, and ANDROID hold a special place in my heart, and I spend most of my time immersed in them. Currently, I'm deeply engaged in API/Webservice frameworks and crafting Hybrid mobile applications to enhance flexibility in the digital realm. If you ever find yourself stuck with a programming challenge, feel free to reach out to me at +91-8955499900 or drop me a line at hemantmenaria008@gmail.com. I'm always eager to help fellow enthusiasts navigate the intricacies of coding!

Saturday, November 3, 2012

How to embed images in HTML mail using JavaMail

/* How to embed images in HTML mail using JavaMail */
// Create message

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
message.setSubject(subject);

// Add html content
// Specify the cid of the image to include in the email

String html = "Test email ";
Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(html, "text/html");
mp.addBodyPart(htmlPart);

// add image in another part

MimeBodyPart imagePart = new MimeBodyPart();
DataSource fds = new FileDataSource(imagePath);
imagePart.setDataHandler(new DataHandler(fds));
// assign a cid to the image
imagePart.setHeader("Content-ID", "my-image-id");
mp.addBodyPart(imagePart);

message.setContent(mp);

// Send the message

Transport.send(message);

Friday, May 25, 2012

AES Encryption - Decryption

//AES Encryption - Decryption

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import org.bouncycastle.crypto.digests.SHA1Digest;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.NoSuchPaddingException;
import org.bouncycastle.crypto.generators.PKCS5S1ParametersGenerator;
import javax.crypto.Cipher;
import org.bouncycastle.crypto.params.KeyParameter;


public class AESEncryptionDecrytionString {
    /**
     * @param args
     */
    static byte[] iv ="OFRna73m*aze01xY".getBytes();
    static byte[] salt="saltkey".getBytes();
    static String password="passwordkey";
    static int iterations=2,keySize=128;
    static String cipher_instance="AES/CBC/PKCS5Padding",algo="AES";   
   
    public static String encrypt(String strDataToEncrypt) throws NoSuchAlgorithmException, NoSuchPaddingException
    {       
        String strCipherText = new String();           
        try 
        {   

            PKCS5S1ParametersGenerator generator = new
            PasswordDeriveBytes(new SHA1Digest());
            generator.init(password.getBytes(), salt, iterations);
            byte[] key = ((KeyParameter)
                    generator.generateDerivedParameters(keySize)).getKey();
            SecretKey secretKey = new SecretKeySpec(key, algo);
            Cipher aesCipher = Cipher.getInstance(cipher_instance);   
            aesCipher.init(Cipher.ENCRYPT_MODE,secretKey,new IvParameterSpec(iv));
            byte[] byteDataToEncrypt = strDataToEncrypt.getBytes("UTF8");
            byte[] byteCipherText = aesCipher.doFinal(byteDataToEncrypt); 
            strCipherText =new String(byteCipherText);//.apache.commons.codec.binary.Base64.encodeBase64String(byteCipherText);// BASE64Encoder().encode(byteCipherText);
            byte[] b=org.apache.commons.codec.binary.Base64.encodeBase64(byteCipherText);
            strCipherText=new String(b);
        } 
        catch (Exception e) 
        {
            System.out.println(e.getMessage());
        }
        return strCipherText;       
    }

    public static String decrypt(String strCipherText) throws NoSuchAlgorithmException, NoSuchPaddingException
    {
        String strDecryptedText = new String();
        try
        {
            SecretKeySpec secretKey = new SecretKeySpec(password.getBytes(), "AES");
            PKCS5S1ParametersGenerator generator = new
            PasswordDeriveBytes(new SHA1Digest());
            generator.init(password.getBytes(), salt, iterations);
            byte[] key = ((KeyParameter)
                    generator.generateDerivedParameters(keySize)).getKey();
            secretKey = new SecretKeySpec(key, algo);
            Cipher aesCipher = Cipher.getInstance(cipher_instance);       
            aesCipher.init(Cipher.DECRYPT_MODE,secretKey,new IvParameterSpec(iv));
            byte[] byteCipherText=org.apache.commons.codec.binary.Base64.decodeBase64(strCipherText.getBytes());

            byte[] byteDecryptedText = aesCipher.doFinal(byteCipherText);
            strDecryptedText = new String(byteDecryptedText);
        }
        catch (Exception e) 
        {
            System.out.println(e.getMessage());
        }       

        return strDecryptedText;       
    }

    public static String encryptString(String strDataToEncrypt,String newkey) throws NoSuchAlgorithmException, NoSuchPaddingException
    {       
        String strCipherText = new String();           
        try 
        {   
           
            PKCS5S1ParametersGenerator generator = new
            PasswordDeriveBytes(new SHA1Digest());
            generator.init(newpassword.getBytes(), salt, iterations);
            byte[] key = ((KeyParameter)
                    generator.generateDerivedParameters(keySize)).getKey();
            SecretKey secretKey = new SecretKeySpec(key, algo);
            Cipher aesCipher = Cipher.getInstance(cipher_instance);   
            aesCipher.init(Cipher.ENCRYPT_MODE,secretKey,new IvParameterSpec(iv));
            byte[] byteDataToEncrypt = strDataToEncrypt.getBytes("UTF8");
            byte[] byteCipherText = aesCipher.doFinal(byteDataToEncrypt); 
            strCipherText =new String(byteCipherText);//.apache.commons.codec.binary.Base64.encodeBase64String(byteCipherText);// BASE64Encoder().encode(byteCipherText);
            byte[] b=org.apache.commons.codec.binary.Base64.encodeBase64(byteCipherText);
            strCipherText=new String(b);
        } 
        catch (Exception e) 
        {
            System.out.println(e.getMessage());
        }
        return strCipherText;       
    }

    public static String decryptString(String strCipherText,String newkey) throws NoSuchAlgorithmException, NoSuchPaddingException
    {
       
        String strDecryptedText = new String();
        try
        {
            SecretKeySpec secretKey = new SecretKeySpec(password.getBytes(), "AES");
            PKCS5S1ParametersGenerator generator = new
            PasswordDeriveBytes(new SHA1Digest());
            generator.init(newkey.getBytes(), salt, iterations);
            byte[] key = ((KeyParameter)
                    generator.generateDerivedParameters(keySize)).getKey();
            secretKey = new SecretKeySpec(key, algo);
            Cipher aesCipher = Cipher.getInstance(cipher_instance);       
            aesCipher.init(Cipher.DECRYPT_MODE,secretKey,new IvParameterSpec(iv));
            byte[] byteCipherText=org.apache.commons.codec.binary.Base64.decodeBase64(strCipherText.getBytes());

            byte[] byteDecryptedText = aesCipher.doFinal(byteCipherText);
            strDecryptedText = new String(byteDecryptedText);
        }
        catch (Exception e) 
        {
            System.out.println(e.getMessage());
        }       

        return strDecryptedText;       
    }
}

Linux send mail configuration

Send mail through linux command prompt

Send mail  Configuration

Step 1: Installation
   
    yum install sendmail-cf

Step 2: Open file /etc/mail/sendmail.mc
       
Step 3:    Comment line (116) by putting dnl in front of this line
    ex:- dnl DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1, Name=MTA')dnl

Step 4: Create Sendmail configuration file ...by executing these command

    m4 sendmail.mc > sendmail.cf

Step 5:  Start sendmail Service

    /etc/init.d/sendmail start

Step 6: Add Sendmail service in Hosts.deny so no one can use it except loopback.
    i) open /etc/hosts.allow file and past this:

        sendmail: 127.0.0.1    

    ii) now open /etc/hosts.deny file and past this:
   
        sendmail: ALL    

Thursday, May 24, 2012

MySQL from linux command prompt


How to use MySQL from SSH (Linux shell)

Posted by Aman Brar on in MySQL, SSH
Using MySQL from SSH may seem to be quite tricky if you’ve never done it before – but fear not – below is a list of MySQL commands that you can use to perform the required actions.
Start by logging-in using a SSH client, like PuTTY, to access the shell command line.
Below when you see # it means from the unix shell. And when you see mysql> it means from a MySQL prompt after logging into MySQL.
To login (from unix shell) use -h hostname only if needed
# mysql -h hostname -u root -p
This would ask you for a password and after providing the correct password you’d be logged-in to the MySQL prompt.
If you get an error with the above command then type # which mysql to make sure that mysql is installed properly and to find the directory. It would print out the mysql directory, and then you can use the above command as this: # [mysql dir]/bin/mysql -h hostname -u root -p
Create a database
mysql> create database [database name];
List all databases
mysql> show databases;
Switch to a database
mysql> use [database name];
To see all the tables in the selected database
mysql> show tables;
To see the database’s field formats
mysql> describe [table name];
To delete a database
mysql> drop database [database name];
To delete a table
mysql> drop table [table name];
Show all data in a table
mysql> SELECT * FROM [table name];
Show the columns and column information pertaining to the designated table
mysql> show columns from [table name];
Show certain selected rows with the value “whatever”
mysql> SELECT * FROM [table name] WHERE [field name] = "whatever";
Show all records containing the name “Bob” AND the phone number ’3444444′
mysql> SELECT * FROM [table name] WHERE name = "Bob" AND phone_number = '3444444';
Show all records not containing the name “Bob” AND the phone number ’3444444′ order by the phone_number field
mysql> SELECT * FROM [table name] WHERE name != "Bob" AND phone_number = '3444444' order by phone_number;
Show all records starting with the letters ‘bob’ AND the phone number ’3444444′
mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number = '3444444';
Show all records starting with the letters ‘bob’ AND the phone number ’3444444′ limit to records 1 through 5
mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number = '3444444' limit 1,5;
Use a regular expression to find records. Use “REGEXP BINARY” to force case-sensitivity. This finds any record beginning with a
mysql> SELECT * FROM [table name] WHERE rec RLIKE "^a";
Show unique records
mysql> SELECT DISTINCT [column name] FROM [table name];
Show selected records sorted in an ascending (asc) or descending (desc)
mysql> SELECT [col1],[col2] FROM [table name] ORDER BY [col2] DESC;
Return number of rows
mysql> SELECT COUNT(*) FROM [table name];
Sum column
mysql> SELECT SUM(*) FROM [table name];
Join tables on common columns
mysql> select lookup.illustrationid, lookup.personid,person.birthday from lookup left join person on lookup.personid=person.personid=statement to join birthday in person table with primary illustration id;
Creating a new user (login as root, switch to the MySQL db, make the user, update privs)
# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO user (Host,User,Password) VALUES('%','username',PASSWORD('password'));
mysql> flush privileges;

Change a user’s password from unix shell
# [mysql dir]/bin/mysqladmin -u username -h hostname.blah.org -p password 'new-password'
Change a user’s password from MySQL prompt (login as root, set the password, update privs)
# mysql -u root -p
mysql> SET PASSWORD FOR 'user'@'hostname' = PASSWORD('passwordhere');
mysql> flush privileges;

Recover a MySQL root password (stop the MySQL server process, start again with no grant tables, login to MySQL as root, set new password, exit MySQL and restart MySQL server)
# /etc/init.d/mysql stop
# mysqld_safe --skip-grant-tables &
# mysql -u root
mysql> use mysql;
mysql> update user set password=PASSWORD("newrootpassword") where User='root';
mysql> flush privileges;
mysql> quit
# /etc/init.d/mysql stop
# /etc/init.d/mysql start

Set a root password if there is on root password
# mysqladmin -u root password newpassword
Update a root password
# mysqladmin -u root -p oldpassword newpassword
Allow the user “bob” to connect to the server from localhost using the password “passwd” (login as root, switch to the MySQL db, give privs, update privs)
# mysql -u root -p
mysql> use mysql;
mysql> grant usage on *.* to bob@localhost identified by 'passwd';
mysql> flush privileges;

Give a user privileges for a database (login as root, switch to the MySQL db, grant privs, update privs)
# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO db (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv) VALUES ('%','databasename','username','Y','Y','Y','Y','Y','N');
mysql> flush privileges;

or
mysql> grant all privileges on databasename.* to username@localhost;
mysql> flush privileges;

To update info already in a table
mysql> UPDATE [table name] SET Select_priv = 'Y',Insert_priv = 'Y',Update_priv = 'Y' where [field name] = 'user';
Delete a row(s) from a table
mysql> DELETE from [table name] where [field name] = 'whatever';
Update database permissions/privileges
mysql> flush privileges;
Delete a column
mysql> alter table [table name] drop column [column name];
Add a new column to db
mysql> alter table [table name] add column [new column name] varchar (20);
Change column name
mysql> alter table [table name] change [old column name] [new column name] varchar (50);
Make a unique column so you get no dupes
mysql> alter table [table name] add unique ([column name]);
Make a column bigger
mysql> alter table [table name] modify [column name] VARCHAR(3);
Delete unique from table
mysql> alter table [table name] drop index [colmn name];
Load a CSV file into a table
mysql> LOAD DATA INFILE '/tmp/filename.csv' replace INTO TABLE [table name] FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (field1,field2,field3);
Dump all databases for backup. Backup file is sql commands to recreate all db’s
# [mysql dir]/bin/mysqldump -u root -ppassword --opt >/tmp/alldatabases.sql
Dump one database for backup
# [mysql dir]/bin/mysqldump -u username -ppassword --databases databasename >/tmp/databasename.sql
Dump a table from a database
# [mysql dir]/bin/mysqldump -c -u username -ppassword databasename tablename > /tmp/databasename.tablename.sql
Restore database (or database table) from backup
# [mysql dir]/bin/mysql -u username -ppassword databasename < /tmp/databasename.sql
Create Table Example 1
mysql> CREATE TABLE [table name] (firstname VARCHAR(20), middleinitial VARCHAR(3), lastname VARCHAR(35),suffix VARCHAR(3),officeid VARCHAR(10),userid VARCHAR(15),username VARCHAR(8),email VARCHAR(35),phone VARCHAR(25), groups VARCHAR(15),datestamp DATE,timestamp time,pgpemail VARCHAR(255));
Create Table Example 2
mysql> create table [table name] (personid int(50) not null auto_increment primary key,firstname varchar(35),middlename varchar(50),lastnamevarchar(50) default 'bato');

Thursday, May 3, 2012

SSL, tomcat and self signed certificates

I have been through the process of getting an application to work via https before but I have always muddled through and never documented exactly what I have done.

I must also admit that I never quite understood exactly what I had done and why.

One problem is that I can not find one place that covers everything you need in one place.

Now I think I am pretty well there.

This post describes what I have done to get a simple client application working using HTTPS posting to tomcat server and using a self signed certificate with the help of several refereneces in particular:

The last reference has a chapter which is pretty well SSL for dummies and explains things very nicely.

The steps that need to be done are:
  1. Create a self signed certificate authority (CA)
  2. Sign a test key via the CA
  3. Add both these keys to a keystore
  4. Setup the application (client) and tomcat (the server) to use this keystore.

1) Create a self signed certificate authority (CA) and keystore

This is described in How to create a self signed certificate, but I will show the steps here

What is happening here:
you will create a CA that later will be added to your keystore file. By adding this CA to your keystore you are saying it is trusted like verisign and any certificates signed by it are then also trusted.


1.1) make a directory to hold the certs and keystore. This might be something like:
C:\ssl 
1.2) generate a private key for the server
openssl genrsa -des3 -out server.key 1024
1.3) generate a CSR (Certificate Signing Request)
openssl req -new -key server.key -out server.csr
1.4) Remove the passphrasse from the key
cp server.key server.key.org

openssl rsa -in server.key.org -out server.key

1.5) Generate the self signed certificate
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt


2) Create a certificate for tomcat and add both to the keystore

2.1) cd to where the keystore is held. This might be something like:
C:\ssl


2.2) Create a keypair for 'tomcat'
keytool -genkey -alias tomcat  -keyalg RSA -keystore tomcat.ks


2.3) Generate a CSR (Certificate Signing Request) for tomcat
keytool -keystore tomcat.ks -alias tomcat -certreq -file tomcat.csr


2.4) create unique serial number
echo 02 > serial.txt


2.5) Sign the tomcat CSR
openssl x509 -CA server.crt -CAkey server.key -CAserial serial.txt -req -in tomcat.csr -out tomcat.cer -days 365

2.6) Import the server CA certificate into the keystore (Keytool path Ex: usr/java/jdk1.7....../bin/keytool)
keytool -import -alias serverCA -file server.crt -keystore tomcat.ks


2.7) add the tomcat certificate to the keystore
keytool -import -alias tomcat -file tomcat.cer -keystore tomcat.ks


3) Tomcat configuration
3.1) Tomcat needs to be configured to use SSL
This is described in more detail at Tomcat SSL Configuration How-To
However all that is needed here is to edit the server.xml to enable SSL
This section is already in the server.xml but commented out.
NB that the location of the keystore has been added.


< !-- Define a SSL HTTP/1.1 Connector on port 8443
This connector uses the JSSE configuration, when using APR, the
connector should be using the OpenSSL style configuration
described in the APR documentation -- >
< Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
keystoreFile="C:\ssl\tomcat.ks"
keystorePass="changeit"
clientAuth="false" sslProtocol="TLS" / >

3.2) test tomcat
start tomcat and go to https://localhost:8443/

your browser will return an error such as "sites certificate is not trusted"

3.3) import the CA certificate server.crt into your browser's tructed root certificates

3.4) test again at https://localhost:8443/

this time you should see the tomcat home page

4) Test your application

4.1) I have a unit test run from eclipse that I have been using to post off to my test server. This produces the error;

Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:174)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:238)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:289)

4.2) The reason for this is that eclipse is not referring to the keystore that we have created. At the time of writing I have not sussed out how to make eclipse use this - Do you know ?
So instead I have added the same two certs to javas keystore

4.3) cd to the directory where java's keystore is held. This might be something like:
C:\java\jdk1.6.0_18\jre\lib\security


4.4) the keystore is a file called cacerts

4.5) copy the files c:\ssl\server.crt and c:\ssl\tomcat.cer to this directory

4.6) import the server CA into the java keystore
keytool -import -alias serverCA -file server.crt -keystore cacerts
4.7 import tomcats cert into the java keystore
keytool -import -alias tomcat -file tomcat.cer -keystore cacerts


5) Test your app again.
Hopefully all will be hunkdory. Enjoy.

6) Caveats:

6.1) the passwords for all keystores and certs are 'changeit'. this is the default keystore password
and I suggest you change this for a production system

6.2) Using a self signed cert is great for a test environment of for a private system but not for a commercial released application. For this you will need to get & pay for a signed certificate from an approved authority such as Verisign.

Wednesday, April 4, 2012

Difference between MS SQL, MySQL and Oracl

One thing you have to watch out for is the fairly severe differences in the way MSSQL and MySQL implement the SQL syntax.

MS SQL works only in Windows and is expensive; MySQL works on Windows and Unix and is free; Oracle works on Windows and Unix and is expensive.  All three can be used to develop high-performance applications."

Moreover, advantages and disadvangates would largely depend on counterpart technologies you plan on using.  Database engines do not exist in a vacuum; they work with some counterparts very well, and not so well with others.  For example, if you are developing a Web application in ASP.Net and expect it to run on a single physical machine (or on a series of parallel machines), SQL Server would be a good choice, because you can take advantage of tight integration of the Microsoft-only software stack; if you plan on having a layered architecture, tight integration is not going to do much for you (IIS and SQL Server are not going to run on the same machine), so you might consider using Oracle on the DB layer.  If you intend to deploy on Linux (or any other Unix or Unix-like platform), this automatically excludes SQL Server from consideration, as it only runs on Windows.  If you intend to write a JSP/Tomcat Web application, you should probably stay away from MySQL, as this pairing is known to have performance issues.  Combinations of other JSP application servers with MySQL have not been extensively tested, so JSP shops tend to lean towards Oracle (especially considering its long history of peaceful and productive co-existence with Java).  If you want to write a scalable PHP or Python application to be deployed on Linux, MySQL will provide an unbeatable combination of price and performance.  

more visit:
Comparison of Different SQL Implementations.