Storing .pfx file in mysql

All,
I am trying to store a .pfx file in mysql.
What is the best way to do this?

I'm using mysql, no CLOB only BLOB.
Currently I am trying to base64 encode the .pfx text and store it into a longtext field.
The problem is when I retrieve it:
Exception in thread "main" java.io.IOException: toDerInputStream rejects tag type 114
        at sun.security.util.DerValue.toDerInputStream(DerValue.java:806)
        at com.sun.net.ssl.internal.pkcs12.PKCS12KeyStore.engineLoad(PKCS12KeyStore.java:1201)
        at java.security.KeyStore.load(KeyStore.java:1185)
        at com.emoneyadvisor.services.util.ThirdPartyCertificate.<init>(ThirdPartyCertificate.java:29)
        at emoneyjava.Emoney.main(Emoney.java:135)My cert is already made and I'm not going to change the format.
Any ideas on how I can easily resolve this?
I guess I understand that java is not understanding the format.
Here I get the contents of the cert file:
import com.Ostermiller.util.Base64;
public static String getFileContents(String filename) throws IOException {
          File file = new File(filename);
          InputStream is = new FileInputStream(file.getPath());
          // Get the size of the file
          long length = file.length();
          // Create the byte array to hold the data
          byte[] bytes = new byte[(int)length];
          // debug - init array
          for (int i = 0; i < length; i++){
               bytes[i] = 0x0;
          // Read in the bytes
          int offset = 0;
          int numRead = 0;
          while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
               offset += numRead;
          // Ensure all the bytes have been read in
          if (offset < bytes.length) {
               throw new IOException("Could not completely read file "+file.getName());
          // Close the input stream and return bytes
          is.close();
          String id = null;
          try {
          ByteArrayOutputStream baos = new
          ByteArrayOutputStream();
          ObjectOutputStream stream = new
          ObjectOutputStream(baos);
          stream.write(bytes);
          stream.flush();
          stream.close();
          id = new
          String(Base64.encode(baos.toByteArray()));
          } catch(Exception ex) {
          ex.printStackTrace();
          return id;
     }Using setString with PreparedStatement I add the cert to the LONGTEXT field.
Then I use this to retrieve the cert:
public static InputStream getCert(String coid){
     InputStream is = null;
     Connection conn = null;
     PreparedStatement pstmt = null;
     String sql = "select cert from table where coid = ? limit 1";
     String cert = null;
     try{
          conn = TradeHelper.connect();
          pstmt = conn.prepareStatement(sql);
          pstmt.setString(1, coid);          
          ResultSet rs = pstmt.executeQuery();
          while(rs.next()){
               cert = rs.getString("cert");
     }catch(Exception e){
          e.printStackTrace();
     }finally{
          try{
               TradeHelper.closeConnection(conn);
               pstmt.close();
          }catch(Exception e){
               e.printStackTrace();
     Base64.decode(cert);
     //lets get an inputstream on the cert.
     try {
          is = new ByteArrayInputStream(cert.getBytes("UTF-8"));
     } catch (UnsupportedEncodingException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
     return is;
}Edited by: iketurner on Apr 14, 2010 10:08 AM

Similar Messages

  • Send files stored as blob in mysql as attachment

    Hey guys,thanks for your attention.
    Here is my question:
    Now,in my website I can upload some files into MYSQL DB,and I want to select some of these files as attachment to be sent to customer.
    I know it is very easy if the file is stored as a file in a particular directory,what i need is to get the path of the file and then use a javamail function "attachFile(path)",how can i do it when the file is stored as blob?Is there any javamail function which can be used to manipulate this process?

    Use ByteArrayDataSource, included with JavaMail 1.4 or available in
    the demo directory in earlier versions.

  • Help : How to import .pfx file to keystore

    Hi,
    I need to generate digital signature for some data string. I got the pfx file with password blank.
    it shows the following detailsusing keytool.
    keytool -list -keystore rating/ebs/scripts/MPay_certificate_11072003.p12 -storetype pkcs12
    unknown attr1.3.6.1.4.1.311.17.1
    Enter keystore password:
    unknown attr1.3.6.1.4.1.311.17.1
    ***************** WARNING WARNING WARNING *****************
    * The integrity of the information stored in your keystore *
    * has NOT been verified! In order to verify its integrity, *
    * you must provide your keystore password. *
    ***************** WARNING WARNING WARNING *****************
    Keystore type: pkcs12
    Keystore provider: SunJSSE
    Your keystore contains 1 entry
    c1e673ff559b00e86a399a1b21e4aed2_6ee3fa08-8ba8-4ff1-a8fd-01031842a3a3, Aug 18, 2003, keyEntry,
    How can I generate the keystore file and know the private key alias so that i can generate the sign using sign().
    thanks in advance.
    Ranjan

    It is possible to import a .p12 file into a keystore with a small Java program...
    I found a sample to do this about a year ago, the source page is no longer valid. I have made some slight modifications to the original program, but left credit to the original author in the top (to the best of my knowledge).
    Sample execution being:
    $ java KeyStoreMove PKCS12 ~/igo.p12 p12-pas JKS ~/.keystore key-pas
    Source alias: lester igo id #2
    Rename alias to [<return> to keep original alias]: my-cert
    New alias: my-cert
    importing key lester igo id #2
    keystore copy successful
    * This code has been downloaded from the internet and contained no license.
    * The Source for this was: http://home.istar.ca/~neutron/Thawte/KeystoreMove.txt
    * The Page referencing it was: http://home.istar.ca/~neutron/Thawte/index.html
    * The author appears to be:
    * Michel I. Gallant
    * [email protected]
    import java.io.*;
    import java.security.*;
    import java.util.*;
    public class KeyStoreMove {
    public static void main(String args[]) throws Throwable {
    java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    if (args.length<6) {
    System.out.println(
    "\nKeyStoreMove Usage: \njava KeyStoreMove <source> <destination> where\n" +
    " <source> and <destination> are " +
    "<storetype> <keystore> <password>\n");
    System.out.println(" - Requires jsse for PKCS12 keystore support \n" +
    " - source storetype can be JKS or PKCS12\n" +
    " - destination storetype must be JKS type (PKCS12 write not supported)\n") ;
    System.exit(0);
    FileInputStream in;
    // -------- Load source keystore to memory ---------
    in = new FileInputStream(args[1]);
    KeyStore ksin = KeyStore.getInstance(args[0]);
    char[] pwin = args[2].toCharArray();
    if (pwin.length==0) { pwin = null; }
    ksin.load(in,pwin);
    in.close();
    // -------- Load destination keystore initial contents to memory ---------
    in = new FileInputStream(args[4]);
    KeyStore ksout = KeyStore.getInstance(args[3]);
    char[] pwout = args[5].toCharArray();
    if (pwout.length==0) { pwout = null; }
    ksout.load(in,pwout);
    in.close();
    //--------- Main Loop to get keys/certs from source keystore ------------
    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
    Enumeration en = ksin.aliases();
    while (en.hasMoreElements()) {
    String alias = (String) en.nextElement();
    if (ksout.containsAlias(alias)) {
    System.out.println(args[4] + " already contains " + alias + " Key will not be copied.");
    continue;
    // ------- Ask user if alias of source key/cert should be renamed -----------
    System.out.println("Source alias: " + alias);
    System.out.print("Rename alias to [<return> to keep original alias]: ") ;
    String newuseralias = stdin.readLine().trim() ;
    if (newuseralias.equals("")){
    newuseralias=alias;
    System.out.println("Original alias used") ;
    else {
    System.out.println("New alias: " + newuseralias) ;
    if (ksin.isCertificateEntry(alias)) {
    System.out.println("importing certificate " + alias);
    ksout.setCertificateEntry(newuseralias, ksin.getCertificate(alias));
    if (ksin.isKeyEntry(alias)) {
    System.out.println("importing key " + alias);
    ksout.setKeyEntry(newuseralias, ksin.getKey(alias,pwin), pwout,ksin.getCertificateChain(alias));
    //--------- End main loop ----------------------
    //--------- Overwrite the destination keystore with new keys/certs --------------
    FileOutputStream out = new FileOutputStream(args[4]);
    ksout.store(out,pwout);
    out.close();
    System.out.println("keystore copy successful\n") ;
    System.exit(0);

  • Unable to Export certificates as Personal Information Exchange - PKCS #12 (.PFX) file format.

    We are using Windows 2003 Certificate Authorities, and we are unable to Export certificates as .PFX, our only options are, DER encoded binary X.509 (.CER), Base-64 encoded X.509 (.CER), or Cryptographic Message Syntax Standard - PKCS #7 Certificates (.P7B).  The .PFX option is grayed out in the Certificate Export Wizard on the CA.
    This posses a problem because our Windows 2008 server running IIS 7 wants us to import a certificate as .PFX
    can someone explain what is happening and how to fix it please

    Greg --
    The private key doesn't exist on the CA, but it does exist on the computer on whic you created the request. Here's what happens when you request a certificate.
    If you're generating a request with a new key pair -- which you will in the vast majority of cases -- Windows first generates the public and private key pair. The private key is written to a key store. Where the key store is located will depend on which
    Cryptographic Service Provider (CSP) or Key Storage Provider (KSP) is specified in the template. KSPs were introduced in Windows Server 2008/Vista, and are only available in v3 templates. In the case of most of the default Microsoft CSP/KSPs (with the exception
    of those used with Smart Cards), the key store is located in either the user's profile, or in the case of computer certificates, the All Users profile. It is at this point, by the way, that the properties of that private key are also written to the key store.
    One property of interest to you immediately is whether or not Windows should allow the private key to be exported.
    Once the key pair is generated, the request is then created. The request contains the information that should be in the certificate. This information is generally specified by the template with the exception of the Subject field, which contains the Common
    Name or Distinguished name of whoever is requesting the certificate. In the case of IIS, the Subject will be your site name. The public key is included in the request. Windows then signs the request with the newly created private key.
    Windows also creates a dummy certificate object in the Certificate Enrollment Requests store so that it knows that there is an outstanding request.
    At this point, the request is saved to a file or sent to an online CA depending on how you generated the request. Note that the private key is
    not sent to the CA in most cases. The exception to this rule occurs when you have Key Archival enabled on the CA, and the template specifies that the private key should be archived in the CA database. If this is the case, Windows retrieves
    the CA Exchange certificate from the CA and uses the public key in that certificate to encrypt the newly created private key. This encrypted private key is included in the request.
    Once the CA receives the request, it processes that request to determine if it should issue the certificate or not. In the case of the Enterprise CA, this decision is based on the permissions on the template. One can also specify that certain templates
    require CA manager approval before they can be issued. Assuming that everything is correct in the request, and that the necessary information can be retrieved from Active Directory (perhaps the user's email address, or the computer's DNS host name -- it depends
    on the settings in the template), and that any CA Manager approvals specified in the template have been performed, the CA builds the certificate and signs it with its current private key. The certificate has been created.
    This certificate is stored in the CA database, which is why you can export it in the Certificate Authority snap-in. If the encrypted private key for that certificate has been included in the request to be archived, the CA decrypts it first with its CA Exchange
    private key, and then re-encrypts it using the public key(s) for any Key Recovery Agents configured on the CA. The newly encrypted private key is also stored in the CA database. Note that this encrypted private key can only be retrieved and decrypted
    by a valid KRA.
    The CA then returns the certificate to principal who requested it. If the request was first saved as a file and then submitted to the CA you have to retrieve the certificate manually. It is only returned automatically if you submitted the request via the
    Certificiates MMC, or if the application you use to submit the request retrieves it for you. IIS does this, when you use the certificate request wizard to request a Web Server certificate.
    When the client has received the certificate, it locates the dummy certificate object in the Certificate Enrollment Requests store. From this object, Windows copies the location of the key store for the private key (among other things). This dummy certificate
    object is then deleted, and the new certificate is imported into the Personal store. The private key information is then written to an internal property of the certificate in the store. This is how Windows locates the private key of that certificate in order
    to use it when you invoke the associated certificate.
    When you go to export the certificate and private key, Windows reads the private key locate information from the certificate properties in order to find the key store wherein it is located. Assuming export is allowed, the certificate and private key are written
    to a password protected PFX file.
    That's how a certificate request gets turned into a certificate, and explains why the private key doesn't exist on the CA. If you need to generate a PFX file, then you'll have to export the certificate from the computer on which you generated the request.
    Hope this helps.
    Jonathan Stephens
    Jonathan Stephens

  • How to display and save a picture stored as BLOB in MySQL database in Jsp?

    Hello i am doing a dataentry form where in i will display the picture stored as Blob in MySQL database to the browser. The form also allow changing the picture and updating the picture Blob in the database.
    How can i do it? I try this
    <img src'"<%=rs.getBlob("picture")%> but it doesn't display the picture.
    another thing, how can i save it in the database, if is use the file field in the html form?
    thanks in advance for your help.

    Hello i am doing a dataentry form where in i will display the picture stored as Blob in MySQL database to the browser. The form also allow changing the picture and updating the picture Blob in the database.
    How can i do it? I try this
    <img src'"<%=rs.getBlob("picture")%> but it doesn't display the picture.
    another thing, how can i save it in the database, if is use the file field in the html form?
    thanks in advance for your help.

  • Certificate in .pfx file

    Hello everybody,
    Is someone able to tell me if it is possible to handle Certificate object while the correponding certificate is stored in a .pfx file.
    If it is, can you tell me also if the type of the certificate remains "X.509"?
    Vincent

    You can read pfx files with JCE IAIK.
    jcewww.iaik.at/products/jce/index.php

  • Storing pdf file in sql database

    currently i am working on my last semester project.I am using visual studio 2010 to design front end and sql server 2008 for database. I that case i want to store the pdf file in sql server 2008 databae and want retrieve it back as and when required.is
    it possible to do so please feedback me soon with an answer.

    look,
    http://stackoverflow.com/questions/2347842/storing-pdf-files-as-binary-objects-in-sql-server-yes-or-no
    Please use Marked as Answer if my post solved your problem and use
    Vote As Helpful if a post was useful.

  • E26 253 Error while checking in and storing: \\sapserver\file.tif

    Hi Experts,
    I have now been fighting with this problem for a couple of weeks, and not been able to solve the issue.
    My problem is to upload/check-in documents from the application serve in background.
    I have a program to create DIF and attach files using BAPI_DOCUMENT_CREATE2.
    When I'm running the program in foreground there is no problem.
    When I run it in background I get the error message E26 254 Error while checking in and storing:
    sapserver\file.tif
    I have checked that the background process can see the document on the server and that is OK, so the problem must be within the actual storing of the document in DMS in the BAPI.
    Any input to how I can solve this issue is appreciated.
    Thanks in advance,
    Thomas

    Hi All,
    We have now done some testing.
    We got it to work on one of our systems but not on the other
    I ran report RSCMST on both systems with the same backend directory. (A directory on the application server of the one that fails).
    Running this report I get this result on the system that does not work.
    HTTP interface test using function group SCMS_HTTP
    21.06.2010 14:39:01
    serverInfo:
    contRep                   ZEBAN
    contRepDescription        PR Attachments
    serverStatus              running
    serverVendor              Copyright SAP AG, All rights reserved 1998, 2001
    serverVersion             6300
    serverBuild               193
    serverTime                123902
    serverDate                21.06.2010
    serverStatusDescription
    pVersion                  0046
    contRepStatus             data(89%) log(1%)
    contRepStatusDescription
                                                      ok           58.848
    create(1): new doc (frontend)                     ok          445.211
    create(2): new doc (back end)
    check_subrc: subrc     2  instead          0
    check_subrc: HTTP error: 400 Bad Request
    create(2): new doc (back end)                    error
    docGet/create(1): copy document                   ok          105.684
    info(1): existing doc                             ok           26.881
    update(1): new comp                               ok           47.050
    info(2): after update                             ok           30.458
    delete(1): unknown doc                            ok           33.061
    delete(2): unknown comp                           ok           31.669
    delete(3): existing doc                           ok           53.330
    delete(4): deleted doc                            ok           34.781
    delete(5): existing doc                           ok           31.088
    putCert:                                          ok           35.785
             1  errors
    Any ideas to what could be wrong?
    Thanks in advance.

  • Uploading File To MySQL from HTML form via Servlet

    Hello all !
    I hope this is better place to ask.
    I'm working on simple Servlet/Jsp application trying to hold to MVC pattern and got stuck on uploading file to MySQL db.
    Here's what I'm trying to accomplish:
    1) client submits a JPEG image via a simple html form on a webpage.
    2) JPEG is put into a database table, column field of type BLOB.
    3) Servlet processes the request, gets a connection to the db and inserts the image into the table.
    4) after that user is able to retrieve an image from db and display it in JSP page.
    This is pretty much the same task Angela was trying to do here:
    http://forum.java.sun.com/thread.jspa?threadID=667597&messageID=3905449
    I could use her snippets if i knew what is what and decided to figure out this myself. Aftet some investigation i found out that i need to import org.apache.commons.fileupload.*;which i found here: http://jakarta.apache.org/commons/fileupload/
    what am i driving at ?
    -----------------------1-----------------------
    After first line of code
    boolean isPart = FileUpload.isMultipartContent(request);netBeans 5.5 beta2 with bundled Tomcat 5.5.17 underlines this with warning saying that
    org.apache.commons.fileupload.FileUploadBase
    has been depreceted
    is it a reason for concern ?
    -----------------------2-----------------------
    Is it actually good idea to store images in db as blob ?
    what about large ammounts of text ?
    thank you
    -Dominik

    is it a reason for concern ?Yes.
    You should take a look at the method in the documentation and find out exact reason for depricating it.
    If it is depricated becouse they going to remove it in the future you should use the new alternative method becouse if you use the old method your app will not work in the future releases of the API.
    If it is depricated becouse it is not safe to use the method you should clearly understand the risks involved in using the method and see if that can give you any trouble in your project.
    -----------------------2-----------------------
    Is it actually good idea to store images in db as
    blob ?I think that it is ths best option available when you want to store binary data
    what about large ammounts of text ?You can use clob columns.
    By the way when you store files in the database its better you put some extra columns to store the file name and file type(mime) becouse you cant directly detect those things later by just looking at the data of the file.

  • Storing PDF file into DB & restoring back to Filesystem

    Hi Everybody,
    I need to store PDF files into Database (Oracle 8.1.6 on Windows NT). This I could do using DBMS_LOB Package. Now, my problem is bringing back the PDF files to OS filesystem.
    I feel my problem will be solved if I have UTL_LOB Package Object in my Database. Where can I get the script or utility that installs the said Object in my Database. Kindly send me the script/utility if anybody has.
    Thanks & Regards,
    Durai.

    look,
    http://stackoverflow.com/questions/2347842/storing-pdf-files-as-binary-objects-in-sql-server-yes-or-no
    Please use Marked as Answer if my post solved your problem and use
    Vote As Helpful if a post was useful.

  • Stored PDF files with Blob

    I have being storing PDF files using Blob, but it is getting very time consuming to access these files again.
    Is there a better way of doing it? Is there a right way of doing it? I do not need to search inside the PDF, but I do need to access them either inside the Database or outside.
    Thank You for nay help

    I have a need to store PDF files that are documents that will complement process that my systems creates. And I need that those PDF files be accessible from inside my system, I do not need to search insede them because they will be stored by subject inside another subject, therefore whoever need the files will know were to find it, but to store and to access it is taking longer and longer as more files are added to the first thead.

  • How to Upload/Attachment File  in MYSQL    ADF???

    HEY Guys...
    How to Upload/Attachment File in MYSQL ADF???
    Regards Ninja,

    You need to provide more information.
    Which jdev version do you use?
    Which ui technology?
    I see two question to be answered:
    1) load the attatchments ADFrc af:inputFile (http://technology.amis.nl/blog/2297/adf-faces-file-uploading-it-is-really-that-simple)
    2) store the loaded data in the DB -> mysql doc or google should have the needed information
    Timo

  • How to add a locally stored video file to a presentation

    Hi all ,
    I want to add a locally stored video file to a presentation .What is the url that i need to use..
    Ur help is much appreciated
    Thanks

    The recommended procedure is to create the presentation on the DMM (upload the video to the DMM) then create a deployment package using the presentation created on the DMM. Once you deploy it to the DMP, the DMM will FTP the video along with presentation files to the DMP which will contain the links to play the video that will be stored locally on the DMP.
    You may want to review the following thread to see how to trigger the local presentation to play and how to update it later:
    https://supportforums.cisco.com/message/3289668
    Regards,
    Fabio Bergamo
    Cisco TAC

  • How to convert a PFX file into mobileconfig format?

    Hi,
    I'm trying to automate the task of creating a mobileconfig file with a client certificate in it.
    I understand that this is some kind of base64 encoding, but I don't get what they're encoding.
    My PFX files are protected with a password (Although I tried to create a PFX without the password, and the base64 version of it differs from the .mobileconfig from iPCU version of it).
    I already saw Alginald99 tip in: https://discussions.apple.com/message/15080631
    That tip didn't work for me. When I convert my PFX file to base64, the encoded string is nothing like the string in the .mobileconfig I created by iPCU.
    Alginald99 - If you're still hang here - please help!
    Thanks,
    Bar.

    Yes, the key container GUID and the cert container GUID are different. That's normal.
    You can reproduce this:
    Delete the cert in windows mmc/certificate console, reimport the same cert in mmc/certificate and import this cert in iPCU. You can see the difference in mobileconfig.
    Catch only the cert part from mobileconfig and dump it with <certutil.exe -v user.enc>. You see different container GUIDs.
    I hope this helps.

  • Storing .jsp files in the web-inf directory

    Has anyone ever heard about storing JSP files in the web-inf directory instead of the web app root directory.
    Apparently it improves security.
    If this is so, how is the user suppose to access the jsp file since I thought that users were not able to access what is stored in the web-inf directory.
    Any thoughts
    Thanks
    Nat

    I didn't tyr this but I think it is possible. You can do it using <servlet-mapping/> as you do with any other servlet.
    For example include lines below, in web.xml of web-inf,
    <servlet>
    <servlet-name>ReportRouter</servlet-name>
    <jsp-file>/web-inf/jsp/ReportRouter.jsp</jsp-file>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>ReportRouter</servlet-name>
    <url-pattern>/myrouter</url-pattern>
    </servlet-mapping>
    This may work. Don't you think so?
    Sudha

Maybe you are looking for

  • Adding scientific notation

    How do I write in Scientific notation, with numbers in subscripts below element letters?

  • GUI sending data to C program

    Hi I am pretty comfortable making a Swing GUI...but i was told today by my mentor that he wants the data ( that user puts in Text fields and etc) to be sent to a c program. so JAVA GUI is just there for the user...all the back ground work is done by

  • Problem wih MobileMe Login

    Hi, Just upgraded to Snow Leopard and after reboot, have been facing issues with MobileMe. 1. Firstly, a pop up window kept appearing saying that I've entered an invalid MobileMe member name or password, for i'm very sure it's correct. 2. Then, when

  • User Account problem

    I have just installed Filemaker Server on my Mac OSX Mountain Lion and it says that it created a User Account called 'fmserver User'. Opening Workgroup Manager I can see the user account, but going to System Preferences > Users and Groups, it is not

  • Ibook remote vga monitors switching off after 30 seconds. (EMERGENCY)

    Hi, I run teleprompter for a major band. I use two white dual usb ibooks as they will run OS9. The only real pro prompter application for the mac never made it successfully to os X (accuprompt). I use two mini VGA to VGA adapters and run 100 ft of VG