Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 14 of 14

Thread: initialization vector question

  1. #1
    Junior Member
    Join Date
    Dec 2017
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default initialization vector question

    I create program for Encryption and Decryption. I like know if its safe initialization vector make public?
    I Create IV with next coomand
    FileOutputStream ivOutFile = new FileOutputStream("iv.enc");
    byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
    ivOutFile.write(iv);
    ivOutFile.close();
    I get IV with text:
    ##áu;1cĚ…»„AT€

    now I like read file iv.enc. For this I use
    File file = new File("iv.enc"); 
      BufferedReader br = new BufferedReader(new FileReader(file)); 
      String st; 
      while ((st = br.readLine()) != null) 
        System.out.println(st); 
      String data = readFileAsString("iv.enc"); 
        System.out.println(data);
    but I get text:
    �u;1��AT�

    How I can read IV that I get oruginak text?

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: initialization vector question

    I'm not sure I understand what you are describing.
    Can you make a small, complete program that compiles, executes and shows the problem?

    Have you tried looking at the output in a hex format instead of as a String of characters?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Dec 2017
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: initialization vector question

    My all code its:
    this its funcion in java clas rezultati
    public void skrij(String[] args) throws Exception{
        	// file to be encrypted
    		FileInputStream inFile = new FileInputStream("plainfile.txt");
     
    		// encrypted file
    		FileOutputStream outFile = new FileOutputStream("encryptedfile.des");
            	// password to encrypt the file
    		String password = "januar";
                    String ime= "opica";
                    byte[] salt = ime.getBytes();
     
     
    		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);
    		AlgorithmParameters params = cipher.getParameters();
                    // create and save IV
                    FileOutputStream ivOutFile = new FileOutputStream("iv.enc");
    		byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
    		ivOutFile.write(iv);
    		ivOutFile.close();
    		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();
    		System.out.println("File Encrypted.");
     
     }

    and this code call objekt and write iv.enc

    public static void main(String[] args) throws Exception {
      rezultati objekt = new rezultati();
      objekt.skrij(args);
            String fileName = "iv.enc";
     
            try {
                byte[] buffer = new byte[1000];
                FileInputStream inputStream = 
                    new FileInputStream(fileName);
                int total = 0;
                int nRead = 0;
                while((nRead = inputStream.read(buffer)) != -1) {
                    System.out.println(new String(buffer));
                    total += nRead;
                }   
                inputStream.close();        
     
                System.out.println("Read " + total + " bytes");
            }
            catch(FileNotFoundException ex) {
                System.out.println(
                    "Unable to open file '" + 
                    fileName + "'");                
            }
            catch(IOException ex) {
                System.out.println(
                    "Error reading file '" 
                    + fileName + "'");                  
     
            }
        }

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: initialization vector question

    How do I compile and execute the code for testing? I do not see any class definitions or any import statements.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Dec 2017
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: initialization vector question

    this its all code:
    this its funcion in java clas rezultati
     
    package preprosti;
     
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.security.AlgorithmParameters;
    import java.security.spec.KeySpec;
    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 rezultati {
    public void skrij(String[] args) throws Exception{
        	// file to be encrypted
    		FileInputStream inFile = new FileInputStream("plainfile.txt");
     
    		// encrypted file
    		FileOutputStream outFile = new FileOutputStream("encryptedfile.des");
            	// password to encrypt the file
    		String password = "januar";
                    String ime= "opica";
                    byte[] salt = ime.getBytes();
     
     
    		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);
    		AlgorithmParameters params = cipher.getParameters();
                    // create and save IV
                    FileOutputStream ivOutFile = new FileOutputStream("iv.enc");
    		byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
    		ivOutFile.write(iv);
    		ivOutFile.close();
    		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();
    		System.out.println("File Encrypted.");
     
     }
    }

    and this code call objekt and write iv.enc

    public static void main(String[] args) throws Exception {
      rezultati objekt = new rezultati();
      objekt.skrij(args);
            String fileName = "iv.enc";
     
            try {
                byte[] buffer = new byte[1000];
                FileInputStream inputStream = 
                    new FileInputStream(fileName);
                int total = 0;
                int nRead = 0;
                while((nRead = inputStream.read(buffer)) != -1) {
                    System.out.println(new String(buffer));
                    total += nRead;
                }   
                inputStream.close();        
     
                System.out.println("Read " + total + " bytes");
            }
            catch(FileNotFoundException ex) {
                System.out.println(
                    "Unable to open file '" + 
                    fileName + "'");                
            }
            catch(IOException ex) {
                System.out.println(
                    "Error reading file '" 
                    + fileName + "'");                  
     
            }
        }

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: initialization vector question

    When I execute the program I get this output:
    File Encrypted.
    %A›Žóéu›ëGžžIç?
    What is supposed to print out?

    Where is the decryption code?
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Dec 2017
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: initialization vector question

    and how i can text from vi.enc "%A›Žóéu›ëGžžIç? " send to string ?
    decryption code work normall

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: initialization vector question

    Where is the decryption code? I don't see it in the posted code.

    Where did you get the encryption code? Was there more code there?
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Dec 2017
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: initialization vector question

    I get code from here. Im litle change him that I dont nead create separate iv.enc.
    https://javapapers.com/java/java-fil...ncryption-pbe/
    my change code for Encryption/Decryption its
    public void skrij(String[] args) throws Exception{  
            byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            IvParameterSpec ivspec = new IvParameterSpec(iv);
            FileInputStream inFile = new FileInputStream("plainfile.txt");
     
    		// encrypted file
    		FileOutputStream outFile = new FileOutputStream("encryptedfile.des");
            	// password to encrypt the file
    		String password = "januar";
                    String ime= "opica";
                    byte[] salt = ime.getBytes();
                    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);
    		AlgorithmParameters params = cipher.getParameters();
                    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();
    }

    im change code for Decrypted. Here I have new problem with Decrypted files

    public void odkrij(String[] args) throws Exception{  
                String password = "januar";
    		String ime= "opica";
                    byte[] salt = ime.getBytes();
            byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            IvParameterSpec ivspec = new IvParameterSpec(iv);
     
                    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");
     
    		// file decryption
    		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    		cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
    		FileInputStream fis = new FileInputStream("encryptedfile.des");
    		FileOutputStream fos = new FileOutputStream("plainfile_decrypted.txt");
    		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();
            }
    My original file
    This its test file with some text.This its original.
    Encrypted file
    ‹öpÝMĘ®Ń#Ŕży!#Ďd¬×r#„k0ź‰~çFm•€##ÝőLxRN#jŽ ą`÷äç˛4 9ƒł…Žă7űčť#a
    Decrypted file has error
    €WxEˆÉD˛TęĎű`Sq.le with some text.This its original.
    Why dont see originak text in Decrypted file?
    Last edited by Norm; January 15th, 2019 at 05:21 PM. Reason: Removed space from code tag

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: initialization vector question

    Please post complete code that can be compiled and executed for testing.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Dec 2017
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: initialization vector question

    my full change code for Encryption/Decryption its
    First create file named plainfile.txt with text: This its test file with some text.This its original.
    Main project. Here call function skrij and odkrijjava class zatest
    public static void main(String[] args) throws Exception {
        zatest objekt = new zatest();
        objekt.skrij(args);// Encrypted file
        objekt.odkrij(args);// Decrypted file
        }
    function for encrypted file in java class zatest
    public void skrij(String[] args) throws Exception{  
            byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            IvParameterSpec ivspec = new IvParameterSpec(iv);
            FileInputStream inFile = new FileInputStream("plainfile.txt");
     
    		// encrypted file
    		FileOutputStream outFile = new FileOutputStream("encryptedfile.des");
            	// password to encrypt the file
    		String password = "januar";
                    String ime= "opica";
                    byte[] salt = ime.getBytes();
                    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);
    		AlgorithmParameters params = cipher.getParameters();
                    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();
    }

    function for decryption file in java class zatest
    public void odkrij(String[] args) throws Exception{  
                String password = "januar";
    		String ime= "opica";
                    byte[] salt = ime.getBytes();
            byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            IvParameterSpec ivspec = new IvParameterSpec(iv);
     
                    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");
     
    		// file decryption
    		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    		cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
    		FileInputStream fis = new FileInputStream("encryptedfile.des");
    		FileOutputStream fos = new FileOutputStream("plainfile_decrypted.txt");
    		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();
            }

    file named plainfile.txt with original text:
    This its test file with some text.This its original.
    I get Encrypted file named encryptedfile.des with text:
    ‹öpÝMĘ®Ń#Ŕży!#Ďd¬×r#„k0ź‰~çFm•€##ÝőLxRN#jŽ ą`÷äç˛4 9ƒł…Žă7űčť#a
    my decrypted file named plainfile_decrypted.txt has text:
    €WxEˆÉD˛TęĎű`Sq.le with some text.This its original.
    Why dont see original text in Decrypted file?

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: initialization vector question

    my full change code
    The posted code is only methods.
    It is not complete. It is missing the import statements and the definition of a class.


    I see the variable: ivspec is defined in both methods but it is never used.

    The initialization of the cipher object is different in the two methods:
       cipher.init(Cipher.ENCRYPT_MODE, secret);
    ...
       cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
    The first one does not use the iv, the second one does.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Dec 2017
    Posts
    26
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: initialization vector question

    Import section in java class zatest
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.security.AlgorithmParameters;
    import java.security.spec.KeySpec;
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.PBEKeySpec;
    import javax.crypto.spec.SecretKeySpec;
    im find kode
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    in function skrij and code
       cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
    in function odkrij

    How I can use IV?
    How I fix error?

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: initialization vector question

    Change the cipher initialization so that both calls to init use the same iv parameters.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. recursion on initialization
    By homey in forum What's Wrong With My Code?
    Replies: 13
    Last Post: April 29th, 2014, 08:09 PM
  2. Initialization in class
    By bllnsr in forum Object Oriented Programming
    Replies: 3
    Last Post: November 12th, 2013, 01:32 PM
  3. Inner class initialization and declaration
    By longwu in forum Object Oriented Programming
    Replies: 2
    Last Post: August 31st, 2011, 07:44 AM
  4. Replies: 2
    Last Post: December 22nd, 2010, 09:21 AM
  5. Initialization of a class
    By Merik in forum What's Wrong With My Code?
    Replies: 1
    Last Post: October 28th, 2010, 07:18 PM