AES encrypt and decrypt not the same

I use aes to encrypt and decrypt a file. Why is the resulting file not the same as the input?
package mybeans;
import java.io.*;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import javax.crypto.*;
import javax.crypto.spec.*;
public class Encrypt {
     public static void main(String args[]) throws Exception {
          Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
          SecretKeySpec keySpec = new SecretKeySpec(
                    "05468345670abcde".getBytes(), "AES");
          IvParameterSpec ivSpec = new IvParameterSpec("f45gt7g83sd56210"
                    .getBytes());
          cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
          FileInputStream fis = new FileInputStream(new File("C:\\text.txt"));
          CipherInputStream cis = new CipherInputStream(fis, cipher);
          FileOutputStream fos = new FileOutputStream(new File(
                    "C:\\encrypted.txt"));
          byte[] b = new byte[8];
          int i;
          while ((i = cis.read(b)) != -1) {
               fos.write(b, 0, i);
          fos.flush();
          fos.close();
package mybeans;
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class Decrypt {
     public static void main(String args[]) throws Exception {
          Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
          SecretKeySpec keySpec = new SecretKeySpec(
                    "05468345670abcde".getBytes(), "AES");
          IvParameterSpec ivSpec = new IvParameterSpec("f45gt7g83sd56210"
                    .getBytes());
          cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
          FileInputStream fis = new FileInputStream(new File("C:\\encrypted.txt"));
          CipherInputStream cis = new CipherInputStream(fis, cipher);
          FileOutputStream fos = new FileOutputStream(new File(
                    "C:\\decrypted.txt"));
          byte[] b = new byte[8];
          int i;
          while ((i = cis.read(b)) != -1) {
               fos.write(b, 0, i);
          fos.flush();
          fos.close();
          cis.close();
          fis.close();
}Here is the data in the file:
James,"smith",007
mike,"smith",001
the result is this:
James,"smith",007
mike,"smith",
Edited by: iketurna on Jun 3, 2008 1:47 PM

Thanks sabre!
Very insightful.
I used PKCS5Padding and the file has all of the data, but there are extra padding at the end of the second line
Also,
how would you store your key and iv?
Currently I using this to create the iv and key:
public class KeyClass {
private SecretKeySpec keygeneration() {
SecretKeySpec skeySpec=null;
try {
  KeyGenerator kgen = KeyGenerator.getInstance("AES");
  kgen.init(128);
  SecretKey skey = kgen.generateKey();
  byte[] key = skey.getEncoded();
  skeySpec = new SecretKeySpec(key,"AES");
}catch(Exception e) {
  System.out.println("error in keygen = "+e);
return skeySpec;
public void keyFile() {
try{
FileOutputStream fos=new FileOutputStream("c:\\keyFile.txt");
DataOutputStream dos=new DataOutputStream(fos);
SecretKeySpec skeySpec=keygeneration();
byte[] key=skeySpec.getEncoded();
BASE64Encoder base64 = new BASE64Encoder();
String encodedString = base64.encodeBuffer(key);
dos.write(encodedString.getBytes());
}catch(Exception e1){
  System.out.println("error file write "+e1);
public static void main(String args[]){
  KeyClass cKey = new KeyClass();
  cKey.keyFile();
}Edited by: iketurna on Jun 5, 2008 7:29 AM

Similar Messages

  • Synced times in ical between iphone and Macbook not the same

    I have tried syncing my ical to my iphone using itunes and the times on my iphone are not the same as my ical. for example 1.30 pm for an appointment in my ical reads as 4.00am and the next day on my iphone calendar. How do I fix this?

    Are both the iPhone and your Mac set to the same (local) time zone? Do you have Time Zone support turned on in iCal Preferences and in iPhone > Settings > Mail, Contacts, Calendar?

  • HT201077 Why are my photos on my iphone and ipad not the same?

    My camera roll and photo stream on my iphone 4 and ipad 2 are not the same.  I have the same apple id for both and both devices are running ios 7.0.4.
    Any ideas?

    The camera roll contains photos actually taken on your device, or saved from text messages, emails, websites, etc.  Because of this you shouldn't expect both devices to have the same photos in the camera roll.
    The my photo stream album is also usually differerent on your devices.  This happens because photo stream photos only remain in iCloud for 30 days (even though they stay on your devices longer).  When you enable photo stream on a device, it can only receive photo stream photos still in iCloud, which are those from the last 30 days.  A consequence of this is that unless you enabled photo stream on both devices within 30 days of each other, one is likely to end up with fewer photo stream photos than the other.

  • Messenger and Contacts not the same over different devices

    I upgraded to iOS8 on my 5S and iPad 4th gen.
    Then I updated my MBP to Yosemite Beta - just in case I need to  utilize iCoud Drive.  I'm not using it.
    On my phone, I noticed that my contacts got jacked up.  First noticed it in my Favorites, where names used to be, there's numbers.  I notice much of the same thing when I open Messenger on the phone.  On my computers and iPad, Messenger has all the contact info the same - the way it used to be.
    I've been around since the @mac.com days, so I have that id.  As well as a @me.com from that transition.  And of course, the @icloud.com id.  I did notice, that one of the device (don't remember which one) was using the iCloud id while the rest wear using the me.com id.  Figured that it wouldn't matter, since they're all Apple id's that have merged all my data over the years.
    thoughts?
    thanks

    What do you mean by "synched on the iPad and iPhone"? Are you using iCloud?

  • Forms Modules under 10g and 11g not the same!

    Hi
    I 'am facing a prb with forms 10g at work, when I open a forms module with forms builder 10g, the items are all showing as radion button , but when I open the same forms module with forms builder 11g the items are all showing normaly as text item .
    Could any one explain the prbs plz?
    Thanks

    Are you trying to open a form that you modified with Forms 11g? If so, Oracle Forms is not backward compatible; meaning, a Forms 11g file can only be opened by Forms 11g. Even different versions of the same release are not backward compatible; eg, Forms 10g (10.1.2.0.2) cannot open a 10.1.2.3.0 file.
    Craig B-)
    If someone's response is helpful or correct, please mark it accordingly.

  • Mac • LR - Prints too dark and color not the same

    I a real problem where my prints are too dark about 2stops+ and color seem way off .
    How can I syc PS & LR so things print the same and the way that they should.
    Having to do work a rounds take up space that I can use, the time wast is ________ .
    Any and all hepl is welcome
    and
    Thank you
    Ric.

    RICHARD RODAMAR wrote:
    I a real problem where my prints are too dark about 2stops+ and color seem way off .
    How can I syc PS & LR so things print the same and the way that they should.
    So, printing an image from PS is OK, but from LR it's dark?
    Do both have the same printer ICC profile selected?
    Bob

  • Why are my ITunes playlists on my iPhone, iPad and Mac not the same?

    I don't understand the ITunes.  I have an Iphone, Ipad and new Mac Probook with Retina Display.  When I add songs to ITunes my playlists do not synchronize.  I have to manually delete the playlist on my Mac, create new ones, then synch with USB to each device.  Isn't there an easier way to manage the playlists?

    You can't drag and drop content onto smart playlists, only regular ones.
    tt2

  • Design and preview not the same

    I am a new Muse CC user so bear with me.
    I have deleted all graphics and navigation items from my three pages. All that is left is the page area.  I put text boxes in each of my pages.  I get about 3 inches of extra white space at the bottom of my page.  I stoked the page area so I can see its area.
    In design mode it looks fine.  In preview mode it gets about three inches longer.
    What have I done to make this happen?

    Hello,
    Please go to File -> Site Properties and disable "sticky footer" to see if that resolves the issue.
    Hope this helps.
    Cheers
    Parikshit

  • Im trying to activate my ipod but i dont know my icloud password or email, My apple ID and passwordsare not the same??

    I need help

    If you don't know your ID, you can try to find it as explained here: http://support.apple.com/kb/HT5625.  If you don’t know your password you can reset the password as explained here: http://support.apple.com/kb/PH2617.

  • Packets not getting encrypt and decrypt IPSEC

    Hi Everyone,
    I have 2691 Router conencted to Internet and it is doing Nat.
    This connects to 3550A  Switch which has connection to 1811W  Router.
    I setup VPN between 1811W and 3550A.
    3550A has connection to 2691 via ospf.
    OSPF is running between 1811w and 3550A.
    1811
    1811w# sh crypto isakmp sa
    IPv4 Crypto ISAKMP SA
    dst             src             state          conn-id status
    192.168.99.2    192.168.99.1    QM_IDLE           2005 ACTIVE
    IPv6 Crypto ISAKMP SA
    1811w# sh crypto ipsec sa
    interface: FastEthernet0
        Crypto map tag: VPN_MAP, local addr 192.168.99.1
       protected vrf: (none)
       local  ident (addr/mask/prot/port): (192.168.0.0/255.255.0.0/0/0)
       remote ident (addr/mask/prot/port): (192.168.99.0/255.255.255.0/0/0)
       current_peer 192.168.99.2 port 500
         PERMIT, flags={origin_is_acl,}
        #pkts encaps: 0, #pkts encrypt: 0, #pkts digest: 0
        #pkts decaps: 0, #pkts decrypt: 0, #pkts verify: 0
        #pkts compressed: 0, #pkts decompressed: 0
        #pkts not compressed: 0, #pkts compr. failed: 0
        #pkts not decompressed: 0, #pkts decompress failed: 0
        #send errors 30, #recv errors 0
         local crypto endpt.: 192.168.99.1, remote crypto endpt.: 192.168.99.2
         path mtu 1500, ip mtu 1500, ip mtu idb FastEthernet0
         current outbound spi: 0x0(0)
         PFS (Y/N): N, DH group: none
         inbound esp sas:
         inbound ah sas:
         inbound pcp sas:
         outbound esp sas:
         outbound ah sas:
         outbound pcp sas:
    3550A
    3550SMIA#                                                                                           sh crypto isakmp sa
    IPv4 Crypto ISAKMP SA
    dst             src             state          conn-id slot status
    192.168.99.2    192.168.99.1    QM_IDLE           1001 ACTIVE
    IPv6 Crypto ISAKMP SA
    3550SMIA#sh cry
    3550SMIA#sh crypto ipsec sa
    interface: FastEthernet0/8
        Crypto map tag: VPN_MAP, local addr 192.168.99.2
       protected vrf: (none)
       local  ident (addr/mask/prot/port): (192.168.0.0/255.255.0.0/0/0)
       remote ident (addr/mask/prot/port): (192.168.99.0/255.255.255.0/0/0)
       current_peer 192.168.99.1 port 500
         PERMIT, flags={origin_is_acl,}
        #pkts encaps: 0, #pkts encrypt: 0, #pkts digest: 0
        #pkts decaps: 0, #pkts decrypt: 0, #pkts verify: 0
        #pkts compressed: 0, #pkts decompressed: 0
        #pkts not compressed: 0, #pkts compr. failed: 0
        #pkts not decompressed: 0, #pkts decompress failed: 0
        #send errors 15, #recv errors 0
         local crypto endpt.: 192.168.99.2, remote crypto endpt.: 192.168.99.1
         path mtu 1500, ip mtu 1500
         current outbound spi: 0x0(0)
         inbound esp sas:
         inbound ah sas:
         inbound pcp sas:
         outbound esp sas:
    As seen above the packets are not encrypted between 1811w and 3550A.
    I have used same ACL  on both 1811W and 3550A
    ip access-list extended INTERESTING_TRAFFIC
    permit ip 192.168.0.0 0.0.255.255 192.168.99.0 0.0.0.255 log
    Any reasons why packets are not getting encrypt and decrypt?
    Thanks
    MAhesh

    Hi Eugene,
    I did that here is info now
            sh crypto ipsec sa
    interface: FastEthernet0
        Crypto map tag: VPN_MAP, local addr 192.168.99.1
       protected vrf: (none)
       local  ident (addr/mask/prot/port): (192.168.0.0/255.255.0.0/0/0)
       remote ident (addr/mask/prot/port): (192.168.99.0/255.255.255.0/0/0)
       current_peer 192.168.99.2 port 500
         PERMIT, flags={origin_is_acl,}
        #pkts encaps: 43, #pkts encrypt: 43, #pkts digest: 43
        #pkts decaps: 43, #pkts decrypt: 43, #pkts verify: 43
        #pkts compressed: 0, #pkts decompressed: 0
        #pkts not compressed: 0, #pkts compr. failed: 0
        #pkts not decompressed: 0, #pkts decompress failed: 0
        #send errors 1, #recv errors 0
         local crypto endpt.: 192.168.99.1, remote crypto endpt.: 192.168.99.2
         path mtu 1500, ip mtu 1500, ip mtu idb FastEthernet0
         current outbound spi: 0x8319FE5B(2199518811)
         PFS (Y/N): N, DH group: none
         inbound esp sas:
          spi: 0xAE0A578B(2919913355)
            transform: esp-des esp-sha-hmac ,
            in use settings ={Tunnel, }
            conn id: 15, flow_id: Onboard VPN:15, sibling_flags 80000046, crypto map: VPN_MAP
            sa timing: remaining key lifetime (k/sec): (4454255/2388)
            IV size: 8 bytes
            replay detection support: Y
            Status: ACTIVE
         inbound ah sas:
         inbound pcp sas:
         outbound esp sas:
          spi: 0x8319FE5B(2199518811)
            transform: esp-des esp-sha-hmac ,
            in use settings ={Tunnel, }
            conn id: 16, flow_id: Onboard VPN:16, sibling_flags 80000046, crypto map: VPN_MAP
            sa timing: remaining key lifetime (k/sec): (4454255/2388)
            IV size: 8 bytes
            replay detection support: Y
            Status: ACTIVE
         outbound ah sas:
         outbound pcp sas:
    Seems it is encrypted now.
    Congig of ACL
    ip access-list extended INTERESTING_TRAFFIC
    permit ip 192.168.0.0 0.0.255.255 192.168.99.0 0.0.0.255 log
    even though i have log command config in thr ACL  still it shows only
    2 logs
    .Dec 15 14:23:55.723 MST: %SEC-6-IPACCESSLOGP: list INTERESTING_TRAFFIC permitted udp 192.168.99.1(123) -> 192.168.99.2(123), 1 packet
    .Dec 15 14:29:28.391 MST: %SYS-5-CONFIG_I: Configured from console by mintoo on vty0 (192.168.98.6)
    .Dec 15 14:40:55.749 MST: %SEC-6-IPACCESSLOGP: list INTERESTING_TRAFFIC permitted udp 192.168.99.1(123) -> 192.168.99.2(123), 1 packet
    1811w#
    Do you know why is this?
    Thanks
    MAhesh

  • Will Verizon Stop encrypting sim cards for iPhones so users can talk and surf at the same time?

    Will Verizon stop encrypting iPhone sim cards so users can surf and talk simultaneously?

    I can prove that this is not the case. I travel abroad monthly and have sim cards for these 2 countries i frequent and i can surf and talk at the same time. The claim that it needs another antenna does not support my findings. Can we be more transparent please. As a costumer i find it highly inconvenient to have to hang up a call with someone just to access an email.
    >> Personal information removed to comply with the Verizon Wireless Terms of Service <<
    Edited by:  Verizon Moderator

  • Urgent - encrypt and decrypt the single field (String)

    Hi,
    I want to create Java program which can encrypt and decrypt the single field (String). Can you please pass me the code. I am new to the Java and my technical background is not from Java. Appreciate your speedy response.
    You can directly reach me at [email protected]
    --Akshay                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Welcome to the Developer Community! We'd like you to get the most out of your experience at the Forums. Please keep in mind that the many of the developers who help you are working for a living, and all of them are providing you with free advice. It is only fair for you to do some homework first prior to posting. Here are some suggestions from the developer community to the newest members. To avoid wasting fellow members' time unnecesarily, please use the following checklist before posting a question:
    * Search before Posting: Especially if you are in a hurry, you may find that the question has already been asked and answered during the long history of the Forums.
    * Know the basics: Read this FAQ and the basic trails of the Java Tutorial (like Getting Started or Learning the Java Language). If you don't understand the question you are posing, you may not understand the answers.
    * Be thorough and precise: Proofread your question before posting. Describe the steps that you have taken. The more effort you put into researching and describing your problem, the more likely you will get a sincere effort in return.
    * Post a subject line that describes the problem: Experts in your subject may skim right past subject lines like "Urgent" and "Need help ASAP". Use keywords about the technologies instead.
    * Post a problem, not an assignment: Break your assignment down into specific problems that you can ask for help with. Dorm hall lounges may be a better resource if you have a last minute, "urgent" demand for solutions to homework problems.
    -- From the [Java Forums FAQ|http://developers.sun.com/resources/forumsFAQ.html#Getting]

  • The Encrypt and Decrypt functions.

    All,
    I need to use the Encrypt and Decrypt functions for our password filed in a table.
    The procedures need to pass in an input_string (string to be en/decrypted) and a key_string (en/decryption key string). What is the key_string? Where can I get it from? or How can I generate it?
    Could someone please give some examples on how to use those functions?
    Thanks in advance!

    This may help you, works with 8.1.7 upwards :
    We used this approach when I worked on a project in Holland. We encrypted customers' names and addresses. Note : the value to be encrypted had to be a multiple of 8 characters in length so we always rpad'd values upto a multiple of 8 say 32 and rtrim'd following decryption. W were using 8.1.7. at the time and I am unsure if this requirement still exists. Note : the encryption key was actually held in a package which was wrapped and in a schema with password only known to few.
    set serverout on size 1000000
    declare
       input_string_c     varchar2(16) := '1234567812345678'; -- must be multiple of 8 bytes long
       key_string_c       varchar2(57) := 'abcdefghijklmnop'; -- the key needs to be at leat 8 bytes long
       encrypted_string_c varchar2(2048);
       decrypted_string_c varchar2(2048);
    begin
       dbms_obfuscation_toolkit.desencrypt (input_string     => input_string_c,
                                            key_string       => key_string_c,
                                            encrypted_string => encrypted_string_c) ;
       dbms_obfuscation_toolkit.desdecrypt (input_string     => encrypted_string_c,
                                         key_string       =>  key_string_c,
                                   decrypted_string => decrypted_string_c);
       dbms_output.put_line('encrypted string = >'||encrypted_string_c||'<');
       dbms_output.put_line('decrypted string = >'||decrypted_string_c||'<');
    end;
    /HTH
    AMM

  • How do I find out my password to back up and restore my new iphone 6? Its not the same as my iTunes password..

    How do I find out my password to back up and restore my new iphone 6? Its not the same as my iTunes password..

    I am guessing you are talking about an encryption password that you placed on the backup you put into iTunes on your computer.
    If so, you elected to encrypt your iPhone's backup.  You will need to recall that password, or you cannot access the backup.

  • My Ipad mini does not see my printer. my wife's ipad2 does. We both use IOS8 and upgraded at the same time. How can I remedy this?

    My Ipad mini does not see my printer. my wife's ipad2 does. We both use IOS8 and upgraded at the same time. How can I remedy this?

    OK great info!
    I found 2 possible ethernet to USB adapters:
    By "Plugable":  USB 2.0 to ethernet LAN wired network adapter - seems this will work, but I'll contact Plugable.
    2. Apple USB Ethernet Adapter
    Easily connect your MacBook Air computer to an Ethernet network with the Apple USB Ethernet Adapter. Small and light, it connects to the USB 2.0 port of your MacBook Air and provides an RJ-45 connector that supports 10/100BASE-T performance.  BUT NOT SURE IF THIS WILL WORK ON ANYTHING BUT a MacBook Air…
    One person commented: 
    This little gem used to be the device of choice for adding a second Ethernet interface to a Mac Mini Server and I'd been using one that way for about a year. After doing a software update to 10.6.6 it stopped working. Forewarned is forearmed – it appears that Apple is finally enforcing the MacBook Air system requirement.
    Thanks for any additional comments.
    Best regards,
    Steve Schulte
    Sunday 6 January 2013

Maybe you are looking for

  • Facetime will not open or load properly

    I have downloaded Facetime onto my IMac, and it will not open correctly, just shows the black screen with camera off. At times will say there is an internal error and ask me to quit and relaunch. Cannot access preferences. Any ideas? It works fine on

  • Capturing desktop

    I need to capture the desktop into a video stream, preferably recording audio input from the mic at the same time. I know there are programs to do this, but surely there's an awesome command line way with ffmpeg or something.

  • ORACLE_HOME in Oracle RAC 11g (Windows Server 2008)

    Hello, I've got two (2) nodes in an Oracle RAC 11g in Windows Server 2008. Oracle software is installed in C:\app. I realized that it's not been set ORACLE_HOME path. In System Properties-> Advanced -> Environment Variables, I see that ORACLE_HOME is

  • HT201150 Where is the shut down dialog?

    Whit the last update (10.9.2) pushing the power button nothing happen, pushing it for 1.5 second the mac goes on standby. No way to found the shut down dialog, it was just esier before.

  • Panels All Open by Default...

    Hi everyone. Just wondering if there was a way to have the panels open automatically when a browser loads, but still have the functionality of collapsing and reopening. Any help would be appreciated! Thanks!