encrypt and serialize by one --- deserialize and decrypt by another - java

I have serializable object:
import java.io.Serializable;
public class ConfigObject implements Serializable{
private String url;
private String user;
private String pass;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
and 2 method in SerializableEncryptDecrypt class:
public static void encrypt(Serializable object, OutputStream ostream, byte[] keyy, String transformationnn) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
try {
// Length is 16 byte
SecretKeySpec sks = new SecretKeySpec(keyy, transformationnn);
// Create cipher
Cipher cipher = Cipher.getInstance(transformationnn);
cipher.init(Cipher.ENCRYPT_MODE, sks);
SealedObject sealedObject = new SealedObject(object, cipher);
// Wrap the output stream
CipherOutputStream cos = new CipherOutputStream(ostream, cipher);
ObjectOutputStream outputStream = new ObjectOutputStream(cos);
outputStream.writeObject(sealedObject);
outputStream.close();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
}
public static Object decrypt(InputStream istream, byte[] keyy, String transformationnn) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
SecretKeySpec sks = new SecretKeySpec(keyy, transformationnn);
Cipher cipher = Cipher.getInstance(transformationnn);
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cipherInputStream = new CipherInputStream(istream, cipher);
ObjectInputStream inputStream = new ObjectInputStream(cipherInputStream);
SealedObject sealedObject;
try {
sealedObject = (SealedObject) inputStream.readObject();
return sealedObject.getObject(cipher);
} catch (ClassNotFoundException | IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
return null;
}
}
I had made 2 softwares(soft1 and soft2) which use this class (SerializableEncryptDecrypt). That softwares encrypt and serialize input data(the same input data). when I compare the output data with the input which I give is totally different data. But I need the same output data.
thanks in advance for your help.

It is a good practice to randomize encryption using some salt (nonce, IV, ...) so even if you encrypt with the same values with the same key, you may (and should) get different output. Having the same output lowers the security in some cases.
I cannot be sure, but I'd bet that's what the "SealedObject" does. If you really need "the same output", you could serialize the object directly (not using the SealedObject). But then - you are responsible for storing the salt, authentication tag, etc..
Please note - if you're using this code in some real project, you should not store the passwords (even encrypted), only their salted cryptographic hashes if neccessary.

Related

Is there an encryption not working on string format

I have facing issue after applying encryption into a string, I want to decrypt that encrypted_string to a normal string, But none of the examples is working.
Also, they are working for byte array code, Byte_array encrypted and decrypted very well, But I need this working for the string.
Example, I tried already,
How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?
public static String encrypt(String strClearText,String strKey) throws Exception{
String strData="";
try {
SecretKeySpec skeyspec=new SecretKeySpec(strKey.getBytes(),"Blowfish");
Cipher cipher=Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, skeyspec);
byte[] encrypted=cipher.doFinal(strClearText.getBytes());
strData=new String(encrypted);
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e);
}
return strData;
}
public static String decrypt(String strEncrypted,String strKey) throws Exception{
String strData="";
try {
SecretKeySpec skeyspec=new SecretKeySpec(strKey.getBytes(),"Blowfish");
Cipher cipher=Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, skeyspec);
byte[] decrypted=cipher.doFinal(strEncrypted.getBytes());
strData=new String(decrypted);
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e);
}
return strData;
}
String to byte[] then byte[] to string conversion not working properly?
You can use Base64 enocde and decode.
Example:
package test;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class Test2 {
public static void main(String[] args) throws Exception {
String key = "abc123!";
String encrypted = encrypt("test", key);
System.out.println(encrypted);
String decrypted = decrypt(encrypted, key);
System.out.println(decrypted);
}
public static String encrypt(String strClearText, String strKey) throws Exception {
String strData = "";
try {
SecretKeySpec skeyspec = new SecretKeySpec(strKey.getBytes(), "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, skeyspec);
byte[] encrypted = cipher.doFinal(Base64.getDecoder().decode(strClearText));
strData = Base64.getEncoder().encodeToString(encrypted);
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e);
}
return strData;
}
public static String decrypt(String strEncrypted, String strKey) throws Exception {
String strData = "";
try {
SecretKeySpec skeyspec = new SecretKeySpec(strKey.getBytes(), "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, skeyspec);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(strEncrypted));
strData = Base64.getEncoder().encodeToString(decrypted);
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e);
}
return strData;
}
}
Output:
Fsmwp8c1n9w=
test
Here simple encoding and decoding (above kitkat)
Write this class and just call method
class EncodeDecode
{
public String encodeString(String text)
{
String b64;
byte[] data=new byte[0];
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT)
{
data=text.getBytes(StandardCharsets.UTF_8);
b64=Base64.encodeToString(data,Base64.DEFAULT);
}
return b64;
}
public String decodeString(String text)
{
String deString;
if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.KITKAT)
{
byte[] data2=Base64.decode(base64,Base64.DEFAULT);
deString=new String (data2,StandardCharsets.UTF_8);
}
return deString;
}
}
I hope this answer will help you..

Is there a maximum base64 size for a encoded string?

I'm using Base64 for encode a very huge JSON string with thousands of data, after encoded I'm storing on disk. Later I'm retrieving again from disk and decoding it again into readable normal string JSON.
public static String encryptString(String string) {
byte[] bytesEncoded = Base64.getMimeEncoder().encode(string.getBytes());
return (new String(bytesEncoded));
}
public static String decryptString(String string) {
byte[] bytesDecoded = Base64.getMimeDecoder().decode(string);
return (new String(bytesDecoded));
}
Does a limitation exist in the size of the Base64 encode and decode functions? Or am I able to encode and decode super big strings?
No maximum size, but I'd like to also suggest different approach to encrypt and decrypt
Encrypt
public static String encrypt(String strClearText,String strKey) throws Exception{
String strData="";
try {
SecretKeySpec skeyspec=new SecretKeySpec(strKey.getBytes(),"Blowfish");
Cipher cipher=Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, skeyspec);
String isoText = new String(strClearText.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); // there are shorthand ways of doing this, but this is for your explaination
byte[] encrypted=cipher.doFinal(isoText.getBytes(StandardCharsets.ISO_8859_1));
strData=Base64.getEncoder().encodeToString(encrypted);
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e);
}
return strData;
}
Decrypt
public static String decrypt(String strEncrypted,String strKey) throws Exception{
String strData="";
try {
SecretKeySpec skeyspec=new SecretKeySpec(strKey.getBytes(),"Blowfish");
Cipher cipher=Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, skeyspec);
byte[] decrypted=cipher.doFinal(Base64.getDecoder().decode(strEncrypted));
isoStrData=new String(decrypted, StandardCharsets.ISO_8859_1);
strData=new String(isoStrData.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e);
}
return strData;
}
key can always be a constant in your program, but it is not recommended.

Android AES decryption returning rare characters

I'm trying to decrypt a String text with the AES algorithm and I found many tutorials but still getting the same error when I try to decrypt the String.
Here is my class:
EditText inputText, inputPass;
TextView out;
Button btnEnc, btnDec;
String outputString;
private static final String AES_MODE = "AES";
View.OnClickListener encryption= new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
outputString= encrypt(inputText.getText().toString(),inputPass.getText().toString());
} catch (Exception e) {
e.printStackTrace();
}
out.setText(outputString);
}
};
View.OnClickListener decryption= new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
outputString= decrypt(outputString,inputPass.getText().toString());
} catch (Exception e) {
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
e.printStackTrace();
}
out.setText(outputString);
}
};
private String encrypt(String data, String pass)throws Exception{
SecretKeySpec key= generateKey(pass);
Cipher c= Cipher.getInstance(AES_MODE);
c.init(Cipher.ENCRYPT_MODE,key);
byte[] encVal= c.doFinal(data.getBytes());
String encryptedValue= Base64.encodeToString(encVal,Base64.DEFAULT);
return encryptedValue;
}
private String decrypt(String cadena, String password)throws Exception{
SecretKeySpec keySpec= generateKey(password);
Cipher c= Cipher.getInstance(AES_MODE);
c.init(Cipher.DECRYPT_MODE,keySpec);
byte[] decValue= Base64.decode(cadena, Base64.DEFAULT);
String decryptedValue= new String((decValue));
return decryptedValue;
}
private SecretKeySpec generateKey(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
final MessageDigest digest= MessageDigest.getInstance("SHA-256");
byte[] bytes= password.getBytes("UTF-8");
digest.update(bytes,0,bytes.length);
byte[] key= digest.digest();
SecretKeySpec secretKeySpec= new SecretKeySpec(key, "AES");
return secretKeySpec;
}
The problem is when I try to retrieve the Decrypted string because it returns this:
As you can see, the output text contains Unicode characters and not the text that I've encrypted. What would be the problem?
You forgot to actually call your cipher in the decrypt method.
private String decrypt(String cadena, String password)throws Exception{
SecretKeySpec keySpec= generateKey(password);
Cipher c= Cipher.getInstance(AES_MODE);
c.init(Cipher.DECRYPT_MODE,keySpec);
byte[] decValue= c.doFinal(Base64.decode(cadena, Base64.DEFAULT));
// ^^^^^^^^^ add this
String decryptedValue= new String((decValue));
return decryptedValue;
}
Furthermore, you should always explicitly specify an encoding when converting from a byte[] to a String or vice versa.

Android - IllegalBlockSizeException: last block incomplete in decryption

I am using the service like this
String value = "test#example.com"
String encrypedValue = EncrypterService get().encrypt(value.getBytes())
String decryptedValue = EncrypterService get().decrypt(encrypedValue .getBytes())
public final class EncrypterService {
private static Key keySpec;
private static Cipher encryptCipher;
private static Cipher decryptCipher;
private static String passphrase = "IU1ZaypiTiVYc3AtPXMxNWNMYGUmVUF8YUAtUSMuKVI=";
private static final String KEY_ALGORIGHT = "HmacSHA256";
private static final String CIPHER_ALGORITHM = "AES";
private static final String MD5_ALGORITH = "MD5";
private static EncrypterService service;
private EncrypterService(){
}
private static synchronized void initialize() {
if (service == null) {
service = new EncrypterService();
service.init();
}
}
public static EncrypterService get() {
initialize();
return service;
}
public String encrypt (byte[] plaintext){
//returns byte array encrypted with key
try {
byte[] encode = encryptCipher.doFinal(plaintext);
return new String(encode);
}catch(Exception e){
throw new RuntimeException("Unable to decrypt data" + e);
}
}
public String decrypt (byte[] ciphertext) {
//returns byte array decrypted with key
try {
byte[] decode = decryptCipher.doFinal(ciphertext);
return new String(decode);
}catch(Exception e){
throw new RuntimeException("Unable to decrypt data" + e);
}
}
private static void init(){
try {
if (encryptCipher == null && decryptCipher == null) {
byte[] bytesOfMessage = Base64.decode(passphrase, Base64.NO_WRAP);
MessageDigest md = MessageDigest.getInstance(MD5_ALGORITH);
byte[] thedigest = md.digest(bytesOfMessage);
keySpec = new SecretKeySpec(thedigest, KEY_ALGORIGHT);
encryptCipher = Cipher.getInstance(CIPHER_ALGORITHM);
encryptCipher.init(Cipher.ENCRYPT_MODE, keySpec);
decryptCipher = Cipher.getInstance(CIPHER_ALGORITHM);
decryptCipher.init(Cipher.DECRYPT_MODE, keySpec);
}
}catch(Exception e){
throw new RuntimeException("Unable to initialise encryption", e);
}
}
}
stacktrace
java.lang.RuntimeException·Unable to decrypt datajavax.crypto.IllegalBlockSizeException: last block incomplete in decryption
Full TraceRaw
EncrypterService .java:59 EncrypterService .decrypt
Issue#1:
java.security.MessageDigest will provide an instance of MD5 digest.
For this, you need to import the following
import java.security.*;
Issue#2:
For encrypedValue, you are using value.getBytes() and
For decryptedValue , you are using encrypedValue .getBytes().
Here is some limitation for using getBytes(). It is platform independent.
so you should use getBytes("UTF-8") instead of getBytes()
byte[] bytesOfMessage = yourString.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance(MD5_ALGORITH);
byte[] thedigest = md.digest(bytesOfMessage);
Resource Link: How can I generate an MD5 hash?
Issue#3: Encoding and Decoding
Mr. Andrea suggested like below:
In Java 8, there is an officially supported API for Base64 encoding
and decoding
Sample code using the "basic" encoding:
import java.util.Base64;
byte[] bytes = "Hello, World!".getBytes("UTF-8");
String encoded = Base64.getEncoder().encodeToString(bytes);
byte[] decoded = Base64.getDecoder().decode(encoded);
Resource Link: Decode Base64 data in Java
return new String(encode);
The problem is here. String is not a container for binary data. The round trip between byte[] and String is not guaranteed. You should either just pass around the original byte[] or else hex- or base64-encode it.

IllegalBlockSizeException need to resolve

I have written my program in java by following this tutorial http://www.java2s.com/Code/Android/Security/AESEncryption.htm
But i am getting an exception i.e. "javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher"
Can anybody help me?
public class utils {
public static String encrypt(String message,String secretPhrase){
try{
MessageDigest mdig=MessageDigest.getInstance("MD5");
byte[] digestedBytes=mdig.digest(secretPhrase.getBytes("UTF-8"));
SecretKeySpec keySpec=new SecretKeySpec(digestedBytes,"AES");
Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encryptedBytes=cipher.doFinal(message.getBytes("UTF-8"));
return new String(encryptedBytes,"UTF-8");
}catch(Exception exc){
return null;
}
}
public static String decrypt(String message,String secretPhrase){
try{
MessageDigest mdig=MessageDigest.getInstance("MD5");
byte[] digestedBytes=mdig.digest(secretPhrase.getBytes("UTF-8"));
SecretKeySpec keySpec=new SecretKeySpec(digestedBytes,"AES");
Cipher cipher=Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] encryptedBytes=cipher.doFinal(message.getBytes("UTF-8"));
return new String(encryptedBytes,"UTF-8");
}catch(Exception exc){
return null;
}
}
}
Well try this ,
public String encrypt(String str) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
} catch (Exception e) {
}
return null;
}
public String decrypt(String str) {
try {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
// Decrypt
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
} catch (Exception e) {
}
return null;
}
Example using it
try {
// Generate a temporary key. In practice, you would save this key.
// See also Encrypting with DES Using a Pass Phrase.
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter(key);
// Encrypt
String encrypted = encrypter.encrypt("Don't tell anybody!");
// Decrypt
String decrypted = encrypter.decrypt(encrypted);
} catch (Exception e) {
}

Categories

Resources