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 21 of 21

Thread: Problem Encrypting a secret key

  1. #1
    Junior Member
    Join Date
    Nov 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Problem Encrypting a secret key

    Hows it going, I have generated a secret key using AES encryption, which is working perfectly. Now I intend the to encrypt that key using an RSA public key that i have generated elsewhere. Ive tried switching from AES to RSA, adding padding and ive also tried importing bouncy castle, but im not sure im doing that right. None of these methods seem to be working as I usually end up with the error - javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes or this one java.security.InvalidKeyException: No installed provider supports this key: sun.security.rsa.RSAPublicKeyImpl. So im here to ask "Whats wrong with my code"
    import java.io.*;
    import java.security.*;
     
    import org.bouncycastle.*;
    import javax.crypto.*;
     
     
    public class ClientSecretKeyEncryption
    {
     
     protected static final String ALGORITHM = "RSA";   
      public static void main(String args[]) {
    //Security.addProvider(new BouncyCastleProvider());
     
       // Encrypts secret key using servers public key
     
       try {
     
     
          // File containing RSA Public key
          FileInputStream keyFIS = new FileInputStream("/Users/Client/RSAPublicKeyFile");
          ObjectInputStream keyOIS = new ObjectInputStream(keyFIS);
     
          // Create RSA cipher instance
          Cipher rsaCipher = Cipher.getInstance("AES");
     
     
          // Read in the AES key
          Key RsaPublicKeyFile = (PublicKey) keyOIS.readObject();
     
            // Initialize the cipher for encryption
          rsaCipher.init(Cipher.ENCRYPT_MODE, (Key) RsaPublicKeyFile);
     
          keyOIS.close();
          keyFIS.close();
         // rsaCipher.init(Cipher.ENCRYPT_MODE, (PublicKey) keyOIS.readObject());
     
     
          // File for writing out encrypted secret key to server
          FileOutputStream fos = new FileOutputStream("/Users/Server/ClientsEncryprtedSecretKey");
     
     
     
          //This brings in the secret key 
          File f = new File("/Users/Client/ClientsSecretKey");
          FileInputStream in = new FileInputStream(f);
          byte[]SecKey = new byte[(int)f.length()];
          in.read(SecKey);
     
          // Encrypt the Secret Key 
          byte[] EncSecKey = rsaCipher.doFinal(SecKey);
     
          // Write Secret Key to file
          fos.write(EncSecKey);
          fos.close();
     
     
     
      } catch (Exception e) {
         System.out.println(e);
        }
     
     }
    }

    Any help on this issue would be must appreciated, ive been googling the issue for the past 2 days now and have found no satisfactory answers. Cheers in advance


  2. #2
    Senior Member PhHein's Avatar
    Join Date
    Mar 2013
    Location
    Germany
    Posts
    609
    My Mood
    Sleepy
    Thanks
    10
    Thanked 93 Times in 86 Posts

    Default Re: Problem Encrypting a secret key

    You need to adjust your JCE policy files. Google for that.

  3. #3
    Junior Member
    Join Date
    Nov 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem Encrypting a secret key

    Quote Originally Posted by PhHein View Post
    You need to adjust your JCE policy files. Google for that.
    Well not sure what you meant by "adjust" so I assumed that I needed to get the latest. I downloaded this and put them into the right folder making sure to replace the old ones. Unfortunately this did not fix the problem as I still get this error-java.security.InvalidKeyException: No installed provider supports this key: sun.security.rsa.RSAPublicKeyImpl

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

    Default Re: Problem Encrypting a secret key

    Search for: "UnlimitedJCEPolicy"
    There are jar files in the JRE that need to be changed.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Nov 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem Encrypting a secret key

    Thats what I had done, I did it again just for peace of mind but it is the same result as before.

  6. #6
    Junior Member
    Join Date
    Nov 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem Encrypting a secret key

    any other suggestions?, head is wrecked with it at this stage, it seems so simple, yet it refuses to cooperate.

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,165
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem Encrypting a secret key

    Can you post the code to create the RSAPublicKeyFile file?
    And the ClientsSecretKey file?

    And any other data the program needs to execute.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Junior Member
    Join Date
    Nov 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem Encrypting a secret key

    import java.io.*;
    import java.security.*;
    import javax.crypto.*;
     
    public class ServerRSAKeyGen 
    {
        public static void main(String args[]) {
     
     
     
     
         try 
         {
     
          // File for writing private key
          FileOutputStream privateKeyFOS = new FileOutputStream("/Users/Server/RSAPrivateKeyFile");
          ObjectOutputStream privateKeyOOS = new ObjectOutputStream(privateKeyFOS);
          // File for writing public key
          FileOutputStream publicKeyFOS = new FileOutputStream("/Users/Server/RSAPublicKeyFile");
          ObjectOutputStream publicKeyOOS = new ObjectOutputStream(publicKeyFOS);
           // File for writing public key to Client
          FileOutputStream serverPublicKeyFOS = new FileOutputStream("/Users/Client/RSAPublicKeyFile");
          ObjectOutputStream serverPublicKeyOOS = new ObjectOutputStream(serverPublicKeyFOS);
     
     
     
           // Generate RSA key pair 
          KeyPair keyPairRSA = KeyPairGenerator.getInstance("RSA").generateKeyPair();
     
     
     
          // Write the keys to respective files
          privateKeyOOS.writeObject(keyPairRSA.getPrivate());
          publicKeyOOS.writeObject(keyPairRSA.getPublic());
          // Write the servers public key to client folder
          serverPublicKeyOOS.writeObject(keyPairRSA.getPublic());
     
          System.out.println("Private and Public keys have been generated using RSA  Encryption.");
          System.out.println("Both keys have been written to the Server folder.");
          System.out.println("The Public key has also been written to the Client folder.");
     
     
          privateKeyOOS.close();
          publicKeyOOS.close();
          privateKeyFOS.close();
          publicKeyFOS.close();
     
     
     
     
     
         }
         catch (Exception e) 
         {
          System.out.println(e);
         }
        }
    }
    [/QUOTE]
     
     
     
    [QUOTE]import java.io.*;
    import javax.crypto.*;
     
     
     
    public class ClientSecretSessionKeyGenerator {
     
      public static void main(String args[]) {
     
       // Client Generates Secert key and writes to file
     
        try {
          // File for writing output
          FileOutputStream keyFOS = new FileOutputStream("/Users/Client/ClientsSecretKey");
          ObjectOutputStream keyOOS = new ObjectOutputStream(keyFOS);
     
          // Generate random AES key
          KeyGenerator keygen = KeyGenerator.getInstance("AES");
          SecretKey SecKey = keygen.generateKey();
          keyOOS.writeObject(SecKey);
     
          System.out.println("Random Secret Key generated and written to file: ClientsSecretKey");
     
          keyOOS.close();
          keyFOS.close();
     
     
        } catch (Exception e) {
             System.out.println(e);
        }
      }
    }

    You will need to create a folder for both Client and Server for it to run, change the directory if needed.
    Last edited by Norm; November 18th, 2013 at 04:12 PM. Reason: changed quote to code tags

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,165
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem Encrypting a secret key

    That code has too many hard coded paths for easy testing. I don't want to set up lots of directories. For testing I want to be able to put all the files in one folder by easily changing the path to the files in one place. For example:
     public static String pathToPubKey = "RSAPublicKeyFile.key";
    Then that String variable would be used where ever the code needs that path.


    The catch() blocks need calls to printStackTrace() so the location of the error can be found.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Junior Member
    Join Date
    Nov 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem Encrypting a secret key

    yeah sorry about that, but the paths are essential to the project, its not a lot of directories, just 2- a folder called "Client" and a folder called "Server", if your using a mac you can add these easy enough to the right directory, if not ill fix it up for you like you said.

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,165
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem Encrypting a secret key

    Ok, fix this so it works. I started making changes before I found that there were a lot more files than just 2:
    /* http://www.javaprogrammingforums.com/whats-wrong-my-code/33933-problem-encrypting-secret-key.html#post130756
     
    NOTE:  Needs files to execute
    */
     
    import java.io.*;
    import java.security.*;
     
    //import org.bouncycastle.*;
    import javax.crypto.*;
     
     
    public class ClientSecretKeyEncryption
    {
     
     protected static final String ALGORITHM = "RSA";   
     
        // Put all files local to this dir
        static String pathToKey = "RSAPublicKeyFile.key";
        static String pathToClntSecKey = "ClientsSecretKey.key";
     
     
     
      public static void main(String args[]) {
     
       ClientSecretSessionKeyGenerator.main(args);      //<<<<<<<<<<
     
    //Security.addProvider(new BouncyCastleProvider());
     
       // Encrypts secret key using servers public key
     
       try {
     
     
          // File containing RSA Public key
          FileInputStream keyFIS = new FileInputStream(pathToKey);
          ObjectInputStream keyOIS = new ObjectInputStream(keyFIS);
     
          // Create RSA cipher instance
          Cipher rsaCipher = Cipher.getInstance("AES");
     
          // Read in the AES key
          Key RsaPublicKeyFile = (PublicKey) keyOIS.readObject();
     
            // Initialize the cipher for encryption
          rsaCipher.init(Cipher.ENCRYPT_MODE, (Key) RsaPublicKeyFile); //  redundant cast to Key
     
          keyOIS.close();
          keyFIS.close();
         // rsaCipher.init(Cipher.ENCRYPT_MODE, (PublicKey) keyOIS.readObject());
     
     
          // File for writing out encrypted secret key to server
          FileOutputStream fos = new FileOutputStream("/Users/Server/ClientsEncryprtedSecretKey");
     
     
     
          //This brings in the secret key 
          File f = new File(pathToClntSecKey);
          FileInputStream in = new FileInputStream(f);
          byte[]SecKey = new byte[(int)f.length()];
          in.read(SecKey);
     
          // Encrypt the Secret Key 
          byte[] EncSecKey = rsaCipher.doFinal(SecKey);
     
          // Write Secret Key to file
          fos.write(EncSecKey);
          fos.close();
     
     
     
      } catch (Exception e) {
         System.out.println(e);
        }
     
     }
     
     
     
     
    static class ClientSecretSessionKeyGenerator {
     
      public static void main(String args[]) {
     
       // Client Generates Secert key and writes to file
     
        try {
          // File for writing output
          FileOutputStream keyFOS = new FileOutputStream(pathToKey);
          ObjectOutputStream keyOOS = new ObjectOutputStream(keyFOS);
     
          // Generate random AES key
          KeyGenerator keygen = KeyGenerator.getInstance("AES");
          SecretKey SecKey = keygen.generateKey();
          keyOOS.writeObject(SecKey);
     
          System.out.println("Random Secret Key generated and written to file: ClientsSecretKey");
     
          keyOOS.close();
          keyFOS.close();
     
     
        } catch (Exception e) {
             System.out.println(e);
        }
      }
    }
     
    static class ServerRSAKeyGen 
    {
        public static void main(String args[]) {
     
     
     
     
         try 
         {
     
          // File for writing private key
          FileOutputStream privateKeyFOS = new FileOutputStream("RSAPrivateKeyFile");
          ObjectOutputStream privateKeyOOS = new ObjectOutputStream(privateKeyFOS);
          // File for writing public key
          FileOutputStream publicKeyFOS = new FileOutputStream("RSAPublicKeyFile");
          ObjectOutputStream publicKeyOOS = new ObjectOutputStream(publicKeyFOS);
           // File for writing public key to Client
          FileOutputStream serverPublicKeyFOS = new FileOutputStream("RSAPublicKeyFile");
          ObjectOutputStream serverPublicKeyOOS = new ObjectOutputStream(serverPublicKeyFOS);
     
     
     
           // Generate RSA key pair 
          KeyPair keyPairRSA = KeyPairGenerator.getInstance("RSA").generateKeyPair();
     
     
     
          // Write the keys to respective files
          privateKeyOOS.writeObject(keyPairRSA.getPrivate());
          publicKeyOOS.writeObject(keyPairRSA.getPublic());
          // Write the servers public key to client folder
          serverPublicKeyOOS.writeObject(keyPairRSA.getPublic());
     
          System.out.println("Private and Public keys have been generated using RSA  Encryption.");
          System.out.println("Both keys have been written to the Server folder.");
          System.out.println("The Public key has also been written to the Client folder.");
     
     
          privateKeyOOS.close();
          publicKeyOOS.close();
          privateKeyFOS.close();
          publicKeyFOS.close();
     
     
     
     
     
         }
         catch (Exception e) 
         {
          System.out.println(e);
         }
        }
    }
     
     
     
    static class ClientSecretSessionKeyGenerator2 {
     
      public static void main(String args[]) {
     
       // Client Generates Secert key and writes to file
     
        try {
          // File for writing output
          FileOutputStream keyFOS = new FileOutputStream(pathToClntSecKey);
          ObjectOutputStream keyOOS = new ObjectOutputStream(keyFOS);
     
          // Generate random AES key
          KeyGenerator keygen = KeyGenerator.getInstance("AES");
          SecretKey SecKey = keygen.generateKey();
          keyOOS.writeObject(SecKey);
     
          System.out.println("Random Secret Key generated and written to file: ClientsSecretKey");
     
          keyOOS.close();
          keyFOS.close();
     
     
        } catch (Exception e) {
             System.out.println(e);
        }
      }
    }
     
     
    }
    If you don't understand my answer, don't ignore it, ask a question.

  12. #12
    Junior Member
    Join Date
    Nov 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem Encrypting a secret key

    ok ill change them all to just one folder, this is the directory ill be using "C:/Client/" so u can add the client folder there.

    --- Update ---

     
    /* [url]http://www.javaprogrammingforums.com/whats-wrong-my-code/33933-problem-encrypting-secret-key.html#post130756[/url]
     
    NOTE:  Needs files to execute
    */
     
    import java.io.*;
    import java.security.*;
     
    //import org.bouncycastle.*;
    import javax.crypto.*;
     
     
    public class ClientSecretKeyEncryption
    {
     
     protected static final String ALGORITHM = "RSA";   
     
     public static String pathToKey = "RSAPublicKeyFile.key";
        static String pathToClntSecKey = "C:/Client/ClientsSecretKey";
     
     
     
      public static void main(String args[]) {
     
       ClientSecretSessionKeyGenerator.main(args);      //<<<<<<<<<<
     
    //Security.addProvider(new BouncyCastleProvider());
     
       // Encrypts secret key using servers public key
     
       try {
     
     
          // File containing RSA Public key
          FileInputStream keyFIS = new FileInputStream(pathToKey);
          ObjectInputStream keyOIS = new ObjectInputStream(keyFIS);
     
          // Create RSA cipher instance
          Cipher rsaCipher = Cipher.getInstance("AES");
     
          // Read in the AES key
          Key RsaPublicKeyFile = (PublicKey) keyOIS.readObject();
     
            // Initialize the cipher for encryption
          rsaCipher.init(Cipher.ENCRYPT_MODE, (Key) RsaPublicKeyFile); //  redundant cast to Key
     
          keyOIS.close();
          keyFIS.close();
         // rsaCipher.init(Cipher.ENCRYPT_MODE, (PublicKey) keyOIS.readObject());
     
     
          // File for writing out encrypted secret key to server
          FileOutputStream fos = new FileOutputStream("C:/Client/ClientsEncryprtedSecretKey");
     
     
     
          //This brings in the secret key 
          File f = new File(pathToClntSecKey);
          FileInputStream in = new FileInputStream(f);
          byte[]SecKey = new byte[(int)f.length()];
          in.read(SecKey);
     
          // Encrypt the Secret Key 
          byte[] EncSecKey = rsaCipher.doFinal(SecKey);
     
          // Write Secret Key to file
          fos.write(EncSecKey);
          fos.close();
     
     
     
      } catch (Exception e) {
         System.out.println(e);
        }
     
     }
     
     
     
     
    static class ClientSecretSessionKeyGenerator {
     
      public static void main(String args[]) {
     
       // Client Generates Secert key and writes to file
     
        try {
          // File for writing output
          FileOutputStream keyFOS = new FileOutputStream("C:/Client/ClientsSecretKey");
          ObjectOutputStream keyOOS = new ObjectOutputStream(keyFOS);
     
          // Generate random AES key
          KeyGenerator keygen = KeyGenerator.getInstance("AES");
          SecretKey SecKey = keygen.generateKey();
          keyOOS.writeObject(SecKey);
     
          System.out.println("Random Secret Key generated and written to file: ClientsSecretKey");
     
          keyOOS.close();
          keyFOS.close();
     
     
        } catch (Exception e) {
             System.out.println(e);
        }
      }
    }
     
    static class ServerRSAKeyGen 
    {
        public static void main(String args[]) {
     
     
     
     
         try 
         {
     
          // File for writing private key
          FileOutputStream privateKeyFOS = new FileOutputStream("C:/Client/RSAPrivateKeyFile");
          ObjectOutputStream privateKeyOOS = new ObjectOutputStream(privateKeyFOS);
          // File for writing public key
          FileOutputStream publicKeyFOS = new FileOutputStream("C:/Client/RSAPublicKeyFile");
          ObjectOutputStream publicKeyOOS = new ObjectOutputStream(publicKeyFOS);
           // File for writing public key to Client
          FileOutputStream serverPublicKeyFOS = new FileOutputStream("C:/Client/RSAPublicKeyFile");
          ObjectOutputStream serverPublicKeyOOS = new ObjectOutputStream(serverPublicKeyFOS);
     
     
     
           // Generate RSA key pair 
          KeyPair keyPairRSA = KeyPairGenerator.getInstance("RSA").generateKeyPair();
     
     
     
          // Write the keys to respective files
          privateKeyOOS.writeObject(keyPairRSA.getPrivate());
          publicKeyOOS.writeObject(keyPairRSA.getPublic());
          // Write the servers public key to client folder
          serverPublicKeyOOS.writeObject(keyPairRSA.getPublic());
     
          System.out.println("Private and Public keys have been generated using RSA  Encryption.");
          System.out.println("Both keys have been written to the Server folder.");
          System.out.println("The Public key has also been written to the Client folder.");
     
     
          privateKeyOOS.close();
          publicKeyOOS.close();
          privateKeyFOS.close();
          publicKeyFOS.close();
     
     
     
     
     
         }
         catch (Exception e) 
         {
          System.out.println(e);
         }
        }
    }
     
     
     
    static class ClientSecretSessionKeyGenerator2 {
     
      public static void main(String args[]) {
     
       // Client Generates Secert key and writes to file
     
        try {
          // File for writing output
          FileOutputStream keyFOS = new FileOutputStream(C:/Client/ClientsSecretKey);
          ObjectOutputStream keyOOS = new ObjectOutputStream(keyFOS);
     
          // Generate random AES key
          KeyGenerator keygen = KeyGenerator.getInstance("AES");
          SecretKey SecKey = keygen.generateKey();
          keyOOS.writeObject(SecKey);
     
          System.out.println("Random Secret Key generated and written to file: ClientsSecretKey");
     
          keyOOS.close();
          keyFOS.close();
     
     
        } catch (Exception e) {
             System.out.println(e);
        }
      }
    }
     
     
    }
    I think thats it, may have made a mistake, not sure.

  13. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,165
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem Encrypting a secret key

    That code still has hardcoded file paths.
    FileOutputStream keyFOS = new FileOutputStream(C:/Client/ClientsSecretKey);

    Can you define the path's each in a String like I did and then use those Strings in the code so that ONE change will change the path for all the places it is used?
    FileOutputStream keyFOS = new FileOutputStream(pathToClientsSecretKey);
    If you don't understand my answer, don't ignore it, ask a question.

  14. #14
    Junior Member
    Join Date
    Nov 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem Encrypting a secret key

    cheers for the help dude, but time is ticking on here, im gonna conclude for the night and pick it up in the morning.

  15. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,165
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem Encrypting a secret key

    see you tomorrow
    If you don't understand my answer, don't ignore it, ask a question.

  16. #16
    Junior Member
    Join Date
    Nov 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem Encrypting a secret key

    Gonna have to confess here, I dont really know how to setup that path idea you had, the hardcoding is all I need to do for the project.

  17. #17
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,165
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem Encrypting a secret key

    Here are two of the path Strings:
        static String pathToKey = "RSAPublicKeyFile.key";
        static String pathToClntSecKey = "C:/Client/ClientsSecretKey";
    Then those Strings are used where ever that file is accessed. For example:
      FileInputStream keyFIS = new FileInputStream(pathToKey);
    //  and
      FileOutputStream keyFOS = new FileOutputStream(pathToKey);
    All the hardcoded paths should be replaced with variables like the above.

    That makes it easy to change any and all of the paths because they are all coded in one place. It also has the benefit that you can not hardcode two paths that you want to be the same but are different because of a spelling error.
    If you don't understand my answer, don't ignore it, ask a question.

  18. #18
    Junior Member
    Join Date
    Nov 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem Encrypting a secret key

     
     
    import java.io.*;
    import java.security.*;
     
     
    import javax.crypto.*;
     
     
    public class ClientSecretKeyEncryption
    {
        protected static final String ALGORITHM = "RSA";   
     
        // Put all files local to this dir
        static String pathToKey = "RSAPublicKeyFile";
        static String pathToClntSecKey = "ClientsSecretKey";
     
      public static void main(String args[]) {
    //ClientSecretKeyEncryption.main(args);    
     
       try {
     
     
          // File containing RSA Public key
          FileInputStream keyFIS = new FileInputStream(pathToKey);
          ObjectInputStream keyOIS = new ObjectInputStream(keyFIS);
     
          // Create RSA cipher instance
          Cipher rsaCipher = Cipher.getInstance("AES");
     
          // Read in the AES key
          Key RsaPublicKeyFile = (PublicKey) keyOIS.readObject();
     
            // Initialize the cipher for encryption
          rsaCipher.init(Cipher.ENCRYPT_MODE, (Key) RsaPublicKeyFile); //  redundant cast to Key
     
          keyOIS.close();
          keyFIS.close();
         // rsaCipher.init(Cipher.ENCRYPT_MODE, (PublicKey) keyOIS.readObject());
     
     
          // File for writing out encrypted secret key to server
          FileOutputStream fos = new FileOutputStream("pathToKey");
     
     
     
          //This brings in the secret key 
          File f = new File(pathToClntSecKey);
          FileInputStream in = new FileInputStream(f);
          byte[]SecKey = new byte[(int)f.length()];
          in.read(SecKey);
     
          // Encrypt the Secret Key 
          byte[] EncSecKey = rsaCipher.doFinal(SecKey);
     
          // Write Secret Key to file
          fos.write(EncSecKey);
          fos.close();
     
     
     
      } catch (Exception e) {
         System.out.println(e);
        }
     
     }
    }[/QUOTE]
     
    [QUOTE]
     
    import java.io.*;
    import java.security.*;
    import javax.crypto.*;
     
    public class ServerRSAandAesKeyGen {
    static String pathToRSAPrivateKeyFile = "RSAPrivateKeyFile";
    static String pathToRSAPublicKeyFile = "RSAPublicKeyFile";
     
        public static void main(String args[]) {
     
     
     
     
         try 
         {
     
          // File for writing private key
          FileOutputStream privateKeyFOS = new FileOutputStream("pathToRSAPrivateKeyFile");
          ObjectOutputStream privateKeyOOS = new ObjectOutputStream(privateKeyFOS);
          // File for writing public key
          FileOutputStream publicKeyFOS = new FileOutputStream("pathToRSAPublicKeyFile");
          ObjectOutputStream publicKeyOOS = new ObjectOutputStream(publicKeyFOS);
           // File for writing public key to Client
          FileOutputStream serverPublicKeyFOS = new FileOutputStream("pathToRSAPublicKeyFile");
          ObjectOutputStream serverPublicKeyOOS = new ObjectOutputStream(serverPublicKeyFOS);
     
     
     
           // Generate RSA key pair 
          KeyPair keyPairRSA = KeyPairGenerator.getInstance("RSA").generateKeyPair();
     
     
     
          // Write the keys to respective files
          privateKeyOOS.writeObject(keyPairRSA.getPrivate());
          publicKeyOOS.writeObject(keyPairRSA.getPublic());
          // Write the servers public key to client folder
          serverPublicKeyOOS.writeObject(keyPairRSA.getPublic());
     
          System.out.println("Private and Public keys have been generated using RSA  Encryption.");
          System.out.println("Both keys have been written to the Server folder.");
          System.out.println("The Public key has also been written to the Client folder.");
     
     
          privateKeyOOS.close();
          publicKeyOOS.close();
          privateKeyFOS.close();
          publicKeyFOS.close();
     
     
     
     
     
         }
         catch (Exception e) 
         {
          System.out.println(e);
         }
        }
    }[/QUOTE]
     
    [QUOTE]
     */
    import java.io.*;
    import javax.crypto.*;
     
     
     
    public class ClientSecretSessionKeyGenerator {
      // Put all files local to this dir
     
        static String pathToClntSecKey = "ClientsSecretKey";
     
      public static void main(String args[]) {
     
       // Client Generates Secert key and writes to file
     
        try {
          // File for writing output
          FileOutputStream keyFOS = new FileOutputStream(pathToClntSecKey);
          ObjectOutputStream keyOOS = new ObjectOutputStream(keyFOS);
     
          // Generate random AES key
          KeyGenerator keygen = KeyGenerator.getInstance("AES");
          SecretKey SecKey = keygen.generateKey();
          keyOOS.writeObject(SecKey);
     
          System.out.println("Random Secret Key generated and written to file: ClientsSecretKey");
     
          keyOOS.close();
          keyFOS.close();
     
     
        } catch (Exception e) {
             System.out.println(e);
        }
      }
     
    }
    right I hope thats it, just add what ever directory you want at the start.
    Last edited by Norm; November 19th, 2013 at 01:25 PM. Reason: slight mistake / changed quote to code tag

  19. #19
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,165
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem Encrypting a secret key

    Where is the one main() that calls all of the other main() methods in the correct order?
    You have commented out where I started calling the other mains:
    public static void main(String args[]) {
    //   ClientSecretKeyEncryption.main(args);

    The ClientSecretKeyEncryption main() method tries to read the file: pathToKey before it is written later in the same method????

    The path name Strings should NOT be in"s. The names are variables that have the values to be used.
    If you don't understand my answer, don't ignore it, ask a question.

  20. #20
    Junior Member
    Join Date
    Nov 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem Encrypting a secret key

    yeah, that gave me an error, I took it out and boom everything worked, the 3 are separate for the moment, but all should work.

    --- Update ---

    run the serverkeygen first, then the client random key generator second, and finally run the client key encryption, which is the one with the original problems.

  21. #21
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,165
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Problem Encrypting a secret key

    Can you make a class with a main() method that calls all the methods in the correct order? I don't like having to execute more than one class when testing. Testing often requires repeated execution so having it all in one class makes it easier to do it correctly.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. [SOLVED] Encrypting a text message
    By dianac in forum What's Wrong With My Code?
    Replies: 21
    Last Post: April 14th, 2013, 07:17 AM
  2. encrypting and decrypting a string
    By mist4lyf in forum What's Wrong With My Code?
    Replies: 17
    Last Post: April 9th, 2013, 08:41 AM
  3. my encrypting simple client to server program unable to get the key from client
    By Paytheprice in forum What's Wrong With My Code?
    Replies: 11
    Last Post: February 3rd, 2013, 07:15 AM
  4. Key Listener problem!
    By DouboC in forum What's Wrong With My Code?
    Replies: 1
    Last Post: January 17th, 2012, 07:47 PM
  5. How to set secret key
    By teppel in forum Java Theory & Questions
    Replies: 2
    Last Post: June 9th, 2011, 07:47 PM

Tags for this Thread