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

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");
}

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

javax.crypto.BadPaddingException: Decryption error

Here is the error I have got when run my Encode & Decode Class.
javax.crypto.BadPaddingException: Decryption error
at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380)
at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:365)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:391)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
at RSAEncDecDemo.decryptData(RSAEncDecDemo.java:64)
at RSAEncDecDemo.main(RSAEncDecDemo.java:47)
java.lang.NullPointerException
at java.lang.String.<init>(String.java:556)
at RSAEncDecDemo.decryptData(RSAEncDecDemo.java:70)
at RSAEncDecDemo.main(RSAEncDecDemo.java:47)
Here is the source code of RSAEncDecDemo.java class file.
public class RSAEncDecDemo {
private static final String PUBLIC_KEY_FILE = "lk.public.key";
private static final String PRIVATE_KEY_FILE = "lk.private.key";
#SuppressWarnings("restriction")
public static void main(String[] args) throws IOException {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
writeStringkey(PUBLIC_KEY_FILE,new BASE64Encoder().encode(publicKey.getEncoded()));
writeStringkey(PRIVATE_KEY_FILE,new BASE64Encoder().encode(privateKey.getEncoded()));
String demoString = "123346";
RSAEncDecDemo rsa = new RSAEncDecDemo();
String decrypted = rsa.decryptData(demoString);
String msisdn = decrypted.substring(0,decrypted.indexOf("|"));
} catch (Exception e) {
e.printStackTrace();
}
}
private String decryptData(String strData) throws IOException {
byte[] data = DatatypeConverter.parseHexBinary(strData);
byte[] descryptedData = null;
try {
PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
descryptedData = cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return new String(descryptedData);
}
#SuppressWarnings("restriction")
public PrivateKey readPrivateKeyFromFile(String fileName)throws IOException, NoSuchAlgorithmException,InvalidKeySpecException {
String publicK = readStringKey(fileName);
byte[] keyBytes = new BASE64Decoder().decodeBuffer(publicK);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory fact = KeyFactory.getInstance("RSA");
return fact.generatePrivate(keySpec);
}
public PrivateKey readPrivateKeyFromFileold(String fileName)throws IOException {
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(new File(fileName));
ois = new ObjectInputStream(fis);
BigInteger modulus = (BigInteger) ois.readObject();
BigInteger exponent = (BigInteger) ois.readObject();
RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey privateKey = fact.generatePrivate(rsaPrivateKeySpec);
return privateKey;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ois != null) {
ois.close();
if (fis != null) {
fis.close();
}
}
}
return null;
}
public static void writeStringkey(String fileName, String data) {
try {
FileWriter out = new FileWriter(new File(fileName));
out.write(data);
out.close();
} catch (IOException e) {
}
}
public static String readStringKey(String fileName) {
BufferedReader reader = null;
StringBuffer fileData = null;
try {
fileData = new StringBuffer(2048);
reader = new BufferedReader(new FileReader(fileName));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
} catch (Exception e) {
} finally {
if (reader != null) {
reader = null;
}
}
return fileData.toString();
}
}
Where is mistaken point.? Decryption part is give that error.
Whole class uploaded here
LINK TO SOURCE CODE
-Thanks
In principle a ciphertext should be indistinguishable from random. That said, ciphers do place constraints on the domain (size and possible values). In the case of RSA PKCS#1 - which is the default mode for "RSA" within the Oracle provider - the output must be precisely the key size (in bytes). Furthermore, the value must be smaller than the modulus.
Now assume that you've just shown us a demo value (because the exception doesn't match the input) and the size of the ciphertext is correct. In that case you would get an unpadding exception when either:
the private key doesn't match the public key used;
the wrong padding mode (e.g. OAEP) was used to create the ciphertext;
the ciphertext was altered (e.g. due to an invalid conversion to a string).
You would have to try until you find the culprit, without the required information we cannot test this for you.

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?

Chacha Encryption in android using sponge castle

I simply want to encrypt and decrypt text in Android using ChaCha20.
I have found some example but can't find a solution to make it in the right way. I want ChaCha encryption. Can someOne guide me how could I achieve it. I tried modifying these code a lot.
SecurityUtil
public class SecurityUtil extends Properties {
public String decrypt(String name, String keyString)
throws Exception {
BlowfishEngine engine = new BlowfishEngine();
PaddedBufferedBlockCipher cipher =
new PaddedBufferedBlockCipher(engine);
StringBuffer result = new StringBuffer();
KeyParameter key = new KeyParameter(keyString.getBytes());
cipher.init(false, key);
byte out[] = Base64.decode(name);
byte out2[] = new byte[cipher.getOutputSize(out.length)];
int len2 = cipher.processBytes(out, 0, out.length, out2, 0);
cipher.doFinal(out2, len2);
String s2 = new String(out2);
for (int i = 0; i < s2.length(); i++) {
char c = s2.charAt(i);
if (c != 0) {
result.append(c);
}
}
return result.toString();
}
public String encrypt(String value, String keyString)
throws Exception {
BlowfishEngine engine = new BlowfishEngine();
PaddedBufferedBlockCipher cipher =
new PaddedBufferedBlockCipher(engine);
KeyParameter key = new KeyParameter(keyString.getBytes());
cipher.init(true, key);
byte in[] = value.getBytes();
byte out[] = new byte[cipher.getOutputSize(in.length)];
int len1 = cipher.processBytes(in, 0, in.length, out, 0);
try {
cipher.doFinal(out, len1);
} catch (CryptoException e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
String s = new String(Base64.encode(out));
return s;
}
}
I have tried changing BlowfishEngine to ChaChaEngine but It is a class not an interface. And tried a lot more way.
AESWrapper
public class AESWrapper {
public byte[] encrypt(byte[] plainData, byte[] key) throws AESEncryptionFailedException {
PaddedBufferedBlockCipher paddedBufferedBlockCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
ParametersWithRandom params = new ParametersWithRandom(new KeyParameter(key));
paddedBufferedBlockCipher.init(true, params);
byte[] cipherText = new byte[paddedBufferedBlockCipher.getOutputSize(plainData.length)];
int val = paddedBufferedBlockCipher.processBytes(plainData, 0, plainData.length, cipherText, 0);
try {
paddedBufferedBlockCipher.doFinal(cipherText, val);
} catch (DataLengthException e) {
throw new AESEncryptionFailedException("AES Encryption failed due to data length mismatch");
} catch (IllegalStateException e) {
throw new AESEncryptionFailedException("AES Encryption failed");
} catch (InvalidCipherTextException e) {
throw new AESEncryptionFailedException("AES Encryption failed due to invalid cipher text");
}
return cipherText;
}
public byte[] decrypt(byte[] cipherText, byte[] key) throws AESDecryptionFailedException {
PaddedBufferedBlockCipher paddedBufferedBlockCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
ParametersWithRandom params = new ParametersWithRandom(new KeyParameter(key));
paddedBufferedBlockCipher.init(false, params);
byte[] plainText = new byte[paddedBufferedBlockCipher.getOutputSize(cipherText.length)];
int val = paddedBufferedBlockCipher.processBytes(cipherText, 0, cipherText.length, plainText, 0);
try {
int len = paddedBufferedBlockCipher.doFinal(plainText, val);
byte[] decryptedData = new byte[val + len];
System.arraycopy(plainText, 0, decryptedData, 0, len + val);
return decryptedData;
} catch (DataLengthException e) {
throw new AESDecryptionFailedException("AES Decryption failed due to data length mismatch");
} catch (IllegalStateException e) {
throw new AESDecryptionFailedException("AES Decryption failed");
} catch (InvalidCipherTextException e) {
throw new AESDecryptionFailedException("AES Decryption failed due to invalid cipher text");
}
}
}
Is there an easy way to simply encrypt and decrypt text using chacha.

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