Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

encrypt & decrypt using keystore

843811May 31 2005 — edited May 31 2005
I have created a keystore using the below command.

C:\temp>keytool -genkey -keystore mykeystore.jks -alias myalias
Enter keystore password: mypassword
after this i have enter required inputs.

how do use this keystore and javax.crypto.Cipher class to Encrypt and Decrypt the String.
The encrypted String will be set as hidden form field.
import java.security.*;
import java.security.cert.Certificate;
import javax.crypto.Cipher;

class CipherTest
{
	private String strFileName;
	private String strKeyStoreFileName = "c:/temp/mykeystore.jks";
	private String strData;
	private char chrPassword[] = null;
	
	private CipherTest()
	{
		strFileName =  "c:/temp/temp.txt";
		chrPassword = "mypassword".toCharArray();
		strData = "Hello world";
	}
	
	public static void main(String[] args) throws Exception
	{
		CipherTest sec = new CipherTest();
		sec.encrypt();
	}

	private Certificate getCertificate() throws Exception 
	{
		FileInputStream fisKeyStore = new FileInputStream(strKeyStoreFileName);
		KeyStore ks = KeyStore.getInstance("JKS", "SUN"); // #1
		ks.load(fisKeyStore, chrPassword);
		Certificate certificate = ks.getCertificate("myalias");
		return certificate;
	}

	private void encrypt() throws Exception
	{
		FileOutputStream fos = new FileOutputStream(strFileName);
		Cipher cipher = Cipher.getInstance("DES"); // #2
		cipher.init(Cipher.ENCRYPT_MODE, getCertificate());
		System.out.println(cipher.doFinal(strData.getBytes()));
	}
}
#1 what do i use as parameter to KeyStore.getInstance(?)
#2 what do use as parameter to Cipher.getInstance(?)

encrypt() method is throwing an Exception
java.security.InvalidKeyException: Invalid key length: 443 bytes
	at com.sun.crypto.provider.DESCipher.engineGetKeySize(DashoA6275)
	at javax.crypto.Cipher.init(DashoA6275)
	at javax.crypto.Cipher.init(DashoA6275)
	at com.test.security.CipherTest.encrypt(CipherTest.java:46)
	at com.test.security.CipherTest.main(CipherTest.java:30)
Exception in thread "main" 
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 28 2005
Added on May 31 2005
2 comments
770 views