Hello,
I need to encrypt a password and decrypt a password. I use Blowfish/ECB/PKCS5Padding provider to encrypt it. And I use Base64 to encode the string and also to decode it. Encryption is no problem. But decryption doesn't work right. And it is not consistent. Sometimes it decrypts right and sometimes it doesn't. Could someone please tell me whats wrong with my code? Appreciate any help.
Thanks.
The program:
public class SimpleBase64Encryption {
private MessageDigest md;
private SecretKeySpec skspec;
private javax.crypto.Cipher cipher;
private BASE64Decoder decoder = new BASE64Decoder();
private BASE64Encoder encoder = new BASE64Encoder();
public SimpleBase64Encryption(String password) {
try{
Provider sunJce = new com.sun.crypto.provider.SunJCE();
Security.addProvider(sunJce);
md = MessageDigest.getInstance("SHA-1");
byte[] passwordInBytes = decoder.decodeBuffer(password);
skspec = new SecretKeySpec(md.digest(passwordInBytes), "Blowfish");
skspec = new SecretKeySpec(passwordInBytes, "Blowfish");
cipher = javax.crypto.Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
}catch(Exception e1){
e1.printStackTrace();
}
}
public byte[] encrypt(byte[] plain) {
try{
cipher.init(javax.crypto.Cipher.ENCRYPT_MODE,skspec);
return cipher.doFinal(plain);
}catch(Exception e1){
e1.printStackTrace();
return null;
}
}
public byte[] decrypt(byte[] ciphered){
try{
cipher.init(javax.crypto.Cipher.DECRYPT_MODE,skspec);
return cipher.doFinal(ciphered);
}catch(Exception e1){
e1.printStackTrace();
return null;
}
}
public static void main(String[] args){
try{
String plainText = "mysecretvalue";
SimpleBase64Encryption test = new SimpleBase64Encryption(plainText);
System.out.println("Text to encrypt and decrypt: " + plainText);
byte[] encryptedArray = test.encrypt(test.decoder.decodeBuffer(plainText));
System.out.println("encrypted value: " + test.encoder.encode(encryptedArray));
byte[] decryptedArray = test.decrypt(encryptedArray);
System.out.println("decrypted value: " + test.encoder.encode(decryptedArray));
}catch(Exception e){
e.printStackTrace();
}
}
}
Output is:
Text to encrypt and decrypt: mysecretvalue
encrypted value: 40TNQAtWPAxKoe8svF4RZA==
decrypted value: mysecretvalu