Save and load public/private RSA key on file

hi
i'm triyng to save and load an RSA key to a file
i generate the keys:
        KeyPairGenerator generator=null;
        KeyPair coppia=null;
        PrivateKey c_privata=null;
        PublicKey c_pubblica=null;
            generator=KeyPairGenerator.getInstance("RSA");
            //imposto la dimensione
            generator.initialize(1024);
            //genero le 2 chiavi
            coppia=generator.genKeyPair();
            //imposto la privata
            c_privata=coppia.getPrivate();
            //imposo la pubblica
            c_pubblica=coppia.getPublic();
//i save the key
        FileOutputStream file = new FileOutputStream("key");
        file.write(c_pubblica.getEncoded());
        file.close();and then i use another program that imports the key:
   Key chiave=null;
   FileInputStream file=new FileInputStream("key");
   byte[]byte_chiave=new byte[162];
             X509EncodedKeySpec chiave_spec = new X509EncodedKeySpec(byte_chiave);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            chiave = keyFactory.generatePublic(chiave_spec);but when i try to reload he key i get:
java.security.InvalidKeyException: IOException : DER input, Integer tag error
where am i wrong?
thanks

sorry...
this is the correct code:
        Key chiave=null;
        FileInputStream file=new FileInputStream(path);
        byte[]byte_chiave=new byte[file.available()];
        System.out.println("leggo: "+file.read(byte_chiave));
        X509EncodedKeySpec chiave_spec = new X509EncodedKeySpec(byte_chiave);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        chiave = keyFactory.generatePublic(chiave_spec);

Similar Messages

  • Save and load variables in java

    Hi ,
    I need a help about Save and load .
    I have a project(tool) which have JText, JRadioButton and other things also.
    I want to save all the changes for the next execution ( fresh startup or fresh bring up of the tool).
    Please let me know what will be the better way to save and load.
    can i get below use of C# in Java similar way ( below one is the C# code)
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")]
        internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
            private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
            public static Settings Default {
                get {
                    return defaultInstance;
            [global::System.Configuration.UserScopedSettingAttribute()]
            [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
            [global::System.Configuration.DefaultSettingValueAttribute("PATH")]
            public string SourceDirectory {
                get {
                    return ((string)(this["SourceDirectory"]));
                set {
                    this["SourceDirectory"] = value;
    }Can i do Strore and load without any File storage?
    Thanks in advance

    Assuming you are deploying applet or webstart than perhaps you can use PersistenceService?
    http://download-llnw.oracle.com/javase/1.5.0/docs/guide/javaws/developersguide/examples.html#PersistenceService

  • Save and load jtree

    Hi,
    I have a jtree which I would like to save and then load and display in a JPanel. Just for info, the nodes of the tree are instances of a user object i have created. Now I have looked into two ways of doing this:
    1) Serialize the actual JTree object; write it to a file using objectoutputstream and then read it in using objectinputstream, OR
    2) Serialize the tree model again using objectoutputstream then read the model back and create a new JTree initialising with the model i read in.
    I made some progress using the second approach, but when I load the tree model back and create a new tree with that model it just displays as a blank root with blank children. (Although the tree structure is the same).
    What am i doing wrong?
    The code is:
    public void saveTheTree() {
            TreeModel tm = tree1.getModel();
            try {
                 ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("treeModel"));
                 out.writeObject(tm);//the actual tree object
                 out.flush();
                 out.close();
            catch(IOException e){}
      public void openTheTree() {
           ObjectInputStream in = null;
             try {
                 in = new ObjectInputStream(new FileInputStream("treeModel"));
                 TreeModel atm = (TreeModel) in.readObject();
                 JTree loaded = new JTree(atm);
                 abPanel3.removeAll();
                 abPanel3.revalidate();
                 abPanel3.add(loaded, BorderLayout.CENTER);
                 abPanel3.revalidate();
             catch(Exception e) {
                  e.printStackTrace();
      }abPanel3 is where the tree is displayed and tree1 is my tree.
    Any help would be much appreciated!

    well the leaves are defaultmutabletreenodes instantiated with a user object which attaches a link and level to each one. According to the java documentation, defaultmutabletreenode is serializable, but do i need to serialize each node of the tree as well?
    Has anyone managed to save and load a jtree before?
    Thanks.

  • Save and load game into and from binary file

    hello!
    I'm new to java and i'm doing a game at school.
    i�m doing the same game and i�m doing a "save" and "Load" game. i'm doing this to save the game:
    public void jMenuJogoSalvar_actionPerformed(ActionEvent e) {
    System.out.println("SAlvar o Jogo actual");
    FileOutputStream out = null;
    ObjectOutputStream s = null;
    int valorRet = jFileChooserSalvar.showSaveDialog(this);
    if (valorRet == jFileChooserSalvar.APPROVE_OPTION) {
    try {
    out = new FileOutputStream(jFileChooserSalvar.getSelectedFile().getAbsoluteFile());
    s = new ObjectOutputStream(out);
    s.writeObject(mesa);
    s.flush();
    catch (FileNotFoundException fNFExc) {
    System.out.println("FileNotFound");
    catch (IOException ioExc) {
    ioExc.printStackTrace();
    finally {
    try {
    if (s != null) {
    s.close();
    if (out != null) {
    out.close();
    catch (IOException ex) {
    and i'm getting this error:
    java.io.NotSerializableException: com.sun.java.swing.plaf.windows.WindowsFileChooserUI
    i have already implemented the method Serializable into the classes that i'm trying to write and the classes they use but i still have this.
    Tell me what to do .
    thanks for the time.

    Does the Object mesa have a com.sun.java.swing.plaf.windows.WindowsFileChooserUI
    object in side it? or does any of the object that are in side it have a com.sun.java.swing.plaf.windows.WindowsFileChooserUI
    object?
    If you post code please use the code button

  • SQL Dev 2.1:Ability to save and load visual query models?

    At SQL Dev 2.1, do we now have the ability to save and load visual query models as with TOAD? Or has that functionality been rolled into the for-pay Data Modeler extension? Seemed strange to hide the functionality deep within SQL Worksheet, then not allow query models to be saved or loaded. From what I recall, load/save was scheduled to be in 2.0.
    I've not yet downloaded and installed 2.1, but also as I recall, it was promised to be a significant (e.g. new-feature rich) release. Has it lived up to that promise? Hoping also that it's not so buggy as to not merit an upgrade. At my workplace, folks have different versions of SQL Dev 1.X installed, each for the purpose of retaining functionality that got broken in future releases, etc. Would love to be able to advise them to retire their 1.X installs in favor of 2.1.
    Edited by: Dana N on Jan 21, 2010 6:45 AM

    Dana, We are working on the query builder. We have not done anything with it in recent releases as we knew that it needed completely overhauled and a
    couple of bug fixes were not going to give us the query builder we needed. Sue will be able to tell you more as the we get closer to releasing it as a feature.Thanks Barry. I know it's probably impossible to give firm dates, but my colleagues would love to know, ballpark, when query builder might be ready. Any particular year/quarter that's targeted for?
    A lot of the bugs in the 2.1 are probably my fault as we decided to build a framework which allowed tasks to be scheduled like eclipse and push them to the
    background. Coupled with this, we tore apart the worksheet to allow us to fit tasks in, but to also give us the ability to do some of the enhancement requests
    that you guys, our users, have been asking for. While its not perfect, I believe its getting much better from both a functionality and performance standpoint. The
    worksheet will not change again and there are no enhancements logged or scheduled which will do that. The issues that have come as part of 2.1 are being
    addressed and we are fixing the highest priority ones as we speak. One of my priorities is to make these components as rock solid as possible.Thanks again. It really is a nice tool to work with, and I'm grateful to have it. I would choose stability for existing features over new ones, but I suppose there always has to be a balance in development. What was really scary in the past was getting bizarre / wrong answers in query results--that's a complete show stopper; e.g. clicking on a row/col intersection in a result set row would show strange and false values. New features can wait, but core functionality must be solid. If one can't presume integrity of query results, it's game over--using a version of SQL Developer that returns inconsistent result sets between runs could be Considered Harmful, or so it is to me.
    Anyway, thanks for responding and I hope Oracle Corp gets you whatever assistance you need to improve the quality of existing functionality while adding new features; with one not being at the expense of the other. :-) Glad also to see Sue has authored a book on the tool. Hopefully that will drive customer demand and force increased allocation of development resources toward the product. I'd like to think having out-of-the-box tools that are a joy to use might even increase market share.
    Data Modeler I would love to use, but am completely priced out of it. Enterprise Architect from Sparx Systems is the best value there so far as I can tell.
    Dana

  • Cannot Read From Registry - Need to save and load config

    I have code the I have tested in other programs. I cannot read or write to the registry from a plugin. Any ideas?
    Any suggestions for the best way to save and load config information?
    Thanks!!!

    Hi Srikanth,
    Thank you for responding.
    I had a problem on one material. So deleted the request and Reload it from PSA. That issue got solved.
    And Now the problem is , Now my senior is saying Delete the data from April-09 till date and Reload it. The issue is My CUBE ( ZSD_C03 ) is updated with 4 data sources. 2LIS_11_V_ITM   ,  2LIS_13_VDITM   ,  2LIS_12_VCHDR  , 2LIS_11_VAITM .
    And I need to delete data from 2LIS_13_VDITM  data source . How Can I proceed for the current issue   ?
    Please suggest   ...
    Thank you ,
    Utpal

  • Core Data - Save and Load

    Hi
    I need to add functionality to my iPad app so that I can save and load notes from a UITextView then load them when the user selects the date in the UIDatePicker that it was originally saved on, much like a calendar, notes for different dates.
    I have asked around on StackOverFlow and people have been spoon feeding me code samples but I am not quite latching on. Complain all you like, but I really want to learn how to do this, however currently its fairly important that I get the functionality added in.
    Here is where I asked:
    http://stackoverflow.com/questions/4133405/core-data-iphone-save-load-depending- on-date
    http://stackoverflow.com/questions/4177398/save-and-load-data-coredata
    I have unsuccessful so far and if anyone can help me here I would be ever so grateful and even more so if you would take a short time to take a peek at my project. You can email me at [email protected], its a fairly simple project and Im sure especially for you guys you could see what I am doing.
    Hope you can help me out.

    Core Data pretty much does away with the concepts of saving and loading. The data is just there. If you want a particular view of data, on a specific date, for examples, you create a predicate to pull only the matching data into a particular controller/UI control.

  • I want to save and load the swf-file to a local disk of any user. Possible?

    Hi, It's good to see you.
    I am a developer in Web Flash Game.( I use AS3.0 )
    I want to save and load the swf-file to a local disk of any user,
    Because I want to decrease the time for loading a flash movie from site.
    Is it possible?
    If it is possible, I hope the swf-file has only one loading from site and
    it will be loaded from a local disk of any user after that.
    (I know a concept of Internet temporary file.
    I want to know the other techniques of only using AS3.0.)

    Hi,
    I have similar problem. We are producing a 70 meg browser based game and would like the user to be able to cache the game to avoid reloading the game the next time. Can this be done if the user authorise the save? If, so how? We don't care where the game is cached .
    Can we prompt the user to download the file by providing a link from within the SWF application?

  • Hi thee.  As logical as I can be.  I export a file back into my folder as a PSD.  I then export that file to PS.  Work on it, save and return it to LR.  The file goes to the bottom of the folder from where I have to put it back in the original place, taki

    Hi thee.  As logical as I can be.  I export a file back into my folder as a PSD.  I then export that file to PS.  Work on it, save and return it to LR.  The file goes to the bottom of the folder from where I have to put it back in the original place, taking time and driving me slightly mad.  Why does the file not go back to where it came from please?  Thanks  Tim

    Umm, but this folder is an amalgam of two cameras and five cards, and I want them in capture order!  Thanks for trying though Jim.
    Cheers
    Tim

  • Will zeroizing and regenerating the Default-RSA-Key affect any other general purpose keys on my ASA 5545x?

    I have an ASA 5545x that is a production device for receiving all AnyConnect VPN traffic for our organization. We purchased and installed a Comodo certificate to create the trust level necessary for our employees to connect. I'm attempting to enable SSH on the device for management purposes, but the current <Default-RSA-Key> does not allow me to initiate a valid SSH session. I have encountered this issue on other ASAs within our organization, and it hasn't been an issue to simply zeroize the current key and regenerate it to restore the ability to SSH to the devices. Where the snag comes in is that this 5545x is the only ASA that has a key installed that wasn't self signed. With that in mind, I have a few questions about whether 3rd-party signed keys are dependent on the self-signed keys on the device. I intend to zeroize both the <Default-RSA-Key> and the <Default-RSA-Key>.server certificates if they will not affect my VPN-associated Comodo key.
    Does the Comodo key depend on other keys existing on the ASA?
    Am I free to zeroize only the <Default-RSA-Key> without affecting the VPN associated Comodo key?
    Here is the result of the command "show crypto key mypubkey rsa" :
    Key pair was generated at: 12:02:29 CDT Aug 19 2014
    Key name: <Default-RSA-Key>
     Usage: General Purpose Key
     Modulus Size (bits): 1024
     Key Data:
    <Redacted>
    Key pair was generated at: 10:16:52 CDT Sep 20 2012
    Key name: my.comodo.key
     Usage: General Purpose Key
     Modulus Size (bits): 2048
     Key Data:
    <Redacted>
    Key pair was generated at: 01:35:42 CDT Jul 30 2014
    Key name: <Default-RSA-Key>.server
     Usage: Encryption Key
     Modulus Size (bits): 768
     Key Data:
    <Redacted>
    Thank you to any and all that assist me in understanding how the ASA handles certificate keys.

    As long as the Comodo-signed certificate is bound to the my.comodo.key private key (i.e. you used that key when generating the certificate signing request), you should be fine to zeroize the Default-RSA-Key. The latter should ideally only be used for ssh access.

  • How can I Save and Load the Configurat​ion File of a VNA HP8510C with LabView

    Hello, I'm working with a HP8510C. In order to simplfy the use, I try to save and to load the configuration file. Actually, such files are saved in the HP8510C, but there is only 4 places to save. It will be more interresting when I can storage this file in the computer with Labview. I don't have found anything about in the Documentation.
    Has someone already deal with such a question?
    Géraud DEVOS
    IWE Karlsruhe

    geraudIWE a écrit:
    Hello, I'm working with a HP8510C. In order to simplfy the use, I try to save and to load the configuration file. Actually, such files are saved in the HP8510C, but there is only 4 places to save. It will be more interresting when I can storage this file in the computer with Labview. I don't have found anything about in the Documentation.
    Has someone already deal with such a question?
    Géraud DEVOS
    IWE Karlsruhe
    Hello GerauIWE,
    Have you try to use the Hewlett-Packard 8510C Instrument Driver?
    You can download it on :
    http://sine.ni.com/apps/we/niid_web_display.drv_re​sults?p_app_area=&p_man=hewlettPackard&p_keywords=​8510c&p_inst_type=&p_env=845&p_drv_type=&p_int=
    Best Regards,
    Sanaa T
    National Instruments France
    Sanaa T.
    National Instruments France
    #adMrkt{text-align: center;font-size:11px; font-weight: bold;} #adMrkt a {text-decoration: none;} #adMrkt a:hover{font-size: 9px;} #adMrkt a span{display: none;} #adMrkt a:hover span{display: block;}
    >> http://www.nidays.fr/images/081110_ban_nidays09_468X60.gif

  • Parent  changes between save and load of a PDF file

    I am using LiveCycle 8.2 and Acrobat 9.2 - and Reader 9.2
    I have an automated process that uses a plug-in to fill out and save a PDF form using XML data.
    This works well - saves time , etc.
    I have a problem where a certain data element seems to have a different heirarchical relationship in the Reader  than in Acrobat..
    I have added some xfa.host.MessageBox() statements to print out data as the form is being saved  and then when it is loaded into the Reader - these  values are not the same -
    but i have checked and when I laod it using Acroabt everyhting is the same as when the data was saved - but there a different relationship apparently exists when I load the form using the reader.
    Has anyone seen this before ?
    Is there anything that I can do about it ?
    Any help is appreciated - thanks

    a snippet of the code involved is listed here :
    Provider.page2.Practice.Associatec.AssociateType.AssociateTypeDescription::initialize - (JavaScript, client)
     var CovgYN;
    var msg; var lineofdata; 
    var assttype = this.rawValue;msg
    = "Check1 : " + assttype + " = " + this.parent.parent.AssociateLastName.rawValue;xfa.host.messageBox(msg);
    lineofdata= this.parent.parent.AssociateFirstName.rawValue + " " + this.parent.parent.AssociateLastName.rawValue + " " + assttype + " -" + CovgYN; 
    The data contained in the msg and lineofdata variables - is different in Acrobat 9.2 and The Reader ... It is correct in Acrobat when I load the form and Import the XML data file.
    When the correct data Form is saved and loaded using the reader the values "parent" is different so - the values are not the same -=
    This is a serious problem !.
    Is this a known bug or issue  ?
     

  • Possible to script palette menus Save and Load Curves?

    Is it possible to script CS4 Photoshop's palette menus? Specifically, the "Save Curves Preset ..." and "Load Curves Preset" ... of the Adjustments Palette.
    I have 600 images, some of which have layer>new adjustment layer>curves applied.
    I want to save the curves using the image name. Later, I want to be able to load the appropriate curve.
    E.g., for image001.tif, the curve would be image001.acv
    (I already have a loop set up to iterate through the files and get the file names.)

    Thank you.
    I got both scripts working without JS or AS errors, but, when trying to load .acv files generated by the second script, CS4 Photoshop gave an error:
    "Could not load the curves because the file is not compatible with this version of Photoshop"
    (The loading script works fine when loading .acv files created directly from Photoshop.)
    The only change I made to your Save Curves code was:
    FROM: var myACV = new File('~/desktop/myCurve.acv')
    TO: var myACV = new File(file);
    and made the code a function:
    saveCurves(file)
    YOUR CODE HERE
    so that I could incorporate it into the Applescript.
    Maybe that was naive (I'm not very knowledgeable about JS).
    Here are the scripts I'm using:
    SAVE CURVES:
    set gammaFolder to "/Users/me/Desktop/myproject/gamma/"
    tell application "Finder"
              set TheFolder to choose folder
              set FileList to every file of entire contents of TheFolder as alias list
    end tell
    repeat with theFile in FileList
              set thefilename to theFile as string
              set text item delimiters to ":"
              set thefilename to last text item of thefilename --remove path
              set text item delimiters to "."
              set thefilename to first text item of thefilename --remove extension
              tell application "Adobe Photoshop CS4"
      activate
      open theFile
                        tell current document
                                  if exists layer "Curves 1" then
                                            set current layer to layer "Curves 1"
                                            do javascript "saveCurves('" & gammaFolder & thefilename & ".acv');
    function saveCurves(file) {
    -- SAVE CURVES JAVASCRIPT HERE
    };" --show debugger on runtime error
                                  end if
                        end tell
              end tell
    end repeat
    LOAD CURVES:
    set gammaFolder to "/Users/me/Desktop/myproject/gamma/"
    tell application "Finder"
              set TheFolder to choose folder
              set FileList to every file of entire contents of TheFolder as alias list
    end tell
    repeat with theFile in FileList
              set thefilename to theFile as string
              set text item delimiters to ":"
              set thefilename to last text item of thefilename --remove path
              set text item delimiters to "."
              set thefilename to first text item of thefilename --remove extension
              set acvFile to gammaFolder & thefilename & ".acv"
              tell application "Finder" to set acvExists to exists my POSIX file acvFile
              if acvExists then
                        tell application "Adobe Photoshop CS4"
      activate
      open theFile
                                  tell current document
                                            if not (exists layer "Curves 1") then
                                                      do action "Create Curve Layer" from "MyActions"
                                            end if
                                            set current layer to layer "Curves 1"
                                            do javascript "loadCurves('" & gammaFolder & thefilename & ".acv');
    function loadCurves(file) {
    -- LOAD CURVES JAVASCRIPT HERE
    };" --show debugger on runtime error
                                  end tell
                        end tell
              end if
    end repeat

  • How do you create a Browser cookie in Captivate to save and load a set of variables?

    Using the below tutorial I am trying to set a cookie that remembers the menu of sections that have been viewed when the browser reopens. Basically sets and loads 6 variables with a cookie. But it's not working and I can't find the JavaScript to debug in Chrome. Alternately does anyone know of a better tutorial for setting cookies in Captivate then this post?
    Eating JavaScript Cookies with Adobe Captivate - CaptivateDev.com

    Thanks for replying. The variables define a number of states within the training. Mostly a main menu showing modules completed or not and also defining areas as locked or unlocked. So it's more then a text caption. I'd like a button on the intro/splash screen that when clicked loads about 6 variable as 0 or 1 from the cookie. Then the user would continue to the training with all the variables loaded.

  • HT4075 I don't have any problems merging the documents by dragging, but when I try to save and open afterwards, only the last shown doc was saved, not the combined files I wanted to merge. I tried save and export, how can I create the file after merging?

    Hi, I'm having trouble saving the documents when merging in Preview. I don't have any problems merging the pdf documents by dragging them in preview, but when I try to save and open afterwards, only the last shown doc was saved, not the combined files I wanted to merge. I've tried save and export, but none merge the documents after saving... how can I create the file (with all the pdf files) after merging?

    That's a comment in the file. It has no effect at all.

Maybe you are looking for

  • Batch IDOCs to single message in XI

    Hi Experts, I have situation wherein I am getting a batch IDOCs of same type and needs to fed in XI as a single message. I would like to know a) How a batch IDOCs can be made to single message? b) How XI can check the number of IDOCs in a batch? c) W

  • When I load a XML in a XFA form can I specify the font color?

    When I load a XML in a XFA form can I specify the font color? Or can I specify background color, font type(bold, ...).

  • Photos on iPad

    When I upload photos on my iPad should they transfer to my iPhone? Both devices are up to date with ios5.

  • SO attachements

    Hi, i have few sale orders,each order having attachement. i want to download those attachements in application server by executing the report in BACK GROUND only. I can down load fiel in local pc and application server via fore ground. Please give me

  • All ports in use?

    I have some java code that connects to a host running on the same machine. The code works fine on my PC (Win2k) and on a laptop(NT), but doesn't on another PC(NT). mySocketConnection = new Socket( hostAddr, hostPort ); throws an IOException for any p