How to Store des key in keystore

I'm writing a program to writing a symmetric key (DES key) to keystore.
see the program below:
public class KeyStoreTest {
public static void main(String[] args) {  
try {
String keyStorePass = "password";
String keyStorePath="c:\\newKeyStoreName";
KeyStore ks = KeyStore.getInstance("JCEKS","SunJCE");//we need to use JCEKS because we need to write sysmetric key into key into keystore
ks.load(null,keyStorePass.toCharArray());//null because i'm creating a new keytsore
//save my secret key
KeyGenerator keyGen = KeyGenerator.getInstance("DES");
SecretKey key =keyGen.generateKey();
ks.setKeyEntry("peter",key.getEncoded(),null);//here we put an alias peter with the generation key into the keytore.no problem here
//then i try to check whether peter is exist.it return true which mean peter exist in the keystore.
//the main point is to get key back.
//when i use the getKey method it req a password.
//wht password should i use.
ks.getKey("peter",keyStorePass.toCharArray());//when i try this want.I got an error. and when i put the password equal to null i still got an error
FileOutputStream fos = new FileOutputStream(keyStorePath);
ks.store(fos, keyStorePass.toCharArray());//this lini just to store the keystore that i created.
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
please help me.i hav done this for the whole week.i hav search the web and still did't get an answer.sorry coz my english is bad.Thanx to all.

As mensioned in the message you can read, the JCE provider implementations can be used when they are first authenticated. This is done through checking their class signature,saved in the jar file, on special instantiatings. So you can not extract the classes and use them in a directory; even rejar them will not help you unless you have got a certificate from sun to sign the jar file. Use the original jar file.
For further litrreature on the JCEAuthentication you can read http://java.sun.com/products/jce/doc/guide/HowToImplAProvider.html#JCEAuth

Similar Messages

  • How to read DES key from a file?

    I stored the DES key in the file as follows:
    KeyGenerator keygen = KeyGenerator.getInstance("DES");
    SecretKey Key = keygen.generateKey();
    FileOutputStream ostream = new FileOutputStream("t.tmp");
         ObjectOutputStream p = new ObjectOutputStream(ostream);
         p.writeObject(Key) ;
         p.flush();
         ostream.close();
    I don't know if there is problem with the above code, I am just new to java cryptography.
    I have problem read in the key and store it in the DES key object to be used for decryption.
    Can someone please tell me how to do it and a simple example will be appriciated.
    thanks
    Jeff

    Thank you for your help. after getting the key from the file( the output of the key is com.sun.crypto.provider.DESKey@fffe786d, not sure if it is right), I use this key to decrypt the message sent from the client program.
    here is the code:
    ObjectInputStream ois=new ObjectInputStream(data.getInputStream());
    String c = ois.readLine() ;//should I convert the byte[] data to String?
    ois.close() ;
    jTextField1.setText(c) ;//display the cipher text to the first textfield
    byte[] ciphertext = c.getBytes() ;
    // System.out.write(ciphertext) ;
    // get key from file
    FileInputStream in = new FileInputStream("t.tmp");
    ObjectInputStream oin = new ObjectInputStream(in);
    SecretKey Key = (SecretKey)oin.readObject();
    oin.close();
    in.close();
    System.out.println(Key) ;
    //decrypt
    Cipher C = Cipher.getInstance("DES");
    C.init(Cipher.DECRYPT_MODE, Key);
    // Decrypt the ciphertext
    byte[] cleartext1 =C.doFinal(ciphertext);
    System.out.write(cleartext1) ;//doesn't show anything!!
    System.out.println("this is cleartexxt");//doesn't even show this!!
    String display = new String(cleartext1);
    jTextField2.setText(display);
    why there is no output from System.out.write(cleartext1)? where did I go wrong?
    thank you.
    Jeff

  • How to store duplicate keys in HashMap

    Hi,
    sun guys,
    please any one guide me how to store duplicate values in the haspmap.
    i think we need override the equals and hash code methods. am i right??
    if so guide me how to do it??
    thanks in advance,
    nagaraju.

    uppala wrote:
    Hi,Hi,
    sun guys,Most of the people who answer questions here, aren't from Sun.
    please any one guide me how to store duplicate values in the haspmap.
    i think we need override the equals and hash code methods. am i right??
    if so guide me how to do it??Associate the key with a list or a set, and place the values in that list/set.
    A put will then mean that you first call get to see if a list already is associated with the key. Place the value in the list in that case. Otherwise create a new list. Place the value in the list, and then call put with the list as value.
    Kaj

  • How to store data,key,cert,... in javacard

    I'm newbie in javacard
    I develop it by use RMI model
    I develop to similar EMV specification but don't exactly
    EMV spec told me that data element such as KEY, CERT,COUNTER,ExpirationDate,...anything. will be keep in file , with tree structure.
    above is not importance
    I try to understand: How to save file into javacard?
    I read a lot of help and manual from sdk , this website ,forum
    and I feel it's impossible to save file (such as text file *.txt, photo file *.jpeg,*.gif) into javacard directly,
    Is my understand correct?
    I try to understand PhotoCardApplet Demo that come with sdk
    run it , have fun with it, try to understand code
    I saw the demo bring the pictures file from reader-side save into card to the "Object" of byte[]
    Is there just only one way to keep KEY,CERT,..DATA in Object in the applet?
    Can it possible to seperate these data away from applet and keep it individual? ( seperate applet , text file ,photo file ,... keep in javacard)
    And if it possible plz tell me how to do it with detailed.
    thx for every answer.

    EMV spec told me that data element such as KEY,
    CERT,COUNTER,ExpirationDate,...anything. will be
    keep in file , with tree structure.That is the file-system part of an EMV smart card. That has nothing (directly) to do with java cards. Most java cards has a file system part, too but that isn't accessible from within the java card applet.
    I try to understand PhotoCardApplet Demo that come
    with sdk
    run it , have fun with it, try to understand code
    I saw the demo bring the pictures file from
    reader-side save into card to the "Object" of
    byte[]
    Is there just only one way to keep KEY,CERT,..DATA
    in Object in the applet?
    Can it possible to seperate these data away from
    applet and keep it individual? ( seperate applet ,
    text file ,photo file ,... keep in javacard)
    No, loading data into the memory which belongs to your java card applet instance makes the data become a part of the applet. If you delete the applet all stored data will be deleted, too.
    You can only separate different objects within your applet by using separate byte-arrays or other java card objects.
    Jan

  • How to strore keys in KeyStores..of JCE Api..

    Hi ,
    i'm trying to implement a program mySignature that creates and verifies digital signatures using Java Cryptography Extension.
    I am using the DSA Algorithm for encryption.
    Now the problem is once i create the private keys and public keys i am not able to store them to the KeyStore.
    here is the code I wrote
    package my.security.test;
    import java.io.BufferedInputStream;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.security.Certificate;
    import java.security.InvalidAlgorithmParameterException;
    import java.security.InvalidKeyException;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.KeyStore;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.NoSuchProviderException;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.SecureRandom;
    import java.security.Signature;
    import java.security.SignatureException;
    import java.security.cert.CertificateException;
    import java.security.cert.CertificateFactory;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.RSAKeyGenParameterSpec;
    * @author sandeepk
    * To change this generated comment edit the template variable "typecomment":
    * Window>Preferences>Java>Templates.
    * To enable and disable the creation of type comments go to
    * Window>Preferences>Java>Code Generation.
    public class MySignature {
         public static void main(String[] args) {
              KeyPairGenerator keyGen = null;
              FileOutputStream sigfos = null;
              try {
                   Signature signature = Signature.getInstance("SHA1withDSA", "SUN");
                   keyGen = KeyPairGenerator.getInstance("DSA", "SUN");
                   keyGen.initialize(1024);
                   KeyPair keyPair = keyGen.generateKeyPair();
                   PrivateKey privateKey = keyPair.getPrivate();
                   PublicKey publicKey = keyPair.getPublic();
                   KeyStore ks = KeyStore.getInstance("JKS", "SUN");
                   System.out.println("Here1");
                   ks.setKeyEntry("privkey", privateKey, "pass".toCharArray(), null);
                   System.out.println("Here2");
                   ks.setKeyEntry("pubkey", publicKey, "pass".toCharArray(), null);
                   System.out.println("Here3");
                   sigfos = new FileOutputStream("C:\\keystore");
                   ks.store(sigfos, "pass".toCharArray());
                   signature.initSign(privateKey);
                   // Reading the contents of them message file               
                   FileInputStream fis = new FileInputStream("C:\\message.txt");
                   BufferedInputStream bufin = new BufferedInputStream(fis);
                   byte[] buffer = new byte[1024];
                   int len;
                   while (bufin.available() != 0) {
                        len = bufin.read(buffer);
                        signature.update(buffer, 0, len);
                   bufin.close();
                   // Writng the signature to a file
                   byte[] realSig = signature.sign();
                   sigfos = new FileOutputStream("C:\\sig.txt");
                   sigfos.write(realSig);
                   sigfos.close();
              } catch (InvalidKeyException e) {
                   e.printStackTrace();
              } catch (NoSuchAlgorithmException e) {
                   e.printStackTrace();
              } catch (FileNotFoundException e) {
                   e.printStackTrace();
              } catch (SignatureException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
              } catch (NoSuchProviderException e) {
                   e.printStackTrace();
              } catch (KeyStoreException e) {
                   e.printStackTrace();
              }catch(CertificateException e){
                   e.printStackTrace();
    I get an error while i try to store the key on to the KeyStore, if I comment out these lines of code the program runs without any probs.
    Can any one help me with this issue, i'ld be thank full to them
    -Chau
    Sandy

    We use 'PDDocCreateWordFinder' , 'PDWordFinderEnumWords' to extract the text from Adobe Reader document through Code, Not tool.
    But, by using these APIs, I can't see any difference in 'new line/row' or 'paragraph' if exists in PDF doc.
    I need such API which can give the exact format of Adobe Reader doc according to the content exists in that PDF doc.
    Thanks!

  • How many different binary search trees can store the keys {1,2,3}

    I am having a hard time answering this question:
    How many different binary search trees can store the keys {1,2,3} or how about {1,2,3,4} and how did u figure this out?
    Any responses helpful
    Thanks!

    the.maltese.falcon wrote:
    practissum, shame on you for doing this chap's homework for him. @ the OP, this is a Java forum, not a basic data structures forum.
    Also, you forgot the cases
    3
    1
    2and
    1
    3
    2
    the.maltese.falcon, I was just trying to help him get started with the base case. Notice that I didn't enumerate all of the possibilities, but was trying to help the OP get on the right track. You, however, have done this. So shame to you, sir!

  • How to create manual key for AES with 256 key size

    we are just finding Different Approch for secure Key Genration and Store.
    For security purpose which way would be secure to store key in database and retrive that key.
    And can u tell me how to create secure maual key.
    Database user has access they should not able to find the what key we are using .
    Anybody has idea.

    1) Use 'keytool' with option -genseckey
    2) Use SecureRandom and store in a Java Keystore.
    3) Use a Secure Random with something like http://www.strongkey.org/
    4) Use hardware encryption such as produced by nCipher and others.
    There are many other approaches and I would suggest that you bring in an expert to advise you.

  • DES Key - Client Side

    Hi,
    I would like to be able to generate a DES key, store it in a file, and use the key to encrypt my message and send it to my friend�s server. I�ve started the program, but am not sure where else to go with it. It�s on the next post. Any help is greatly appreciated.
    Thanks,
    James
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import javax.crypto.*;
    public class Cipher
         public static void main(String[] args) throws Exception
              String message = "Hi John, here is the first message.";
              String host = "xxx.xxx.xxx";
              int port = 7999;
              Socket s = new Socket(host, port);
                        //Help here
              // DES key.
              //Storage of DES key
              // Encrypt the message using the key and send it to the server         
    }

    Please excuse my ignorance, but what is keystore?Search the web!
    http://www.unix.org.ua/orelly/java-ent/security/ch11_01.htm
    I can't really comment, because I have yet to use it.

  • How to store jsp session data of different user in util.hashmap

    how to store jsp session data of different user in java.util.hashmap
    and access the data of all user on the server side
    The same example is given in professional jsp but its not working.
    I can use getIds() of httpsessioncontext but it's depricated

    Hi
    I'm trying to make an example.
    With the following codes you can get the date from the session.
    request.getSession().getAttribute("sessionname")
    To store it in a hashmap you could do it like this ->
    Hashmap hm = new Hashmap();
    hm.put(Object key, request.getSession().getAttribute("sessionname"));
    I hope you understand it if not just write it!
    Cyrill

  • How to store a text file in a hash table in C#?

    I am fairly new to c#. I am creating a console application project for practice. I am supposed to create a program that reads a text file (it's a poem), store it in a hash table, have two different sorts, and unhash the table. I managed to get the poem read
    by using streamwriter, but now I am not sure how to store it in a hash table. 
    I'm not sure if I am doing this hash table correct, but I made my hash table like this to store the text file: 
          Hashtable hashtable = new Hashtable();
                hashtable[1] = (@"C:\\Documents\\Datastructures\\Input\\Poem");

    Hi,
    Hashtable in C# represents a collection of key/value pairs which maps keys to value. Any non-null object can be used as a key but a value can. We can retrieve  items from hashTable to provide the key . Both keys and values are Objects.
    Here is a sample about Hashtable,
    Hashtable weeks = new Hashtable();
    weeks.Add("1", "SunDay");
    weeks.Add("2", "MonDay");
    weeks.Add("3", "TueDay");
    weeks.Add("4", "WedDay");
    weeks.Add("5", "ThuDay");
    weeks.Add("6", "FriDay");
    weeks.Add("7", "SatDay");
    //Display a single Item
    MessageBox.Show(weeks["5"].ToString());
    //Search an Item
    if (weeks.ContainsValue("TueDay"))
    MessageBox.Show("Find");
    else
    MessageBox.Show("Not find");
    //remove an Item
    weeks.Remove("3");
    //Display all key value pairs
    foreach (DictionaryEntry day in weeks)
    MessageBox.Show(day.Key + " - " + day.Value);
    >>I managed to get the poem read by using streamwriter, but now I am not sure how to store it in a hash table
    Hashtable hashtable = new Hashtable();
    hashtable[1] = (@"C:\\Documents\\Datastructures\\Input\\Poem");
    But follow your scenario above, you just store a string path to hashtable not a file.
    About saving data to a file, you can use the following code.
    // Write the string to a file.
    System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
    file.WriteLine(lines);
    file.Close();
    Best wishes!
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Trust store and key store

    What is the fundamental difference between trust store and key store ?

    what this means to an end user ?I have no idea, but what it means to me is that JBoss don't understand the difference between them any more than you did when you asked the question.
    A keystore is a high-security item that needs to be kept under lock and key as it contains credentials sufficient to identify that peer legally, and I mean in a courtroom in a dispute over millions of dollars. A truststore on the other hand is a collection of public certificates whose security requirement is to prevent people adding untrustworthy certificates to it. A completely different matter. In any large organization, the personnel with the authority over the keystore would never be the same as the personnel with authority over the truststore. Putting both in the same file compromises the security of both. It makes no sense whatsoever.

  • How to create Secret Key.

    Hi,
    Can any one point me, where I can find to create a Secret Key and store it inside the KeyStore ?
    I am trying to use the w3'c encryption / decryption and I want to create a key which can be compatible to TripleDESCBC or rsa-1_5.
    Since I am new to all these, any pointer will be helpful.
    Thanks in advance,
    -Kalpesh.

    Asuming you have a JCE Provider installed that support 3DES, try this:
    import javax.crypto.*;
    SecretKey generateSecretKey ( String alg ) {
      SecretKey sk = null;          
      try {
        KeyGenerator keyGen = KeyGenerator.getInstance(alg);
        keyGen.init(new SecureRandom());
        sk = (SecretKey)keyGen.generateKey();
        return(sk);
      } catch (Exception e) {
        e.printStackTrace();
        return null;
    }Pass in "DESede/CBC" or "3DES/CBC" for 'alg'. You might also want to specify the pading, depending on the Provider you're using. BouncyCastle is a good open-source JCE provider that supports 3DES.
    Note that RSA is a MUCH different beast - you want a key-PAIR- there, neither half of which is a SecretKey.
    Good luck,
    Grant

  • How to set F2 Key to Convert to Profile OSX 10.7

    Can someone clue me how to set my F2 key to Edit> Convert to Profile (instead of my display brightness)?
    I used to be able to do this quite easily prior to 10.7, but now I can't figure it out.
    Photoshop: Edit Keyboard Shortcuts> Convert to Profile won't accept my F2 key (it lights up my brightness)
    System Prefs> Keyboard> Shortcuts is probably the key, but unchecking F2 doesn't solve the problem
    PS13.0.1

    conroy wrote:
    In this case, I don't see anything to complain about.
    Seems pretty clear gator soup didn't expect that function to be taken over, and it's lucky that someone thought to include an option that could be changed to cause the function key to work the right way.  When do you think they might drop that option to reduce support cost even further?
    Does Apple think there are just too many keys on the keyboard for the average user?  Maybe they've been taking too many service calls from ignorant users who can't figure out how to press two keys at once to change their screen brightness and instead of trying to educate people on how to actually use a computer they just choose to cater to their stupidity.
    I guess one must not need the F2 key to play most of the games in the App Store.
    I think I'll drop off the forum now.  I'm clearly in a foul mood today.  Something about testing Windows 8 stuff sent me down this path. 
    -Noel

  • Plz Help! How to Store digital certificate on to java card?

    We are working on java cards.......
    But i don't know how to store digital certificate on to java card?
    Any "step-by-step procedure" to follow after getting the certificate will be appriciated.....
    Plz any relative information if u have do reply...............
    Its urgent..............
    Thanks in advance..........

    I'm not understanding the confusion. Instead of storing a picture you are storing a certificate. Treat it as a blob of data. You will send data, approx 250 bytes in length, then send the next blob beginning from previous offset, etc. On the card, you store data into a large byte array beginning at the offsets. Read the picture sample again.
    You would generate the key pair using the KeyPair class. Send that public key to the CA and store the cert returned from the CA.
    If you are attempting PKCS#15, I wouldn't go that route until you understand Java Cards and the PKCS specification.

  • Help with DES key

    In my Java application, I use a DES key to encrypt files. Im not much of a security guy, so was wondering what a DES key looks like. Is it a string of characters? Is it a number?.
    The reason Im asking is that my application requires the user to note down the key and remember it (perhaps by jotting it down on a piece of paper). The key value has to hence be displayed to the user. How can I display the key value in Java in a human readable form so that next time he types it into my application, the application gets the same key it printed out earlier?
    Many thanks

    Seems a silly approach asking the user to remember the key but you will need to encode the key from binary into human readable form. You could try Base64 or Hex encoding.
    P.S. A PBE approach to the whole thing would probably be better.

Maybe you are looking for

  • S076 SOP table for SD report (Sales Forecast Report ).

    Hi We are using S076 SOP table for SD report (Sales Forecast Report ).  This has only material number as key at present , where as we want to know if flexible planning will give material/shipto as key for forecast. Thanks In advance .

  • In mail I am all of a sudden unable to fully delete messages.

    In Mail I am suddenly unable to delete messages. When I do the msg is replaced by another that is titled no sender / no subject / no content and has a date of 69-12-31.  To compound things there is seemingly no way to delete the new message.   Any su

  • How to get a single particle image after particle analysis in vision development toolkit

    Hi all, After a long time I am here again to find out some solutions regarding image processing. I have an RGB image with a number of particles in it. For processing I have made it binary image and then particle analysis function is used. It is showi

  • Need help!! Bad TV Show Download

    I was downloading Nothing Takes the Past Away (Wildfire, Season 2) and was watching it as it downloaded and my computer sort of froze. It kept downloading and playing the show, but it wouldn't let me exit out of the show. I decided to leave it like t

  • How do I cancel my Subscription!?!!

    Please help!!! I want to cancel my subscription and the web-site loops me...HELP!  Someone please help.  I've bee charged $13.99/mo and I have never used this service. What do I do? Thanks to anyone who can help. -dg