Streaming out de-encrypted data

Hi,
I have 2 classes "parsing.java" and "enc.java". "parsing.java" parses an xml file "INFO.xml", to get a few attribute values. I'm using SAX parsing.
However, "INFO.xml" is encrypted (password based encryption), and needs to be de-encrypted before it can be parsed. So "parsing.java" calls "enc.java" which de-encrypts the xml file, and creates the "readable xml file" say "rINFO.xml". Then the program reads the xml file.
parsing.java
String passphrase = "123456789";
String oFile = "C:\\rINFO.xml";
String iFile = "C:\\INFO.xml";
enc f = new enc();f.decFile(iFile,oFile,passphrase);  //starts parsing reader.parse(oFile);....enc.java
public class enc
     public void decFile(String inputFile, String outputFile, String  passphrase)   
     InputStream in = new FileInputStream(inputFile);       
OutputStream out = new FileOutputStream(outputFile);      
byte[] inBytes = new byte[blockSize];       
byte[] outBytes = new byte[outputSize];     
while(more)      
{            inLength = in.read(inBytes);                      
if(inLength == blockSize)           
int outLength = cipher.update(inBytes, 0, blockSize,  outBytes);                out.write(outBytes, 0, outLength);           
else              
more = false;       
............. You should have noticed that I'm creating a new file "rINFO.xml" and sending the de-encrypted data to that file. However, I would like to stream out the de-encrypted contents using output stream to "parsing.java", and do not want to save it as a file, because the whole purpose of encryption is lost otherwise.
1)Is there a way of having the de-encrytped xml file in memory and then parsing that ?
2) or streaming the de-encrypted contents to "parsing.java", where I can use
reader.parse(new InputSource(new InputStreamReader (inStream)));
instead of
reader.parse(oFile);
any help appreciated .
-Sara

Have you looked at the Cipher stream classes?
http://java.sun.com/j2se/1.4.2/docs/api/javax/crypto/CipherInputStream.html
http://java.sun.com/j2se/1.4.2/docs/api/javax/crypto/CipherOutputStream.html

Similar Messages

  • Problem when streaming out a binary file

    Hi,
    I am trying to stream out a binary file to an output stream (not a file, but a socket). My file is a gzip file, and I was initially simply trying to open the
    file, read it to a a byte array, and writing it out to my output stream. However, I got corrupted data at my other end and it took me quite a bit of
    debugging hours to find out why.
    I tried writing to a file the same information I was writing to my output stream but, although my file was correct, my output stream still contained
    corrupted data.
    I think I have finally narrowed down my problem to the fact that when I try to write a 0x00 value to my output stream, everything gets ignored from this
    point until I write a 0x0a byte to my output stream. Obviously this produces corrupted data, since I need all the bytes of my binary file.
    If somebody can direct me as to how to write a 0x00 value to a socket output stream, I would really appreciate your input.
    This is a sample of my code (Right now I am writing byte by byte: not very efficient, but was the only way I found where I was getting a problem):
    // out is of type OutputStream
    if (Zipped){
         // In this case we just have to stream the file out
    File myFile = new File(fileName);
         FileInputStream inputFile = new FileInputStream(myFile);
         FileOutputStream fos = new FileOutputStream(new File("/tmp/zip.gz")); //zip.gz results in a good (not corrupted) file.
         ByteArrayOutputStream out1 = new ByteArrayOutputStream(1024);
         int bytes = (int)myFile.length();
         byte[] buffer = new byte[bytes];
         bytes = inputFile.read(buffer);
         while (bytes != -1) {
              out1.write(buffer,0,bytes);
              bytes = inputFile.read(buffer);
         inputFile.close();
         try {
              int count=0;
              bytes=out1.size();
              while (count<bytes){
                   fos.write(buffer,count,1);
    out.write(buffer,count,1); // when buffer[count] == 0x00, everything after it gets ignored until a 0x0a byte is written.
                   count++;
         } catch (IOException ioe) {
              SysLog.event("IOEXCEPTION: "+ioe);
         } catch (Exception e) {
              SysLog.event("EXCEPTION: "+e);
         fos.flush();
         fos.close();
         out.flush();
    out.close();
         return;
    }

    Actually, I had thought about that and for some time I tried getting rid of some of the header information in the gzipped file, and then I stopped doing that when I realized that part of the gzipped file is a CRC value which I believe is computed taking into account both the data of the file and the header information. If this is the case, then getting rid of part of the header would produce a corrupted file ... but then, I might be wrong in this issue.
    Anyway, to make my application more clear, what I am doing is writing the code for a cgi command which is suppossed to access information from a database, create an xml file, gzip it, and then send it to the client who requested the information.
    Therefore, what I am sending is an xml file (Content-Type: text/xml) in compressed format (Content-Encoding: gzip). Note that if I don't gzip the file and then send it uncompressed to the client, I have no problems. However, for me it is very important to gzip it because the size of the file can get very large and that would just take bandwidth unnecessarily.
    On the other hand, if I try to gunzip the file locally, I have no problem either (the file is not corrupt at the server's end). Therefore, my problem is when I stream it out.
    Any further help would be really appreciated!

  • How to handle HTTP-POST encrypted data for ECC Using proxy or RFC

    I have a scenario HTTP-POST ->PI->ECC.sender is HTTP Post  send encrypted data i need to handle the data and stored in to SAP ECC  with out decrypt using PI .what should i take for receiver  can i use inbound proxy or RFC  and how can handle the encrypted data  for decrypt.
    Regards
    Ravi

    1. my sender is HTTP POST . what should i configure in sender communication channel in SAP PI .like SOAP or HTTP .What are the parameters i need to pass .
    >>>
    If you are on PI 7.3 and above, configure the HTTP AAE adapter - Configuring the Java HTTP Adapter on the Sender Channel - Advanced Adapter Engine - SAP Library
    2.while using inbound proxy for encrypted data  i need  store the data in to table , the same proxy can i call  another outbound  service for decrypt  same data.
    >>>>
    Yes you can always a proxy within a proxy.

  • Insert an encrypt data in a Table

    Hi all,
    i have encrypted a data with HmacMD5, all its fine. but when i've tried to insert encrypt data in my table, hash code may return symbols like �?��Z��x��. then when i do a select data has been corrupted. how can i encrypted in stardand symbols( like mysql passwords). here is my code:
                KeyGenerator kg = KeyGenerator.getInstance("HmacMD5");
                SecretKey sk = kg.generateKey();
                // Get instance of Mac object implementing HMAC-MD5, and
                // initialize it with the above secret key
                Mac mac = Mac.getInstance("HmacMD5");
                mac.init(sk);
                byte[] result = mac.doFinal(dirMAC.getBytes());
                String macenc=new String(result);
                String x = "jdbc:mysql://localhost/"+
                        "mydatabase?user="+user+"&password="+
                        pass;
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                conn = DriverManager.getConnection(x);
                conn.createStatement().executeUpdate("insert into user " +
                        "(User,Password) values('system','"+myPass+"')");
                java.sql.ResultSet rs=conn.createStatement().executeQuery("select password "+
                         "from " +"user where user ='system' ");
                rs.next();
                if((rs.getString(1).equals(macenc))) {
                    System.out.println(rs.getString(1)+" YES "+macenc);
                } else {
                    System.out.println(rs.getString(1)+" NO "+macenc);
                }Output NO. and sometimes when hash has (') character Query not found.
    thanks.

    Thie is most probably the offending line
    String macenc=new String(result);
    It is never a good idea to try to convert arbitrary bytes into a String using this approach. Not all byte sequences have valid char representation. If you must have a String representation use Base64 or Hex encoding of your Hmac. Google for Jakarta Commons Codec to get a library to assist you with this.

  • Will this encrypt data securely?

    Hey I'm using bouncy castle AES password based encryption. I was just wondering if anyone would take a quick look at my code below to see if it will encrypt a string securely, or if I've missed anything out?
    Thanks in advance
    import java.io.File;
    import java.security.Security;
    import java.util.Vector;
    import javax.crypto.Cipher;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    import javax.swing.JOptionPane;
    import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator;
    import org.bouncycastle.crypto.params.KeyParameter;
    import org.bouncycastle.crypto.params.ParametersWithIV;
    import org.bouncycastle.util.encoders.Base64;
    public class encryptor {
         private final byte[] salt = { (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c,
                   (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99,
                   (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c,
                   (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 };
         public static void main(String[] args)
              new encryptor();
         public encryptor()
              char[] password = "aRandomPassword".toCharArray();
              SecretKeySpec key = generateKey(password, salt);
              encrypt(salt, key, "A secret message");
         public SecretKeySpec generateKey(char[] charPassword, byte[] salt)
              byte[] bytePassword;
              PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator();
              Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
              int count = 16;
              try
                   bytePassword = new String(charPassword).getBytes("ASCII");
                   generator.init(bytePassword, salt, count);
                   ParametersWithIV params = (ParametersWithIV) generator.generateDerivedParameters(128, 128);
                   KeyParameter keyParam = (KeyParameter) params.getParameters();
                   return new SecretKeySpec(keyParam.getKey(), "AES");
              catch(Exception e)
                   System.out.println(e);
                   System.exit(1);
              //This will never occur
              return null;
         public void encrypt(byte[] salt, SecretKeySpec key, String text)
              IvParameterSpec iv = new IvParameterSpec(salt);
              Cipher cipher;
              byte[] temp;
              try
                   cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
                   cipher.init(Cipher.ENCRYPT_MODE, key, iv);
                   temp = cipher.doFinal(text.getBytes("ASCII"));
                   System.out.println(new String(Base64.encode(temp), "ASCII"));
              catch(Exception e)
                   System.out.println(e);
    }

    I'm no expert in cryptology but you are using the salt byte array in two places, as salt and as the initialization vector. This strikes me as a big "no-no"; I suspect it could weaken your cipher. Even if I had no evidence of such weakening, I'd avoid that if at all possible.
    You should generate separate salt and initialization vectors; in fact, you should generate them randomly each time you encrypt something. Naturally, you'll have to carry them along with the encrypted data so that you can pass them back in to the decryption process, but that's a small part to pay for not opening yourself up to dictionary attacks.
    Also, you might want to apply the salt more than just 16 times; try something much larger, such as 1024.

  • Encrypt data send from a non-SAP system to ECC.

    Hi,
    We are tryign to encrypt the credit card details send from web (non-sap system) via a xml file to ECC.
    From Basis side, I have exported the public key from the ECC for the web server to encrypt the CC details while sending via xml.
    The external web consultants encrypted the cc detail with the public key and send it via xml but that was not able to decrypt at the ECC side.
    The developers were using the FM 'CCARD_DEVELOPE'at ECC to decrypt the data in the xml file. It was saying SSF error: No data transfered.
    Meanwhile SAP CryptoLib is installed and credit card encryption/decryption is working fine for CC details entered via GUI interface.
    Is there anything I am missing out here to encrypt CC details send from a Non-SAP system to ECC.? Do we need to load the SAP cryptolib in the non-SAP system to ecrypt this data at the senders end. Or is there a alternate solution for this ?
    We are in ECC6.0/RHEL/Oracle10204.
    Appreciate your help.
    Thanks

    Hi Nelis,
    Thanks for your reply.
    This note does not get any information regarding encrypting data from a non-SAP system to SAp system.
    I am looking setup/information for encrypting data from a non-SAP system to SAP system.
    Thanks

  • Encrypt data on Time Capsule

    I know you can encrypt data on the hard disk of the Mac with FileVault but how can the data be backuped encrypted on the Time Capsule, too? Will the data be encrypted automatically if they are on the hard disk they come from?

    That's a great question. This concern is the reason I held back buying one.
    While it's great to back-up data, how does one encrypt the content of the TC? One reason to want this is if the TC is stolen for instance. The data on there should be encrypted.
    Glad to read it's as simple as turning on File Vault (which I did on my laptops) in Mac OS X.
    However I am reading on another thread that Time Machine won't let you back-up the encrypted user folder:
    +Time Machine backs up home folders protected by FileVault only when logged out. You cannot browse items of the protected home folder in the Time Machine backup. Because you cannot browse the items in the Time Machine backup, you cannot restore individual items.+
    So what's one to do?

  • B2B - SFTP - Encrypt data using PGP

    Hello,
    I am hearing / reading mixed comments on using PGP encryption / decryption using the SFTP Transport in Oracle B2B.
    The requirement is the data needs to be encrypted during the transport between the trading partners. The SFTP server houses the PGP encrypted data, B2B should be able to listen, pick and decrypt and process the files.
    Is this possible in Oracle SOA Suite 11g? If yes, could you please point me to any documentation that explains configuring B2B to decrypt a PGP encrypted file.
    Thanks in advance,
    Venkatesh

    I think most comments you read about this would have said that B2B SFTP cannot handle PGP encryption. This is true. B2B out-of-box does not support PGP encryption/decription. Most people suggest using Java callout.
    ~Ismail.

  • Way to find out old Encryption Key

    Hey everyone,
    Is there a way to find out the old Encryption Key?  I just recently upgraded an old 5.9 database to WT6 PL10.  I am getting the Padding error, however I used the same Private Key from the old database and matched the Installer to it.  Is there a way to find out the old private key?  Not sure how it changed...  If I can't figure out the old key, what do I have to do to get the old database online to match the Keys?  Any thoughts would be greatly appreciated.
    Thanks,
    Kristen

    The private key is used to create a one-way hash and therefore cannot be discovered by any sort of reverse engineering. Web tools uses RM PKI encryption which is specifically built to disallow such operations.
    1) Try recreating the hash by opening the Installer in tasks mode(Installer -tasks from command line)
    2) If this doesnt do the trick, re-initialize the synch and clear out only the data that synchs, which does not include themes or catalogs, but be ready for the subsequent sync to take a minute or so, ok more like an hour or more
    3) Don't forget to recreate the web.config file(installer -tasks again) if you change the private key. In fact you may wish to do this now, just to be sure it has the right one, and the updated version of it, since this is an upgrade from 5.9(.Net 1.1)

  • How to insert encrypted data by using blowfish into mysql database

    Hi
    I have encrypted data using blowfish algorithm . And i tried to insert that encrypted data into mysql. it was stored but i dont know that it stores in the same encrypted formate
    When i am trying to get the encrypted data from the mysql database and decrypting that data i am getting errors.
    Exception are like
    input length should be multiple of 8 bits
    or Given block are not properly padded
    and when i am displaying the data using system.out.println ();
    the string is not similar to the string which is in database.
    what is the problem how can i solve my problem
    thank you

    It sounds like your column is a VARCHAR so you need to Base64 or Hex encode the cipertext bytes before putting them in the database.

  • Encrypting data on card

    Hello, I was hoping somebody would be able to explain some queries I have regarding encryption. I have been attempting to encrypt data in my card but I have been unable to find enough documentation to cover the topic thoroughly. What I have done is;
    Declare my variables:
    protected byte[] KeyData;
    protected Key des_key;
    protected Cipher cipher;
    I have then initialised them in my constructor prior to a call to the register method, as follows:
    // Create DES key
    DESKey des_key = (DESKey)KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES, false);
    // Initialise DES key
    KeyData = new byte[]{(byte)1};
    des_key.setKey(KeyData, (short)0);
    // Create Cipher object with the DES algorithm
    cipher = Cipher.getInstance(Cipher.ALG_DES_CBC_NOPAD, false);
    // Initialise with DES key for encryption
    cipher.init(des_key, Cipher.MODE_ENCRYPT);
    register();
    In one of my methods, I then attempt to encrypt data contained in the byte array 'temp':
    // Encrypt data and write into jcname array
    cipher.doFinal(temp, Offset, len, jcname, Offset);
    When I have tested this in jcwde the create method fails with the sw()6444.
    I'm afraid I don't understand how the Key is created or what should be contained within the KeyData array, this may be where my problem is arising. If you can help or provide some explanation of what is happening I would be very grateful. TIA
    Tony

    The error code you are getting is because the crypto isn't implemented. The crypto is hardcoded to return that. If you peek at the code, you'll see that none of the cyrpto packages are implemented.
    So you have to write them yourself or find an implementation somewhere.
    When you buy a kit from a vendor, the cards will contain some form of crypto ( DES, 3DES, RSA) and you can fully test it out that way.

  • Most simple query on Event Hub stream (json) constantly gives Data Conversion Errors

    Hello all,
    Been playing with ASA in December and didn't have any issues, my queries kept working and outputted the data as needed.  However, since January, I created a new demo, where I now constantly get Data Conversion errors.  The scenario is described
    below, but I have the following questions:
    Where can I get detailed information on the data conversion errors?  I don't get any point now (not in the operation logs and not in the table storage of my diagnostic storage account)
    What could be wrong in my scenario and could be causing these issues
    The scenario I have implemented is the following:
    My local devices send EventData objects, serialized through Json.Net to an Event Hub with 32 partitions.
    I define my query input as Event Hub Stream and define the data as json/utf8.  I give it the name TelemetryReadings
    Then I write my query as SELECT * FROM TelemetryReadings
    In the output, I create an output on blob with CSV/UTF8 encoding
    After that, I start the job
    The result is an empty blob container (no output written) and tons of data conversion errors in the monitoring graph.  What should I do to get this solved?
    Thanks
    Sam Vanhoutte - CTO Codit - VTS-P BizTalk - Windows Azure Integration: www.integrationcloud.eu

    So, apparently the issue was related to the incoming objects, I had.  I was sending unsupported data types (boolean and Dictionary).  I changed my code to remove these from the json and that worked out well.  There was a change that got deployed
    that (instead of marking the unsupported fields as null, they were throwing an exception).  That's why things worked earlier.
    So, it had to do with the limitation that I mentioned in my earlier comment:
    https://github.com/Azure/azure-content/blob/master/articles/stream-analytics-limitations.md
    Unsupported type conversions result in NULL values
    Any event vales with type conversions not supported in the Data Types section of Azure Stream Analytics Query Language
    Reference will result in a NULL value. In this preview release no error logging is in place for these conversion exceptions.
    I am creating a blog post on this one
    Sam Vanhoutte - CTO Codit - VTS-P BizTalk - Windows Azure Integration: www.integrationcloud.eu

  • Stream in stream out

    can anyone give me a short example how to read a stream in(not from a file.. just a simple datastream from USB) and how to write a stream out from that..thx

    ok.. i managed to detect the USBs.
    http://www-106.ibm.com/developerworks/java/library/j-usb/
    import usb.core.*;
    public class ListUSB
    public static void main(String[] args)
    try
    // Bootstrap by getting the USB Host from the HostFactory.
    Host host = HostFactory.getHost();
    // Obtain a list of the USB buses available on the Host.
    Bus[] bus = host.getBusses();
    int total_bus = bus.length;
    // Traverse through all the USB buses.
    for (int i=0; i<total_bus; i++)
    // Access the root hub on the USB bus and obtain the
    // number of USB ports available on the root hub.
    Device root = bus.getRootHub();
    int total_port = root.getNumPorts();
    // Traverse through all the USB ports available on the
    // root hub. It should be mentioned that the numbering
    // starts from 1, not 0.
    for (int j=1; j<=total_port; j++)
    // Obtain the Device connected to the port.
    Device device = root.getChild(j);
    if (device != null)
    // USB device available, do something here.
    // Obtain the current Configuration of the device and the number of
    // Interfaces available under the current Configuration.
    Configuration config = device.getConfiguration();
    int total_interface = config.getNumInterfaces();
    // Traverse through the Interfaces
    for (int k=0; k<total_interface; k++)
    // Access the currently Interface and obtain the number of
    // endpoints available on the Interface.
    Interface itf = config.getInterface(k, 0);
    int total_ep = itf.getNumEndpoints();
    // Traverse through all the endpoints.
    for (int l=0; l<total_ep; l++)
    // Access the endpoint, and obtain its I/O type.
    Endpoint ep = itf.getEndpoint(l);
    String io_type = ep.getType();
    boolean input = ep.isInput();
    // If the endpoint is an input endpoint, obtain its
    // InputStream and read in data.
    if (input)
    InputStream in;
    in = ep.getInputStream(); <--------------------- here i have the problem... it simply returns "null"
    // Read in data here
    in.close();
    // If the Endpoint is and output Endpoint, obtain its
    // OutputStream and write out data.
    else
    OutputStream out;
    out = ep.getOutputStream();
    // Write out data here.
    out.close();
    } catch (Exception e)
    System.out.println(e.getMessage());
    look the code above.. it really works very well.. it detects that i have an input device on an USB(in fact i just have plugged my mouse there).
    so here is my question: i want to put there a video cam who send data streams. so does
    in = ep.getInputStream();
    get the whole stream? or do i have to write there somewhere a while boucle to read it well...
    and is
    InputStream in;
    appropriate for that?
    (sorry at the moment i can't do any test with a cam because i dont have it here)

  • Keychain, private encrypted data

    I had to reset my Adobe password, and chose the auto password suggestion that popped up, and said yes to saving it in my keychain. It is now saved there and will auto fill when I need it, but I also want to open it in keychain to see what the password actually is. When I go to keychain, the new password is there in "private encrypted data" and it asks for a password to open the keychain window that shows the password.
    Trouble is, i don't know what the password is; I didn't set one for it, and my keychain ones don't work. How do I find out what the password is to open the keychain file to find out what my Adobe password is..?
    Thanks

    If the prompt looks like this
    Then it wants your Mac OS X Admin password, unless you have given your keychain a different unique password (something you would have had to manually do, and hopefully you would remember if you did).

  • Encrypting data for testing - but keeping it legible and the right length

    Hello,
    I currently work with a client where one of our final stages of testing is done against test databases (9.2), maintained by the client, but holding real data, taken as a snapshot. This gives us volumes of data similar to what will be encountered in production.
    The client now has a (valid) concern that our people testing the app therefore get to see 'real', if slightly out-of-date, data, particularly names and addresses, and have asked us if there's some way of hiding this from the testers, who have access to the test db both through a front-end mainly built on Oracle Forms, but also e.g. querying directly with SQL Plus.
    I can't just give all the parties stored in the system the same name or address, so what I think I'd like to do is to replace the sensitive data with encrypted versions, possibly using the DBMS_OBFUSCATION_TOOLKIT. A problem with that, though, is that the encrypted data could contain any characters and may cause problems displaying in the front-end, certainly where testers have to e.g. type in a name to search on.
    I could use rawtohex to convert the data into an easily read / typed format, but then the results could be too long for the existing columns and the fields in the front-ends.
    Has anyone encountered a similar problem and come up with a solution?
    Thanks in advance,
    James

    There are a variety of tools out there sold by companies to automate this sort of thing.
    One relatively common, and relatively simple, approach would be to run a process that mixes and matches data from different records. That is, you take the first name from record 1, the last name from record 2, address from record 3... Of course, you'd have to figure out how sophisticated a jumbling algorithm you need depending on how sensitive the data and how performant an algorithm you need depending on data volumes.
    Relatively efficient, but relatively simple to reverse, would be to use something like this to populate the tables
    insert into emp( ename, sal, comm )
    select ename,
          lag(sal) over( order by empno ),
          lag(comm,2) over (order by empno )
      from emp@prod_db_linkJustin

Maybe you are looking for

  • Computer is no longer authorized for apps installed on your iPhone

    Does anyone else get a message that your computer is no longer authorized for apps installed on your iPhone?  When I click "authorize" I get a message that "This computer is already authorized".  But when I click ok, I get the first message again . .

  • NOT funny, Adobe. Paid but CC's still trial

    Hi all, This is crazy, ridiculous and maddening. I've got loads of work to do, but instead I have to keep on "playing" this CC membership game - for another week now. PROBLEM: I paid for a membership, it's showing on my account fine, but I keep getti

  • BDC_INSERT, screen .&. is invalid

    Hi All, My BDC was working fine yesterday. When I execute today it is giving me the following error. What is this error and how to solve it. Thanks Veni.

  • How to open folders in hot mail on i phone

    how to open folders in hotmail with i phone

  • Internet browser problems

    Hi I have recently noticed that when I go to my internet browser bar it will start to load but then stops and I have to shut the page down and start again, as anyone else experienced similar problems?