encrypt file c# and decryptFile in java

pingus team

New member
Joined
Sep 4, 2019
Messages
4
Programming Experience
Beginner
I hawv code for encrypt and decrypt file. Original code its in c# (prevedicsharp) code work normal. I’m transfer code to java (prevedijava) and work normal too. I have problem if I want want encrypt file c# and decrypt File in java or vice versa ( from java to c#)
what mising in original code (c#)?
 

Attachments

  • prevodcsharp.txt
    3.4 KB · Views: 10
  • prevodjava.txt
    2.6 KB · Views: 6
What problem are you encountering?
 
What problem are you encountering?
if I encrypt file c# and decryptFile in java I cant open file. File. I get similar message as if I want to open encrypt file. But this problem its only if want want encrypt file c# and decrypt File in java or vice versa ( from java to c#)
 
Look at the generated keys with a debugger. I suspect that the key generated by C# is different from the key generated by Java, and vice versa.

Why are you even using derived key bytes? Why not just use the password directly?
 
I noticed that in the C# code you are getting the UTF-8 version of the password to ensure that you have just 8-bit values to build the derived key bytes, while in the Java version you simply use toCharArray(). My reading of the PBEKeySpec documentation is that it could still use 16-bit characters for the key.
Different PBE mechanisms may consume different bits of each password character. For example, the PBE mechanism defined in PKCS #5 looks at only the low order 8 bits of each character, whereas PKCS #12 looks at all 16 bits of each character.

Anyway, in the future, it will be better to post your code a text in code tags rather than attaching files. You want to make it easier for people to help you, not harder by making them have to download the files. Not everyone will be reading these posts on a laptop. For people just reading on a phone, you basically are putting the off from readily being able to scan the code.
 
I have code for encoryption and decryption file in java. Im this code translate in C# I have problem with line
output = csDecrypt.TransformFinalBlock(inputBuffer, 0, read);
Special with word TransformFinalBlock
How I can Fix error?

original java code:
package qrcodeworx;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

/**
 *
 * @author igor
 */
public class zaizvoz {
    String besedilo,  beseda2,  beseda3, spomin, kljuc2, kljuc3;
    String geslo, geslo1, geslo2, znak, password, ime, niz;
    String konec, ime2, test = null;
    int pak,  a,  b, c, dol,  dolg, dolg2, d, e;
    // zašifriraj datoteko
    public void skrij(String[] args) throws Exception {
        niz ="C:\\Users\\igor\\Documents\\NetBeansProjects\\preprosti\\jaslice.jpg";
 this.besedilo = this.niz;
 password = "igor";
 ime ="kresnik";
        byte[] output;
        int bytesRead;
        this.niz = this.besedilo;
        this.konec = this.niz.substring(this.niz.lastIndexOf(46) + 1);
        System.out.printf("'%s'%n", this.konec);
        this.ime2 = this.niz;
        String[] z = this.ime2.split("\\.");
        if (z[1].equals(this.konec)) {
            z[1] = ".temp";
            this.test = z[0] + z[1];
        }
        FileInputStream inFile = new FileInputStream(this.besedilo);
        FileOutputStream outFile = new FileOutputStream(this.test);
        String password = this.geslo1;
        String ime = this.geslo2;
        this.geslo = password + ime;
        Base64.Encoder encoder = Base64.getEncoder();
        String str = encoder.encodeToString(this.geslo.getBytes());
        this.geslo = str + str;
        String iv = this.geslo = str.substring(this.d, 16);
        byte[] ivBytes = iv.getBytes();
        IvParameterSpec ivspec = new IvParameterSpec(ivBytes);
        byte[] salt = ime.getBytes();
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
        SecretKey secretKey = factory.generateSecret(keySpec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(1, (Key)secret, new IvParameterSpec(ivBytes));
        AlgorithmParameters params = cipher.getParameters();
        byte[] input = new byte[this.dol];
        while ((bytesRead = inFile.read(input)) != -1) {
            output = cipher.update(input, 0, bytesRead);
            if (output == null) continue;
            outFile.write(output);
        }
        output = cipher.doFinal();
        if (output != null) {
            outFile.write(output);
        }
        inFile.close();
        outFile.flush();
        outFile.close();
        File file2 = new File(this.besedilo);
        boolean delete = file2.delete();
       // this.cop();
    }
// odšifriraj datoteko
//
    
     public void odkrij(String[] args) throws Exception {
        byte[] output;
        int read;
   // spremeni končnici
        this.niz = this.besedilo;
        this.konec = this.niz.substring(this.niz.lastIndexOf(46) + 1);
        System.out.printf("'%s'%n", this.konec);
        this.ime2 = this.niz;
        String[] z = this.ime2.split("\\.");
        if (z[1].equals(this.konec)) {
            z[1] = ".temp";
            this.test = z[0] + z[1];
        }
        // konec spremeni končnico
        String password = this.geslo1;
        String ime = this.geslo2;
        byte[] salt = ime.getBytes();
        this.geslo = password + ime;
        Base64.Encoder encoder = Base64.getEncoder();
        String str = encoder.encodeToString(this.geslo.getBytes());
        this.geslo = str + str;
        String iv = this.geslo = str.substring(this.d, 16);
        byte[] ivBytes = iv.getBytes();
        IvParameterSpec ivspec = new IvParameterSpec(ivBytes);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
        SecretKey tmp = factory.generateSecret(keySpec);
        SecretKeySpec secret = new SecretKeySpec(tmp.getEncoded(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(2, (Key)secret, new IvParameterSpec(ivBytes));
        FileInputStream fis = new FileInputStream(this.niz);
        FileOutputStream fos = new FileOutputStream(this.test);
        byte[] in = new byte[this.dol];
        
        while ((read = fis.read(in)) != -1) {
            output = cipher.update(in, 0, read);
            if (output == null) continue;
            fos.write(output);
        }
        output = cipher.doFinal();
        if (output != null) {
            fos.write(output);
        }
        fis.close();
        fos.flush();
        fos.close();
        File file2 = new File(this.besedilo);
        boolean delete = file2.delete();
 //       this.cop();
    }
    
     // dotazki
    public void povej() {
        String password = this.geslo1;
        String ime = this.geslo2;
        this.a = password.length();
        this.b = ime.length();
        this.geslo = password + ime;
        Base64.Encoder encoder = Base64.getEncoder();
        String str = encoder.encodeToString(this.geslo.getBytes());
        this.geslo = str + str;
        this.dolg = str.length();
        this.dolg2 = this.a + this.b + 16;
        if (this.dolg2 < this.dolg) {
            this.d = this.a + this.b;
            this.e = this.d + 16;
        }
        if (this.a < this.b) {
            this.pak = 256;
            this.dol = 100 + this.a;
            this.b = 8;
        }
        if (this.a > this.b) {
            this.pak = 256;
            this.dol = 100 + this.a + this.b;
        }
        if (this.a == this.b) {
            this.pak = 256;
            this.dol = 100 + this.b;
        }
    }

}

C# code:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        Program program = new Program();
        program.skrij(args);
        program.odkrij(args);
    }

    string niz, besedilo, password, ime, konec, ime2, test, geslo1, geslo2, geslo;
    int d, dol, a, b, dolg, dolg2, e, pak;

    public void skrij(string[] args)
    {
        niz = besedilo;
        besedilo = niz;
        password = "igor";
        ime = "kresnik";
        byte[] output;
        int bytesRead;

        niz = besedilo;
        konec = niz.Substring(niz.LastIndexOf('.') + 1);
        Console.WriteLine("'{0}'", konec);

        ime2 = niz;
        string[] z = ime2.Split('.');
        if (z[1] == konec)
        {
            z[1] = ".temp";
            test = z[0] + z[1];
        }

        using (FileStream inFile = new FileStream(besedilo, FileMode.Open))
        using (FileStream outFile = new FileStream(test, FileMode.Create))
        {
            password = geslo1;
            ime = geslo2;
            geslo = password + ime;
            byte[] passwordBytes = Encoding.UTF8.GetBytes(geslo);
            using (Rfc2898DeriveBytes derivedBytes = new Rfc2898DeriveBytes(passwordBytes, salt, iterations))
            {
                byte[] keyBytes = derivedBytes.GetBytes(keySize / 8);
                byte[] ivBytes = derivedBytes.GetBytes(16);

                using (Aes aesAlg = Aes.Create())
                {
                    aesAlg.KeySize = keySize;
                    aesAlg.Key = keyBytes;
                    aesAlg.IV = ivBytes;

                    using (CryptoStream csEncrypt = new CryptoStream(outFile, aesAlg.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        byte[] inputBuffer = new byte[dol];
                        while ((bytesRead = inFile.Read(inputBuffer, 0, inputBuffer.Length)) > 0)
                        {
// the bottom line reports error cs1061
                            output = csEncrypt.TransformFinalBlock(inputBuffer, 0, bytesRead);
                            outFile.Write(output, 0, output.Length);
                        }
                    }
                }
            }
        }

        File.Delete(besedilo);
    }

    public void odkrij(string[] args)
    {
        byte[] output;
        int read;

        niz = besedilo;
        konec = niz.Substring(niz.LastIndexOf('.') + 1);
        Console.WriteLine("'{0}'", konec);

        ime2 = niz;
        string[] z = ime2.Split('.');
        if (z[1] == konec)
        {
            z[1] = ".temp";
            test = z[0] + z[1];
        }

        string password = geslo1;
        string ime = geslo2;
        byte[] salt = Encoding.UTF8.GetBytes(ime);
        geslo = password + ime;

        using (FileStream fis = new FileStream(niz, FileMode.Open))
        using (FileStream fos = new FileStream(test, FileMode.Create))
        {
            password = geslo1;
            ime = geslo2;
            geslo = password + ime;
            byte[] passwordBytes = Encoding.UTF8.GetBytes(geslo);

            using (Rfc2898DeriveBytes derivedBytes = new Rfc2898DeriveBytes(passwordBytes, salt, iterations))
            {
                byte[] keyBytes = derivedBytes.GetBytes(keySize / 8);
                byte[] ivBytes = derivedBytes.GetBytes(16);

                using (Aes aesAlg = Aes.Create())
                {
                    aesAlg.KeySize = keySize;
                    aesAlg.Key = keyBytes;
                    aesAlg.IV = ivBytes;

                    using (CryptoStream csDecrypt = new CryptoStream(fos, aesAlg.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        byte[] inputBuffer = new byte[dol];
                        while ((read = fis.Read(inputBuffer, 0, inputBuffer.Length)) > 0)
                        {
// the bottom line reports error cs1061
                            output = csDecrypt.TransformFinalBlock(inputBuffer, 0, read);
                            fos.Write(output, 0, output.Length);
                        }
                    }
                }
            }
        }

        File.Delete(niz);
    }

    byte[] salt = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
    int iterations = 65536;
    int keySize = 256;
}
 
What is the error message? What have you tried to resolve the issue?
 
Also this code you wrote doesn't make sense:
C#:
while ((read = fis.Read(inputBuffer, 0, inputBuffer.Length)) > 0)
{
    // the bottom line reports error cs1061
    output = csDecrypt.TransformFinalBlock(inputBuffer, 0, read);
    fos.Write(output, 0, output.Length);
}

If you are looping, then how could the current block that you are writing out be the final block?

Anyway, you can see here what are the supported methods of a CryptoStream:
 

Latest posts

Back
Top Bottom