error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT - java

I'm getting the following error when i tried to decrypt a list of ogg files but when i try to decrypt only one it works this is my code.
for (IpstoriResponse ipstori: descargas) {
Executors.newSingleThreadExecutor().execute(() -> {
ipstori.setAudioHistory(getOfflineFile(ipstori.getAudioPath(), ipstori.getAudioCle(), ipstori.getAudioIv(), requireContext(), ipstori.getAudioCle()));
prepareList.add(...);
});
}
}
private String getOfflineFile(String input, String key, String iv, Context context, String name){
String result = null;
try {
File initialFile = new File(input);
InputStream inputStream = new FileInputStream(initialFile);
File outputDir = context.getCacheDir(); // context being the Activity pointer
File outputFile = File.createTempFile(name, ".ogg", outputDir);
FileOutputStream fos = new FileOutputStream(outputFile);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKey secretKey = makeKey(key);
IvParameterSpec ivParameterSpec = makeIv(iv);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
byte[] buffer = new byte[8192];
int nread;
while ((nread = cipherInputStream.read(buffer)) > 0) {
fos.write(buffer, 0, nread);
}
fos.flush();
fos.close();
cipherInputStream.close();
result = outputFile.getPath();
tempFiles.add(result);
} catch (Exception ex) {
...
}
return result;
}
that's really weird cause when you try to decrypt only one element of the list the code works fine

Related

Java encryption won't decrypt on Android

Okay, so when I encrypt anything, lets say in this case a file, with my computer. It works fine encrypting and decrypting said file. However if encrypt the file with my computer then send it too my android and run the same decryption code I wrote it wont decrypt the file properly. It doesn't show any errors, however the file is clearly not decrypted properly.
So I've learned that Bouncy Castle is quite different than JVM/JDK standard encryption library, so I'm not 100% sure if that's the problem. However it would make sense. The issue is that if it is I don't know how to use the JVM/JDK library for encryption on my android. I don't want too use the Bouncy Castle library on my computer.
public static void encrypt(File source, File dest, String password){
try{
FileInputStream inFile = new FileInputStream(source.getPath());
FileOutputStream outFile = new FileOutputStream(dest.getPath());
byte[] salt = new byte[8], iv = new byte[16];
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
SecretKey secretKey = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(iv));
byte[] input = new byte[64];
int bytesRead;
while((bytesRead = inFile.read(input)) != -1){
byte[] output = cipher.update(input, 0, bytesRead);
if(output != null){
outFile.write(output);
}
}
byte[] output = cipher.doFinal();
if(output != null){
outFile.write(output);
}
inFile.close();
outFile.flush();
outFile.close();
}catch(Exception e){
e.printStackTrace();
}
}
public static void decrypt(File source, File dest, String password){
try{
byte[] salt = new byte[8], iv = new byte[16];
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
SecretKey tmp = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
FileInputStream fis = new FileInputStream(source.getPath());
FileOutputStream fos = new FileOutputStream(dest.getPath());
byte[] in = new byte[64];
int read;
while((read = fis.read(in)) != -1){
byte[] output = cipher.update(in, 0, read);
if(output != null){
fos.write(output);
}
}
byte[] output = cipher.doFinal();
if(output != null){
fos.write(output);
}
fis.close();
fos.flush();
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}
The outcome would be too be able too encrypt any file with my computer using the standard JVM/JDK encryption library and being able too decrypt the same file with my android.
However if there is a different library other than Bouncy Castle that would work with android I'm open for ideas.
I've faced similar issue. First check if your encryption and decryption is setup properly.
If those are okay, then you should convert the encrypted text to Base64 or similar encoding.
Then decode the Base64 encoding first on the mobile and then decrypt the file.
The issue occurs because, some characters are not suitable for saving or transfering between mediums. They also gets affected by the underlying OS. Even if a bit is changed, your whole decrypted text will be changed, that might be the case here
ANDROID CODE
public static void decrypt(File source, File dest, String password){
try{
Base64InputStream fis = new Base64InputStream(new DataInputStream(new FileInputStream(source.getPath())), Base64.DEFAULT);
FileOutputStream fos = new FileOutputStream(dest.getPath());
byte[] salt = new byte[8], iv = new byte[16];
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
SecretKey tmp = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
byte[] in = new byte[64];
int read;
while((read = fis.read(in)) != -1){
byte[] output = cipher.update(in, 0, read);
if(output != null){
fos.write(output);
}
}
byte[] output = cipher.doFinal();
if(output != null){
fos.write(output);
}
fis.close();
fos.flush();
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}
Regular JVM
public static void encrypt(File source, File dest, String password){
try{
FileInputStream inFile = new FileInputStream(source.getPath());
OutputStream outFile = Base64.getEncoder().wrap(new FileOutputStream(dest.getPath()));
byte[] salt = new byte[8], iv = new byte[16];
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
SecretKey secretKey = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(iv));
byte[] input = new byte[64];
int bytesRead;
while((bytesRead = inFile.read(input)) != -1){
byte[] output = cipher.update(input, 0, bytesRead);
if(output != null){
outFile.write(output);
}
}
byte[] output = cipher.doFinal();
if(output != null){
outFile.write(output);
}
inFile.close();
outFile.flush();
outFile.close();
}catch(Exception e){
e.printStackTrace();
}
}
public static void decrypt(File source, File dest, String password){
try{
InputStream fis = Base64.getDecoder().wrap(new FileInputStream(source.getPath()));
//FileInputStream fis = new FileInputStream(source.getPath());
FileOutputStream fos = new FileOutputStream(dest.getPath());
byte[] salt = new byte[8], iv = new byte[16];
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
SecretKey tmp = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
byte[] in = new byte[64];
int read;
while((read = fis.read(in)) != -1){
byte[] output = cipher.update(in, 0, read);
if(output != null){
fos.write(output);
}
}
byte[] output = cipher.doFinal();
if(output != null){
fos.write(output);
}
fis.close();
fos.flush();
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}

Java - BouncyCastle - 3DES encryption and decryption of files: Files are corrupted after round trip

I am trying to encrypt and decrypt files with BouncyCastle 3DES. But the files are corrupted after encrypting and decrypting. For example a simple text-file or a jpg-image-file. This is my Code:
ZipUnzipBouncyCastle()
{
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
}
public void encrypt3DES(String password, String file)
throws IOException, DataLengthException, IllegalStateException,
InvalidCipherTextException, NoSuchAlgorithmException
{
byte[] data = Files.readAllBytes(new File(file).toPath());
SecureRandom random = new SecureRandom(data);
KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
keyGenerator.init(168, random);
SecretKey secreteKey = keyGenerator.generateKey();
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
new CBCBlockCipher(new DESedeEngine()));
cipher.init(true, new KeyParameter(secreteKey.getEncoded()));
byte[] result = new byte[cipher.getOutputSize(data.length)];
int tam = cipher.processBytes(data, 0, data.length, result, 0);
cipher.doFinal(result, tam);
byte[] encodedData = Base64.getEncoder().encode(result);
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(encodedData);
fileOutputStream.flush();
fileOutputStream.close();
}
public void decrypt3DES(String password, String file)
throws NoSuchAlgorithmException, DataLengthException,
IllegalStateException, InvalidCipherTextException, IOException
{
byte[] data = Files.readAllBytes(new File(file).toPath());
byte[] decodedData = Base64.getDecoder().decode(data);
SecureRandom random = new SecureRandom(decodedData);
KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
keyGenerator.init(168, random);
SecretKey secreteKey = keyGenerator.generateKey();
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
new CBCBlockCipher(new DESedeEngine()));
cipher.init(true, new KeyParameter(secreteKey.getEncoded()));
byte[] result = new byte[cipher.getOutputSize(decodedData.length)];
int tam = cipher.processBytes(decodedData, 0, decodedData.length, result, 0);
cipher.doFinal(result, tam);
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(result);
fileOutputStream.flush();
fileOutputStream.close();
}
I looked all over the Internet but could not find any explanation. What am I doing wrong?

Decrypt Video File and save to internal storage

I have an encrypted video with the key and I want to decrypt that video file with Key but I am not able to decrypt the video file. I try 2 3 methods but Non of these works for me.
Crypto.Class
public class Crypto {
static void fileProcessor(int cipherMode,String key,File inputFile,File outputFile){
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = new SecureRandom();
secureRandom.setSeed(key.getBytes("UTF-8"));
keyGenerator.init(128, secureRandom);
SecretKey secretKey = keyGenerator.generateKey();
// Key secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(cipherMode, secretKey);
FileInputStream inputStream = null;
byte[] inputBytes = new byte[0];
try {
inputStream = new FileInputStream(inputFile);
inputBytes = new byte[(int) inputFile.length()];
inputStream.read(inputBytes);
} catch (IOException e) {
e.printStackTrace();
}
byte[] outputBytes = cipher.doFinal(inputBytes);
FileOutputStream outputStream = new FileOutputStream(outputFile);
outputStream.write(outputBytes);
inputStream.close();
outputStream.close();
} catch (NoSuchPaddingException | NoSuchAlgorithmException
| InvalidKeyException | BadPaddingException
| IllegalBlockSizeException | IOException e) {
e.printStackTrace();
}
}
public static String Decrypt(String filePath) {
String key = "my_encrypted_key";
// File inputFile = new File("text.txt");
File encryptedFile = new File(filePath);
String decryptedFilePath="";
//check special guid folder if not exist create
//get the selected video file path with settings path if exist decrypt if not exist show message
File decryptedFile = new File(decryptedFilePath);
try {
//Crypto.fileProcessor(Cipher.ENCRYPT_MODE,key,inputFile,encryptedFile);
Crypto.fileProcessor(Cipher.DECRYPT_MODE,key,encryptedFile,decryptedFile);
Log.d("success", "Decrypt: success");
return decryptedFile.getAbsolutePath();
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
return "";
}
}
But this does not work for me and I try another one.
public static void TEST2(String orgFile) {
try {
String password = "estudies741852963#123";
File outFile_dec = new File(Environment.getExternalStorageDirectory()+"/testVideo/abc.mp4");
if(!outFile_dec.isDirectory()) {
outFile_dec.mkdir();
}
if(!outFile_dec.exists()){
outFile_dec.createNewFile();
}
// reading the salt
// user should have secure mechanism to transfer the
// salt, iv and password to the recipient
FileInputStream saltFis = new FileInputStream(orgFile);
byte[] salt = new byte[8];
saltFis.read(salt);
saltFis.close();
// reading the iv
FileInputStream ivFis = new FileInputStream(orgFile);
byte[] iv = new byte[16];
ivFis.read(iv);
ivFis.close();
SecretKeyFactory factory = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 1000,
256);
SecretKey tmp = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
// file decryption
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
InputStream fis = new FileInputStream(orgFile);
OutputStream fos = new FileOutputStream(outFile_dec);
// byte[] in = new byte[1024];
// int read;
// while ((read = fis.read(in)) != -1) {
// byte[] output = cipher.update(in, 0, read);
// if (output != null)
// fos.write(output);
// }
//
// byte[] output = cipher.doFinal();
// if (output != null)
// fos.write(output);
// fis.close();
// fos.flush();
// fos.close();
// System.out.println("File Decrypted.");
fos = new CipherOutputStream(fos, cipher);
int count = 0;
byte[] buffer = new byte[1024];
while ((count = fis.read(buffer)) >= 0) {
fos.write(buffer, 0, count);
}
fis.close();
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
In this method, its always shows on exception saying no such directory. And I try another method also But none of these works for me.
Tried this solution to decrypt my video
Java 256-bit AES Password-Based Encryption
How do i decrypt a file in Android with AES?

Encrypting and decrypting a file using CipherInputStream and CipherOutputStream

I've been trying to write an encrypted file in AES and decrypt it subsequently by using Cipher Streams provided in JCA. However, I'm having problems while reading the file, as the decryption is going haywire.
public class CipherStreams {
public static void main(String[] args) {
try {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Key k = keygen.generateKey();
Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
aes.init(Cipher.ENCRYPT_MODE, k);
FileOutputStream fs = new FileOutputStream("Encrypyed.txt");
CipherOutputStream out = new CipherOutputStream(fs, aes);
out.write("[Hello:Okay]\nOkay".getBytes());
out.close();
Cipher aes2 = Cipher.getInstance("AES/ECB/PKCS5Padding");
aes2.init(Cipher.DECRYPT_MODE, k);
FileInputStream fis = new FileInputStream("Encrypyed.txt");
CipherInputStream in = new CipherInputStream(fis,aes2);
byte[] b = new byte[8];
int i = in.read(b);
while(i!=-1) {
System.out.print((char)i);
i = in.read(b);
}
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IOException ex) {
Logger.getLogger(CipherStreams.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I'm receiving a single byte output as 5. Can anyone please help point out the problem?
You're not writing the bytes read, you're writing the number of bytes being read.
You're also assuming that the default platform encoding just transforms each character to a byte.
Just do the reverse of what you did when writing: read everything, and transform the read byte array to a String, then print that string:
public class CipherStreams {
public static void main(String[] args) {
try {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
Key k = keygen.generateKey();
Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
aes.init(Cipher.ENCRYPT_MODE, k);
String fileName = "Encrypted.txt";
FileOutputStream fs = new FileOutputStream(fileName);
CipherOutputStream out = new CipherOutputStream(fs, aes);
out.write("[Hello:Okay]\nOkay".getBytes());
out.flush();
out.close();
Cipher aes2 = Cipher.getInstance("AES/ECB/PKCS5Padding");
aes2.init(Cipher.DECRYPT_MODE, k);
FileInputStream fis = new FileInputStream(fileName);
CipherInputStream in = new CipherInputStream(fis, aes2);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int numberOfBytedRead;
while ((numberOfBytedRead = in.read(b)) >= 0) {
baos.write(b, 0, numberOfBytedRead);
}
System.out.println(new String(baos.toByteArray()));
}
catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IOException ex) {
ex.printStackTrace();
;
}
}
}

Android javax.io.IOException: last block incomplete in decryption

I am trying to make a encryption and decryption app but in decryption method I got javax.crypto.IllegalBlockSizeException: last block incomplete in decryption
byte[] key = ("Sh").getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKeySpec = new SecretKeySpec(key, "AES");
cipher = Cipher.getInstance("AES");
public void dec (String dir)
{
try{
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
String cleartextFile = dir;
FileInputStream fis = new FileInputStream(cleartextFile);
CipherInputStream cis = new CipherInputStream(fis, cipher);
FileOutputStream fos = new FileOutputStream(dir);
block = new byte[6];
while ((i = cis.read(block)) != -1) {
fos.write(block, 0, i);
}
fos.close();
}
catch(Exception ex)
{
Toast.makeText(MainActivity.this, "Chiper Error"+ex, Toast.LENGTH_LONG).show();
}
}

Categories

Resources