Is there an encryption not working on string format - java

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..

Related

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.

Java/Android Cipher Encryption/Decryption

I'm trying to implement a Cipher-Encryption/Decryption class.
Testing it:
System.out.println(MysteryHandler.decrypt(MysteryHandler.encrypt("I like programming!")));
But the result-String is this: >�տm����s��ng!
Class:
public class MysteryHandler {
private static SecretKey secretKey;
private static Cipher cipher;
private static byte[] utf8Bytes;
/**Verschluesseln*/
public static byte[] encrypt(String plainText){
try {
secretKey = KeyGenerator.getInstance("AES").generateKey();
cipher = Cipher.getInstance("AES/CBC/PKCS7PADDING");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
utf8Bytes = plainText.getBytes("UTF8");
return cipher.doFinal(utf8Bytes);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**Entschluesseln*/
public static String decrypt(byte[] secret){
try {
cipher = Cipher.getInstance("AES/CBC/PKCS7PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(secret, secret.length - 16, 16));
utf8Bytes = cipher.doFinal(secret);
return new String(utf8Bytes, "UTF8");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
What am I doing wrong?

javax.crypto.BadPaddingException: Given final block not properly padded DES

I get error when I try to decode.
This is Decoder:
public class Encrypter {
Cipher ecipher;
Cipher dcipher;
SecretKeySpec key = new SecretKeySpec("missyou1".getBytes(), "DES");
public DesEncrypter() throws Exception {
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}
public String encrypt(String str) throws Exception {
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
}
public String decrypt(String str) throws Exception {
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] asd = new byte[(dec.length/8+1)*8];
for(int i = 0; i < dec.length; i++){
asd[i] = dec[i];
}
byte[] utf8 = dcipher.doFinal(asd);
return new String(utf8, "UTF8");
}
}
This is code where I get error:
private static void appenda(Encrypter encrypt) {
if (Files.exists(Paths.get(filePath), new LinkOption[] { LinkOption.NOFOLLOW_LINKS })) {
Stream<String> stringStream = null;
try {
stringStream = Files.lines(Paths.get(filePath), StandardCharsets.UTF_8);
} catch (IOException e) {
LOGGER.error("Failed ", e);
}
if (stringStream.toString() != null) {
stringStream.forEach(s -> {
try {
System.out.println(encrypt.decrypt(s));
endpoint.delete(0, endpoint.length());
endpoint.append(encrypt.decrypt(s));
} catch (Exception e) {
LOGGER.error("Failed to decrypt", e);
}
});
}
}
}
in line endpoint.append(encrypter.decrypt(s));
Any idea why?
Its not working because you are needlessly copying the data into an incorrectly sized array.
Just remove the array copy and decrypt the bytes directly.
public String decrypt(String str) throws Exception {
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
}

Encrypt and Decrypt a String with RSA

I am a new bee to Java Security and Crypto. Below code does not return me the correct decryption.
Also please let me know any recommendation for using an algorithm to make a strong key.
Below code has two methods one is for encryption a String and the other is for decryption.
public class TestSecurityDiscussions {
public static byte[] encryptData(KeyPair keys){
String rawData = "Hi how are you>?";
Cipher cipher = Cipher.getInstance("RSA");
try {
cipher.init(Cipher.ENCRYPT_MODE, keys.getPublic());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] encrypted = cipher.doFinal(rawData.getBytes());
return encrypted;
}
public static String decryptData(byte[] encrypted,KeyPair keys) {
Cipher cipher = Cipher.getInstance("RSA");
try {
cipher.init(Cipher.DECRYPT_MODE, keys.getPrivate());
} catch (Exception e) {
e.printStackTrace();
}
byte[] deycrypted = cipher.doFinal(encrypted);
return deycrypted.toString();
}
public static void main(String[] args) {
KeyPair keys = KeyPairGenerator.getInstance("RSA").generateKeyPair();
byte[] keydata = encryptData(keys);
System.out.println("======>"+decryptData(keydata,keys));
}
}
I think your problem is this line:
return decrypted.toString();
Byte Strings will give a memory location via the toString(). You should do this:
return new String(decrypted);

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