Leading garbage characters when using CipherInputStream

So, after receiving an encrypted message, I can decrypt it perfectly except that I get a random amount of leading garbabe characters. Using the same plaintext, here are examples of the beginning of the output file for two runs (using od -c to look at the files):
0000000 315 7 004 371 242 \0 w ` t h e L L S E
and
0000000 1 " 246 317 0 j 321 V t h e L L S E
The part beginning with "The LLSE..." is correct.
The fact that the leading garbage appears to be random leads me to believe that there is something wrong with the crypto rather with the file I/O.
Here's the relevant code chunk:
Cipher sharedCypher = Cipher.getInstance("DES/CFB8/PKCS5Padding");
SecretKeySpec DESKeySpec = new SecretKeySpec(clientDESKey.getEncoded(), "DES");
IvParameterSpec iv = new IvParameterSpec(clientDESKey.getEncoded());
sharedCypher.init(Cipher.DECRYPT_MODE, DESKeySpec, iv);
CipherInputStream cis = new CipherInputStream(new FileInputStream(WD), sharedCypher);     
String time = ""+System.currentTimeMillis();
File outputFileW = new File("/tmp/new_wireless_data."+time);
System.out.println(System.currentTimeMillis()+": Output file is" + outputFileW.getAbsolutePath());
outputFileW.createNewFile();
FileOutputStream fos = new FileOutputStream(outputFileW);
byte[] putCypherBytes = new byte[8];
int i=0;
while((i=cis.read(putCypherBytes)) !=  -1) {
   fos.write(putCypherBytes, 0, i);
}Any thoughts on cleaning this up would be greatly appreciated.
Best,
Glenn

Well, I seriously doubt its the JDK or JCE. I dont have time right now to
download that exact version and test it, but instead I'll give you the code
I pieced together from your posts. Put your text to be encrypted in a file
called plaintext.txt in the directory you run the class in. The decrypted
text should be appear in new_wireless_data...
If you can run this without error, then your problem most likely lies
on your server-side.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
public class CryptoTest {
    public static String encryptedFile = "encrypted.txt";
    public static String plainTextFile = "plaintext.txt";
    public static SecretKey clientDESKey;
    public static String keyString = "emePXfjmLNw=";
    public static void main(String [] args) {
        try {
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] keyBytes = base64Decoder.decodeBuffer(keyString);
            clientDESKey = new SecretKeySpec(keyBytes, "DES");
            _main(args);
        } catch (Exception e) {
            System.out.println("ERROR! : " + e.getMessage());
            e.printStackTrace();
    public static void _main(String [] args) throws Exception {
        Cipher serverCypher = Cipher.getInstance("DES/CFB8/PKCS5Padding");
        serverCypher.init(Cipher.ENCRYPT_MODE, clientDESKey,
            new IvParameterSpec(clientDESKey.getEncoded()));
        File inputFileW = new File(plainTextFile);        
        CipherInputStream cis1 =
            new CipherInputStream(
                new FileInputStream(inputFileW),serverCypher);               
        File outputFileW1 = new File(encryptedFile);
        FileOutputStream fos1 = new FileOutputStream(outputFileW1);
        byte[] putCypherBytes1 = new byte[8];
        int i1=0;
        while((i1=cis1.read(putCypherBytes1)) !=  -1) {
           fos1.write(putCypherBytes1, 0, i1);
        inputFileW.delete();
        //=========================================================
        Cipher sharedCypher = Cipher.getInstance("DES/CFB8/PKCS5Padding");
        SecretKeySpec DESKeySpec = new SecretKeySpec(clientDESKey.getEncoded(), "DES");
        IvParameterSpec iv = new IvParameterSpec(clientDESKey.getEncoded());
        sharedCypher.init(Cipher.DECRYPT_MODE, DESKeySpec, iv);
        CipherInputStream cis = new CipherInputStream(new FileInputStream(encryptedFile), sharedCypher);     
        String time = ""+System.currentTimeMillis();
        File outputFileW = new File("new_wireless_data."+time);
        System.out.println(System.currentTimeMillis()+": Output file is" + outputFileW.getAbsolutePath());
        outputFileW.createNewFile();
        FileOutputStream fos = new FileOutputStream(outputFileW);
        byte[] putCypherBytes = new byte[8];
        int i=0;
        while((i=cis.read(putCypherBytes)) !=  -1) {
           fos.write(putCypherBytes, 0, i);
}

Similar Messages

  • Garbage characters when using CR XI R1 with Sharp M350 printer PCL5e driver

    My application uses CR XI R1. We have a customer who has a Sharp M350 printer. When printing or previewing a report from my application with this printer set as the default, the text is garbled - the characters look like gibberish.
    If they change the default printer to another printer, it works fine. but they need to be able to print to the Sharp printer so I need to find a solution to the problem.
    Changing the printer driver to a PCL6 has no effect. Does anyone have any suggestions for fixing this?

    A few questions:
    1) What development language are you using?
    2) Have you ever applied any CR Service Packs?
    3) Have you checked for any updated for the Sharp M350 printer driver?
    4) Can you duplicate the issue on your development system?
    5) Are you able to print correctly to that printer using the CR designer? (even if you have to as a test, install it on one of the client machines?)
    6) What Crystal Reports SDK are you using? RDC? If so, what is the CR dlls referenced in your app?
    Ludek

  • [svn:bz-trunk] 20505: Bug: Watson #2818669 - AbstractAmfInput uses System. getProperty in Constructor leading to AccessControlException when using in Applet

    Revision: 20505
    Revision: 20505
    Author:   [email protected]
    Date:     2011-03-01 07:31:55 -0800 (Tue, 01 Mar 2011)
    Log Message:
    Bug: Watson #2818669 - AbstractAmfInput uses System.getProperty in Constructor leading to AccessControlException when using in Applet
    QA: Yes
    Doc: No
    Checkintests: Didn't run - the change was to wrap the System.getProperty in a try/catch that would have caused the SecurityException, so no real functionality change that could affect the check-in tests.
    Modified Paths:
        blazeds/trunk/modules/core/src/flex/messaging/io/amf/AbstractAmfInput.java

  • Is there any way to forse user to put at least 5 characters when using LOV?

    Hi gurus,
    I have a question.
    Is there any way to force user to put at least 5 characters when using LOV?
    I want user to put at least 4 characters before/when using LOV.
    Is there any way to do that?
    Thank you for your answers.
    Nerijus

    Hello,
    i've tested it both on 6i and 10g and also set the lov name at runtime.
    All i can say is, it does what it is supposed to do.
    So you should give it one more try:
    - leave the item properties NULL ( LOV name ) and NO ( Validate_From_List )
    - add following code in the WVI - Trigger
    IF :AUFTRAG_NEU.PN IS NOT NULL AND LENGTH ( :AUFTRAG_NEU.PN ) < 5 THEN
      Show_Message ( 'Bitte 5 Zeichen eingeben' );
      RAISE FORM_TRIGGER_FAILURE;
    ELSIF :AUFTRAG_NEU.PN IS NULL THEN
      NULL;
    ELSE
      SET_ITEM_PROPERTY ( 'AUFTRAG_NEU.PN', LOV_NAME, 'LOV_PN_PROJEKT' );
      SET_ITEM_PROPERTY ( 'AUFTRAG_NEU.PN', VALIDATE_FROM_LIST, PROPERTY_TRUE );
      IF SHOW_LOV THEN
        NULL;
      END IF;
      SET_ITEM_PROPERTY ( 'AUFTRAG_NEU.PN', VALIDATE_FROM_LIST, PROPERTY_FALSE );
      SET_ITEM_PROPERTY ( 'AUFTRAG_NEU.PN', LOV_NAME, '' );By the way, what exactly doesn't work?
    Bernd

  • Multibyte character was garbage characters, when multipart requested (Multipartリクエストで文字化けが発生する) on WebLogic12(12.1.2.0)

    When using File Upload functionality of Servlet3 specification, other item's value(<input type="text">) was garbage characters.
    Need special settings?
    WebLgic12c(12.1.2.0)のファイルアップロード機能(Servlet3仕様の機能)にて、アップロードファイル以外の項目の値が文字化けしました。
    これは、何か設定が必要なのでしょうか?
    【Note】
    When normal request(application/x-www-form-urlencoded), submitted value is not garbage characters.
    Filename & File content of uploaded file is not garbage characters.
    I confirmed by debugger that stored value in temporary file is not garbage characters.
    HttpServletRequest#setCharacterEncoding("UTF-8") is used.
    enctype="multipart/form-data"を指定しないリクエストでは文字化けは発生していません。
    アップロードしたファイルのファイル名及びアップロードファイルの中身自体は文字化けしていない。
    アップロード時に出力される一時ファイルの中身をデバッグ実行して確認したところ、この段階では文字化けしていなかった。
    HttpServletRequest#setCharacterEncoding("UTF-8")も実行しています。
    【Environment Information】
    OS : MacOS X 10.8.5
    JVM : Oracle Java7
    VM Encoding : UTF-8 (-Dfile.encoding=UTF-8)
    WebPage Encoding : UTF-8
    OS LANG : LANG=ja_JP.UTF-8
    IDE : STS(Spring Tool Suite)
    Boot Platform : WTP for Weblogic12.1.2.0
    Framework : Spring MVC(3.2.4)
    I want to know how to solve this behavior.
    なにかご存知の方いましたら、解決方法をご教授頂ければと思います。
    Message was edited by: user11123661 modified main language.(japanese -> english).

    The basic problem is not obscure, it has come up countless times since Tiger was released. See this note and try Fix C (dingbat) to see if it will help:
    http://homepage.mac.com/thgewecke/woutlook.html

  • Cannot rename file with non-ASCII characters when using the

    My application moves files from one directory to another by calling File[] srcFiles = srcDir.listFiles() to get a list of files in the source directory, and then calling srcFiles.renameTo(destFile) to rename each file.
    This does not work (renameTo returns false and the file is not moved) under the following circumstances:
    - the file's leaf name contains non-ASCII characters, for example "�"
    - the OS is Solaris 9
    - the LANG and LC_* environment variables are unset, i.e. the C locale is being used
    If I set the LANG environment variable to, for example, en_GB.UTF-8 then the rename succeeds.
    I have tried calling srcFiles[index].getName().getBytes("UTF-8") and the non-ASCII characters are being replaced with ? (0x3f) characters when LANG is unset.
    Is this a bug in the JRE? I would argue that since my code does not actually manipulate the filename (I just use the File object that File.listFiles() gives me) then the rename should succeed. Of course I would not expect the file name to be displayed correctly if I printed it out.
    I have reproduced this behaviour with JDK 1.4.2_05 and 1.5.0_04 on Solaris 9.
    Francis

    Thanks for the info Alan.
    I considered setting the locale in the environment (this sounds like the "correct" fix to me and we might implement it later), but this application shares a WebLogic server with many other applications so we would have to do a huge amount of testing to make sure that the locale change wouldn't break the other apps. In the end I worked around the problem by making the code that generates the filenames in the first place strip out any non-ASCII characters (the names of the files are not critically important).
    Looking forward to JSR-203, in the meantime perhaps a note about this behaviour in the java.io.File javadoc would be useful.

  • I have problems typing certain characters when using gmail or online forums. Can someone help?

    When I try to use an apostrophe, when using online forums or my email (all in safari), a white bar appears at the bottom of the screen displaying the punctuation mark but it will not allow me to use it. Any idea how I can fix this?

    Have you tried resetting your iPad?
    Reset: Press the Home and On/Off buttons at the same time and hold them until the Apple logo appears (about 10 seconds).
    No data will be lost.

  • Having garbage characters while using enctype="multipart/form-data"

    Hi to all! =)
    I'm uploading a CSV file in JSP ny adding [enctype="multipart/form-data"].
    <html:form method="POST" action="/upload.do" enctype="multipart/form-data">Now, I have a problem on handling Japanese Characters. (becomes garbage)
    I have declared a UTF-8 charset above my JSP
    [<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="Shift_JIS" %>]Using
    System.out.println(response.getCharacterEncoding());in my action, I get "ISO-8859-1" instead of UTF-8
    I don't have any clue why this has happened. Can someone teach me how to override the "ISO-8859-1" coding.
    Any suggestions will be deeply appreciated.

    Hi to all! =)
    I'm uploading a CSV file in JSP ny adding [enctype="multipart/form-data"].
    <html:form method="POST" action="/upload.do" enctype="multipart/form-data">Now, I have a problem on handling Japanese Characters. (becomes garbage)
    I have declared a UTF-8 charset above my JSP
    [<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="Shift_JIS" %>]Using
    System.out.println(response.getCharacterEncoding());in my action, I get "ISO-8859-1" instead of UTF-8
    I don't have any clue why this has happened. Can someone teach me how to override the "ISO-8859-1" coding.
    Any suggestions will be deeply appreciated.

  • Garbage characters when retrieving HTML via Java

    I wanted to use Java to extract my characters profile from http://www.magelo.com. The results returned from the URL are basically garbled characters; however retrieving cnn.com or yahoo.com the results are fine. So, the only thing I can think of is that the magelo webserver detects that its Java and, since it may not want people to not use this approach for mining concerns, changes the output to garbage. I tried setting the connections property "User-Agent" and others to mimic a browser, but nothing worked...the only way I can view non-garbaled HTML is by using a webbrowser. Not exactly sure that this is what is going on -- but I can't come up with another explaination.

    code & garbage.

  • Garbled characters when using bookmark fast searches

    I add the following site into my bookmark search:http://bk.baidu.com/searchword/?word=%s&pic=1&sug=1&oq=w&rsp=-1
    and set keyword bk.When I search chinese words the search words become garbled characters.For example,I type"bk 内存" in the address bar to search,and it turns out the search words become garbled characters"鍐呭瓨".The search result address is "http://bk.baidu.com/notexists?word=内存",if I replace the %s with the search words and type it in the address bar,it turns out OK.Chrome do not have such problem.

    The difference seems to be this HTTP request (first 4 RC and second in 3.6).<br />
    That first code is the result of encodeURIComponent.<br />
    I don't know how the second is encoded, but it looks like a bug in Firefox 4.<br />
    That second request is also send in Firefox 4 if I use the search field on http://bk<i></i>.baidu<i></i>.com/
    * GET /searchword/?word=%E5%86%85%E5%AD%98&pic=1&sug=1
    * GET /searchword/?word=%C4%DA%B4%E6&pic=1&sug=1

  • How to support non alphanumeric characters when using WORLD_LEXER?

    BASIC_LEXER has an attribute of printjoins which we can specify the non alphanumberic characters as normal alphanumberic in query and included with the token. However, WORLD_LEXER doesn't have this attribute. So in order to use some non alphanumberic characters and treat them as alphanumberic characters in Oracle Text Index, such as ><$, what should I can?
    Thanks in advance for any help.

    I use WORLD_LEXER to create Oracle Text Index to support UTF-8.
    Below is the script to create table and index:
    REM Create table
    CREATE TABLE my_test
    ( id VARCHAR2(32 BYTE) NOT NULL,
    code VARCHAR2(100 BYTE) NOT NULL,
         CONSTRAINT "my_test_pk" PRIMARY KEY ("id"));
    REM create index
    exec ctx_ddl.create_preference('stars_lexer','WORLD_LEXER');
    exec ctx_ddl.create_preference('stars_wordlist', 'BASIC_WORDLIST');
    exec ctx_ddl.set_attribute('stars_wordlist','substring_index','TRUE');
    exec ctx_ddl.set_attribute('stars_wordlist','PREFIX_INDEX','TRUE');
    -- create index for Table corrosion level
    CREATE INDEX my_test_index
    ON my_test(code)
    INDEXTYPE IS CTXSYS.CONTEXT
    PARAMETERS ('LEXER stars_lexer STOPLIST stars_stop WORDLIST stars_wordlist SYNC(EVERY "SYSDATE+5/1440") TRANSACTIONAL');
    INSERT INTO my_test('1', 'English word1');
    INSERT INTO my_test('2', '违违');
    INSERT INTO my_test('3', '违违&^|违违');
    When I query:
    select * from corrosion_levels r where contains(r.CORROSION_LEVEL, '{%违${|违%}') > 0
    ID CODE
    3 违违$(|违违
    2 违违
    Actually, the result what I want is: 3 违违$(|违违
    So the requirement is that all non-alphanumeric characters should be treated as normal alphanumeric charcters. Please tell me how to implement it.

  • How to retain new line characters when using Node.getNodeValue()

    Hi,
    I have xml as shown bellow
    *<DETAILS>*
    this is line one
    this is line two
    thi is line three
    *</DETAILS>*
    when I parse this using dom( Node.getNodeValue() ), the value I am getting is as shown bellow
    this is line onethis is line twothis is line three
    but I wanted as is I have in my xml i.e,
    this is line one
    this is line two
    this is line three
    ( to show that as is in HTML page)
    can some body help me ??
    Thanks in advance .

    Hi,
    You could try this:
    replace(your_data, chr(10), '')

  • Web pages display OK, but print with garbage characters. I think it's character encoding, but don't know WHICH I should use. Have tried all Western and UTF options. Firefox 3.6.12

    I used to only have troubles with headers & footers printing out as garbage characters. I tried changing Character Encoding, now entire pages have garbage characters, even though pages view ok when browsing.

    If the pages look OK when you are browsing then it is not a problem with the encoding.<br />
    It can be a problem with the font that is used and you can try to disable website fonts and posibly try a few different default fonts to see if that helps.
    Tools > Options > Content : Fonts & Colors: Advanced (Allow pages to choose their own fonts, instead of my selections above)

  • 802.1X PEAP fails when using special characters in login

    I am using MS AD & NPS for 802.1X Enterprise authentication with PEAP (no client certificate - MS-CHAPv2 user credentials for login). This works fine for iOS devices on 8.1 (iPhone 5 and iPad mini) and 6.1.6 (iPhone 3GS) when the user has standard "English" ASCII characters in the username and password.
    However, when I introduce Unicode special accented characters in the login name or password such as French é/ù or Spanish ñ then after accepting the server cert authentication fails with "Incorrect username or password for <WLAN name>". Windows 7 and CentOS 6.5 laptops have no problem authenticating to the same setup with either "English" credentials or ones with special accented characters. I also tried an old iPod touch on ancient software version and that fails, so its not something recently introduced.
    I tried using a different access point (TP-Link instead of Ruckus) and had exactly the same issue, so highly unlikely this is an AP issue.
    Then I setup FreeRadius with and see exactly the same issue, so its highly unlikely to be a MS AD/NPS issue.
    When comparing a working/failed authentication Wireshark packet capture on the NPS server, I see the failed attempt is missing the last 4 packets in the authentication exchange. The last packet sent is an Access-Challenge from the NPS server and no response from the iOS device, so the NPS server never even sends an Access-Reject. The iOS device appears to have decided it can't resolve the special characters and terminates the authentication attempt.
    To me this seems to be an Apple iOS software deficiency when using Unicode special characters in the username or password for 801.2X authentication?

    Enterprise support:
    Call enterprise support  (866) 752-7753  to create  a case ID number
    Get an account at
    http://developer.apple.com/  then submit a bug report to http://bugreporter.apple.com/
    Once on the bugreporter page,
       -- click on New icon
       -- See if you need to attach a log file or log files, clicking on Show instructions for gathering logs.  Scroll down to find the area or application that matches the problem.
       -- etc.
    Developers:
    "Submitting Bugs and Feedback
    Your feedback goes a long way towards making our products even better. With Apple Bug Reporter, you can submit bug reports or request enhancements to APIs and developer tools."
    https://developer.apple.com/bug-reporting/

  • Arabic characters appear as empty squares when using certain HTML tags or font styles

    Only when HW acceleration is on. Arabic characters appear as empty squares when using "italic" or "oblique" font styles or when using &lt;i&gt; or &lt;em&gt; html tags.
    Try this code to replicate the problem
    <pre>
    &lt;p&gt;مشكلة ظهور المربعات الخالية بدل الحروف&lt;/p&gt;
    &lt;p style="font-style: italic;">Italic مشكلة ظهور المربعات الخالية بدل الحروف&lt;/p&gt;
    &lt;p style="font-style: oblique;">Oblique مشكلة ظهور المربعات الخالية بدل الحروف&lt;/p&gt;
    &lt;i&gt;i tag مشكلة ظهور المربعات الخالية بدل الحروف</i> &lt;br&gt; &lt;br&gt;
    &lt;em&gt;em tag مشكلة ظهور المربعات الخالية بدل الحروف &lt;/em&gt;
    </pre>

    After lots of research, I found the problem. The boxes (squares) show up whenever there is a font in the webpage that does not have Arabic within its Unicode range such as Times New Roman Italic or Oblique. Normally, Firefox will pick another font to display the characters but now, a newly introduced feature is interfering.
    To fix the problem without turning off hardware acceleration.
    Go to about:config
    locate: gfx.font_rendering.directwrite.use_gdi_table_loading
    which is True by default in FF4.0 Beta 10, and change it to False.
    This is a bug that has to be fixed.

Maybe you are looking for

  • Macbook makes a WiFi connection, but Safari says it doesn't...?

    I got a new laptop for Christmas!!  Well, an early 08, which is new in my world.  I have had my Mac mini set up to be my WiFi access for a year or two now and it has worked perfectly for both my husband and my Android phones, as well as his tab, also

  • Getting Type Mismatch Error while passing Array of Interfaces from C#(VSTO) to VBA through IDispatch interface

    Hi, I am facing issues like Type Mismatch while passing Array of interfaces from .NET  to VBA and vice versa using VSTO technology. My requirement is that ComInterfaceType needs to be InterfaceIsIDispatch. My Interface definition is somewhat like thi

  • Multi-clip audio editing?

    Hi all, I'm sure this is  a very easy fix, but I can't figure out anything from the manual. I shoot a lot of school sports and now that I'm doing basketball indoors, the audio is generally too hot. Because I stop and start recording during time-outs

  • Nokia E72 WLAN Home Network Issues After SW Update...

    Hi, I just updated my software recently to the most recent update, and until doing so, I was able to connect to my home WLAN network. Now that I've updated the software, when I try to access the internet from my network, I get an "Invalid server" err

  • Source System for Flat Flie in QA?

    Hi Expert! I have defined a new source system for flat files in QA environment, and mapped this in 'conversion of source system names after transport' but the loads do not recognize this new SS... Error Msg "Source   does not exist" What can I do? Th