DES decryption

Hi,
If I have a file that is DES encrypted and I know the String key value e.g. "8AE.B(,5". How can I decript the file?
Thanks in advance.
PS I also need to GUNZIP this afterwards...
String x = "8AE.B(,51";               
byte[] keyBytes  = x.getBytes();
SecretKey key = new SecretKeySpec(keyBytes, "DES");Is this the correct way to use the String key??

Will this type of code help?
e465. Converting a 56-bit Value to a DES Key
The DES encrypter/decrypter requires a 64-bit key where only 56-bit are significant. The other 8-bit are parity bits used to ensure that the key has not been corrupted. To make the 64-bit key, the 56-bit value is broken up into 7-bit chunks. Each 7-bit chunk is moved into an 8-bit slot taking up the most significant bit positions. The least significant bit (the parity bit) is set to either 1 or 0 in order to make the quantity of 1 bits in the byte an odd number.
This example implements a method to convert a 56-bit value into a valid DES key. Such a method could be used to convert a 7-character string password to a valid DES key.
See also e462 Encrypting a String with DES.
    // Takes a 7-byte quantity and returns a valid 8-byte DES key.
    // The input and output bytes are big-endian, where the most significant
    // byte is in element 0.
    public static byte[] addParity(byte[] in) {
        byte[] result = new byte[8];
        // Keeps track of the bit position in the result
        int resultIx = 1;
        // Used to keep track of the number of 1 bits in each 7-bit chunk
        int bitCount = 0;
        // Process each of the 56 bits
        for (int i=0; i<56; i++) {
            // Get the bit at bit position i
            boolean bit = (in[6-i/8]&(1<<(i%8))) > 0;
            // If set, set the corresponding bit in the result
            if (bit) {
                result[7-resultIx/8] |= (1<<(resultIx%8))&0xFF;
                bitCount++;
            // Set the parity bit after every 7 bits
            if ((i+1) % 7 == 0) {
                if (bitCount % 2 == 0) {
                    // Set low-order bit (parity bit) if bit count is even
                    result[7-resultIx/8] |= 1;
                resultIx++;
                bitCount = 0;
            resultIx++;
        return result;
    // Get the 56-bit value
    byte[] raw = new byte[]{0x01, 0x72, 0x43, 0x3E, 0x1C, 0x7A, 0x55};
    byte[] keyBytes = addParity(raw);
    // You can check that the parity has been set properly
    try {
        boolean b = DESKeySpec.isParityAdjusted(keyBytes, 0);
    } catch (java.security.InvalidKeyException e) {
        // The DES is invalid
    // Convert the bytes into a SecretKey suitable for use by Cipher
    SecretKey key = new SecretKeySpec(keyBytes, "DES");

Similar Messages

  • FTP to mail scenario with DES decryption

    Hi All,
    I have a existing process where FTP data files are scheduled to be available at 1:00pm each day on the FTP server.  Earlier to support this, a Windows-based FTP client script has been developed by us  which automatically retrieves the files via the Internet and does a number of other tasks which are detailed below.  This script runs at 1:10pm each day, including weekends and holidays.  The script retrieves 3 files, which are saved locally, and then decrypted, archived, and finally transferred via mail and also FTP to specific Unix directories for import into various SAP systems
    I have a scenario where SAP PI needs to do the same stuff above that is pick a file from the ftp location and send it to a mail address. The file will be in encrypted format and SAP PI needs to decrypt the file and the decrypted file needs to be send through.
    The files at the FTP side are encrypted using DES Encryption so ideally SAP PI needs to decrypt it using DES decryption.
    I know I can keep the DES software on the UNIX server at XI side and call it in sender file adapter at OS level calls but as far as I know it will be difficult for maintenance as the logs won't be available for proper monitoring.
    What is the best way to achieve this  ?
    Thanks in advance.
    Ravijeet
    Edited by: RAVIJEET.SAP.PI on Dec 2, 2010 4:00 PM
    Edited by: RAVIJEET.SAP.PI on Dec 2, 2010 8:18 PM

    Any suggestions

  • InternalError: DES Decryption error

    **PLEASE HELP** I recenty did an extension update from MCE 1.2.1 to 1.2.2 for both the 1.2.2 framework and provider. It resolved my previous ExceptionInInitializerError of 'Cannot set up certs for trusted CAs.' I'm now getting an InternalError or "DES Decryption error
    at com.marconi.soc.util.Des3.decrypt (Des3.java:114)
    at com.marconi.soc.util.Crypt3.decrypt (Crypt3:java:51)
    and so on.
    This occurs after starting Openview's NNM which is integrated with Marconi's NMS app, ServiceOn Data (ver2.2).
    I'm not a software or java person so I desperately need some expert help from this forum.
    I believe we're using jre 1.2 thru 1.4 ( each NMS app uses a different jre version, I think). It all worked fine before the JCE expired.

    Hi,
    MDN (Message Disposition Notifications) is nothing but an Exchange Level acknowledgement. MDN ensures the sender of the document that the recipient has successfully received the document. The sender specifies how the MDN is to be sent back (either synchronously or asynchronously, and signed or unsigned). MDN provides the "Non-repudiation" element of AS2
    In case, recipient is able to read the received message successfully a success MDN is sent back otherwise a failed MDN is sent back. Not getting any MDN back also indicates a failure.
    Ask your tp to check the information he/she received in MDN.
    Regards,
    Anuj

  • Help  with DES  decryption

    Hello !
    I wrote the code for DES Encryption , which i have tested and works perfectly, consistent with the results expected.
    But I have not been able to implement the decryption process correctly asI have not yet understood the way i need to shift the order of keys , or their elements.I tried reversing the left shifting sequence , but it didn't solve the problem
    Please suggest something .I just need to understand the exact process used for decryption.
    Many Thanks..

    @dstuz
    I haven't been reinventing the wheel , but I have been working out the DES code on my own.
    I have already coded the application for encryption & it works perfectly- thoroughly verified.
    Now since i have been looking to finish the cipher by implementing the Decryption stage..i am stuck because there isn't enough info available to actually clarify my doubt.Some variation has to be made in the way we apply keys to the Right Expanded array but i haven't quite figured out how..
    I can do the coding on my own..infact 90% of the coding is finished
    FYI.
    Its just this last step , where i have been stuck , trying to figure out how the last step is to be done.
    I just need help to exactly understand the process & lend the finishing touch to the cipher.

  • DES Decryption using a decrypt id

    I have a decrypt id from the vendor from whom i get the data encrypted in DES. So i wanna how i can use that decrypt id and decrypt the encrypted data. Hope someone has already worked on this and hoping for a quick reply..
    Thanks,
    Ravi

    I have a decrypt id from the vendor from whom i get the data encrypted in DES. So i wanna how i can use that decrypt id and decrypt the encrypted data. Hope someone has already worked on this and hoping for a quick reply..
    Thanks,
    Ravi

  • DES Decryption Code Review / Not Running

    Hi,
    I'm trying to do the following in a java program:
    -Read a DES key from the a file generated by my client
    -Use the incoming DES key to decrypt an incoming message from socket s
    -Print out the message
    I've gotten it started, but I just don't know what else I'm missing.
    Thanks,
    James
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import javax.crypto.*;
    public class CipherServer
         public static void main(String[] args) throws Exception
              int port = xxxx;    //I purposely changed to xxxx for privacy
              ServerSocket server = new ServerSocket(port);
              Socket s = server.accept();     
              //Read the key from the file
              ObjectInputStream in=new ObjectInputStream(new FileInputStream("des.key"));
              key=(Key)in.readObject();
              in.close();
              //Decrypt
              Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
              cipher.init(Cipher.DECRYPT_MODE, key);
              //Printing the message
              System.out.println(message);
    }

    Hi,
    Thanks for the reply Sabre150. Here's the client side of my program and how it's sent, if it helps:
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import javax.crypto.*;
    public class Ciphert
         public static void main(String[] args) throws Exception
              String message = "Hi John, how are you?";
              String host = "xxx.xxx.xxx";
              int port = xxxx;
              Socket s = new Socket(host, port);
              //DES Key Generation
              KeyGenerator generator= KeyGenerator.getInstance("DES");
              generator.init(new SecureRandom());
              key=generator.generateKey();
              //Storage of DES Key to File                    
              ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("des.key"));
              out.writeObject(key);
              out.close();             
              //usage of ObjectOutputStream to communicate with the server
              ObjectOutputStream outSocket = new ObjectOutputStream(cipherOut);
              //Encrypt the message above using the key and send it over socket s to the server
              Cipher cipher=Cipher.getInstance("DES/ECB/PKCS5Padding");
              cipher.init(Cipher.ENCRYPT_MODE, key);
              //Passing the encrypted message over socket s to the server
              CipherOutputStream cipherOut = new CipherOutputStream(s.getOutputStream(), cipher);
    }

  • Problem with DES Decryption of String - Need Urgent Help

    Hi,
    I created this program to encrypt and decrypt a string using DES algorithm but somehow I keep getting an exception. The code is given below.
    /* ASCryptography.java*/
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.security.*;
    import java.io.*;
    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;
    public class ASCryptography
         public static String[] encryptPassword(String password)
              String returnvalue[] = new String[2];
              try
                   KeyGenerator keygen = KeyGenerator.getInstance("DES");
                   SecretKey skey = keygen.generateKey();
                   byte[] bytekey = skey.getEncoded();
                   returnvalue[0] = new BASE64Encoder().encode(bytekey);
                   Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
                   cipher.init(Cipher.ENCRYPT_MODE, skey);
                   byte[] bytepassword = password.getBytes();
                   byte[] byteencryptedpassword = cipher.doFinal(bytepassword);
                   returnvalue[1] = new BASE64Encoder().encode(byteencryptedpassword);
              catch(Exception err)
              return (returnvalue);
         public static String decryptPassword(String key, String encryptedpassword)
              String password = null;
              try
                   Cipher decipher = Cipher.getInstance("DES/CBC/PKCS5Padding");               
                   byte[] bytekey = new BASE64Decoder().decodeBuffer(key);
                   SecretKey skey = new SecretKeySpec(bytekey, "DES");
                   decipher.init(Cipher.DECRYPT_MODE, skey, decipher.getParameters());   /* Netbeans detected the error to be in this part*/
                   byte[] byteencryptedpassword = new BASE64Decoder().decodeBuffer(encryptedpassword);
                   byte[] bytedecryptedpassword = decipher.doFinal(byteencryptedpassword);
                   password = new String(bytedecryptedpassword);
              catch(Exception err)
                   System.out.println(err);
              return password;
    }The methods of this class are used by another class given below.
    /*Crypt.java*/
    public class Crypt
         public static void main(String[] args)
              String password = "pic01234";
              String value[] = new String[2];
              value = ASCryptography.encryptPassword(password);
              System.out.println(value[0]);
              System.out.println(value[1]);
              String returnedvalue = ASCryptography.decryptPassword(value[0], value[1]);
              System.out.println(returnedvalue); //the returned value remains null
              System.out.println(returnedvalue.length()); // This generates a null pointer exception coz of above.
    }Now whenever I run the Crypt.java program the Netbeans IDE gives the following as output
    jL+Fg2EBp9Y=
    LOhqKHoJRkKWc76IkU4q/A==
    java.security.InvalidAlgorithmParameterException: Parameters missing
    null
    Exception in thread "main" java.lang.NullPointerException
    I used the Step in tool of Netbeans and came out with the following conclusion
    1. The first 2 strings are the encrypted key and the password string so encryption is working fine.
    2. All is fine till the decipher.init(Cipher.DECRYPT_MODE, skey, decipher.getParameters()); part is encountered at this point the java.security.InvalidAlgorithmParameterException: Parameters missing is thrown.
    3.The NullPointerException is caused due to the null value stored in returnedvalue
    Can anyone help me out with this one I have been trying to solve for the past 6 hours.
    Thanks!

    Also -
    1) Using an array to return a compound result is at best poor. You should really define a class as a container for your encryption result.
    2) Since you generate and return a new key for each password, where are you going to store the key. If you store it in the same place (database ?) as the encrypted password then this is just the same as not encrypting the password because anyone with with access to the encrypted password will also have access to the key!

  • Having Trouble Correctly Encrypting Email Addresses Using DES

    Hi, I am having some problems when I try to encrypt email addresses using DES encryption. I can't really find a solution to the problem. Any help would be appreciated.
    //String Encryptor. Takes a string and returns it's equivalent DES encryption.
        private String encrypter(String str)
            try
                byte[] word = str.getBytes("UTF8");
                byte[] encryptedString = this.encrypt.doFinal(word);
                return new String(encryptedString);
            catch(Exception e)
                e.printStackTrace();
            return null;
    //String decryptor: Takes an encrypted string and returns its equivalent DES decrypted string
        private String decrypter(String str)
            try
                byte[] encryptedString = str.getBytes();
                byte[] word = this.decrypt.doFinal(encryptedString);
                return new String(word);
            catch (Exception e)
                e.printStackTrace();
            return null;
            }This is a simple input and output:
    Input: [email protected]
    Out: ‰Qœnõœ £¥Å¼ˆ'v(úR»ñ]{&õa?´n±                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    You don't say what your problem is but this code is an example of the number 1 problem reported in this forum. String is not a suitable container for binary data and encrypted data returned by          byte[] encryptedString = this.encrypt.doFinal(word);
      is definitely binary data and should not be converted to a String using new String(encryptedString);The basic problem is that for the majority of character encodings the transformation
    bytes -> String  -> bytesdoes not produced the original bytes.

  • Relationship between D3DES of Java and C++

    Could you pls advise is it possible for me to encrypt the message by C++ and then decrypt by Java? By other words, do those two D3DES have simaliar funtion? I tried to encrypt some program by C++ but I failed to decrypt it by Java. Pls advise!

    I posted two programs below. Pls help to check if there is any change I need to modify so that I can encrypt and decypt freely later on.
    #include "stdafx.h"
    #include "memory.h"
    #include "Des.h"
    // initial permutation IP
    const static char IP_Table[64] = {
         58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4,
         62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8,
         57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3,
    61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7
    // final permutation IP^-1
    const static char IPR_Table[64] = {
         40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31,
         38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29,
    36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27,
         34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25
    // expansion operation matrix
    static const char E_Table[48] = {
         32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9,
         8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17,
         16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25,
         24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1
    // 32-bit permutation function P used on the output of the S-boxes
    const static char P_Table[32] = {
         16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10,
         2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25
    // permuted choice table (key)
    const static char PC1_Table[56] = {
         57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18,
         10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36,
         63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22,
         14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4
    // permuted choice key (table)
    const static char PC2_Table[48] = {
         14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10,
         23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2,
         41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48,
         44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32
    // number left rotations of pc1
    const static char LOOP_Table[16] = {
         1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1
    // The (in)famous S-boxes
    const static char S_Box[8][4][16] = {
         // S1
         14,     4,     13,     1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
         0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
         4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
    15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13,
         // S2
    15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
         3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
         0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
    13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9,
         // S3
    10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
         13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
         13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
    1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12,
         // S4
    7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
         13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
         10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
    3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14,
         // S5
    2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
         14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
         4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
    11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3,
         // S6
    12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
         10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
         9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
    4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13,
         // S7
    4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
         13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
         1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
    6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12,
         // S8
    13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
         1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
         7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
    2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11
    typedef bool (*PSubKey)[16][48];
    static void DES(char Out[8], char In[8], const PSubKey pSubKey, bool Type);//
    static void SetKey(const char* Key, int len);//
    static void SetSubKey(PSubKey pSubKey, const char Key[8]);//
    static void F_func(bool In[32], const bool Ki[48]);// f
    static void S_func(bool Out[32], const bool In[48]);// S
    static void Transform(bool Out, bool In, const char *Table, int len);//
    static void Xor(bool InA, const bool InB, int len);//
    static void RotateL(bool *In, int len, int loop);//
    static void ByteToBit(bool Out, const char In, int bits);//
    static void BitToByte(char Out, const bool In, int bits);//
    static bool SubKey[2][16][48];// 16
    static bool Is3DES;//
    static char Tmp[256], deskey[16];
    // Code starts from Line 130
    bool Des_Go(char Out, char In, long datalen, const char *Key, int keylen, bool Type)
    if( !( Out && In && Key && (datalen=(datalen+7)&0xfffffff8) ) )
              return false;
         SetKey(Key, keylen);
         if( !Is3DES ) {   // DES
              for(long i=0,j=datalen>>3; i<j; ++i,Out+=8,In+=8)
                   DES(Out, In, &SubKey[0], Type);
         } else{   // 3des
              for(long i=0,j=datalen>>3; i<j; ++i,Out+=8,In+=8) {
                   DES(Out, In, &SubKey[0], Type);
                   DES(Out, Out, &SubKey[1], !Type);
                   DES(Out, Out, &SubKey[0], Type);
         return true;
    void SetKey(const char* Key, int len)
         memset(deskey, 0, 16);
         memcpy(deskey, Key, len>16?16:len);
         SetSubKey(&SubKey[0], &deskey[0]);
         Is3DES = len>8 ? (SetSubKey(&SubKey[1], &deskey[8]), true) : false;
    void DES(char Out[8], char In[8], const PSubKey pSubKey, bool Type)
    static bool M[64], tmp[32], Li=&M[0], Ri=&M[32];
    ByteToBit(M, In, 64);
    Transform(M, M, IP_Table, 64);
    if( Type == ENCRYPT ){
    for(int i=0; i<16; ++i) {
    memcpy(tmp, Ri, 32);
    F_func(Ri, (*pSubKey));
    Xor(Ri, Li, 32);
    memcpy(Li, tmp, 32);
    }else{
    for(int i=15; i>=0; --i) {
    memcpy(tmp, Li, 32);
    F_func(Li, (*pSubKey)[i]);
    Xor(Li, Ri, 32);
    memcpy(Ri, tmp, 32);
    Transform(M, M, IPR_Table, 64);
    BitToByte(Out, M, 64);
    void SetSubKey(PSubKey pSubKey, const char Key[8])
    static bool K[64], KL=&K[0], KR=&K[28];
    ByteToBit(K, Key, 64);
    Transform(K, K, PC1_Table, 56);
    for(int i=0; i<16; ++i) {
    RotateL(KL, 28, LOOP_Table[i]);
    RotateL(KR, 28, LOOP_Table[i]);
    Transform((*pSubKey)[i], K, PC2_Table, 48);
    void F_func(bool In[32], const bool Ki[48])
    static bool MR[48];
    Transform(MR, In, E_Table, 48);
    Xor(MR, Ki, 48);
    S_func(In, MR);
    Transform(In, In, P_Table, 32);
    void S_func(bool Out[32], const bool In[48])
    for(char i=0,j,k; i<8; ++i,In+=6,Out+=4) {
    j = (In[0]<<1) + In[5];
    k = (In[1]<<3) + (In[2]<<2) + (In[3]<<1) + In[4];
              ByteToBit(Out, &S_Box[i][j][k], 4);
    void Transform(bool Out, bool In, const char *Table, int len)
    for(int i=0; i<len; ++i)
    Tmp[i] = In[ Table[i]-1 ];
    memcpy(Out, Tmp, len);
    void Xor(bool InA, const bool InB, int len)
    for(int i=0; i<len; ++i)
    InA[i] ^= InB[i];
    void RotateL(bool *In, int len, int loop)
    memcpy(Tmp, In, loop);
    memcpy(In, In+loop, len-loop);
    memcpy(In+len-loop, Tmp, loop);
    void ByteToBit(bool Out, const char In, int bits)
    for(int i=0; i<bits; ++i)
    Out[i] = (In[i>>3]>>(i&7)) & 1;
    void BitToByte(char Out, const bool In, int bits)
    memset(Out, 0, bits>>3);
    for(int i=0; i<bits; ++i)
    Out[i>>3] |= In[i]<<(i&7);
    // Code ends at Line 231
    package com.longmai.system.util.common;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2004</p>
    * <p>Company: longmai</p>
    * @author ouyw
    * @version 1.0
    import java.io.*;
    import javax.crypto.*;
    import javax.crypto.Cipher;
    import javax.crypto.spec.*;
    import javax.crypto.spec.DESedeKeySpec;
    import java.security.spec.KeySpec;
    import java.security.spec.AlgorithmParameterSpec;
    import java.security.*;
    public class Des3
    private static String Des = "Des";
    private static String Desede = "DESEDE";
    private static String DesBlowfish = "Blowfish";
    private static String algorithm =Desede;
    private static String key ="";
    public static byte[] encrypt(byte[] data,String key )
    try{
    byte[] rawkey = key.getBytes();
    DESedeKeySpec keyspec = new DESedeKeySpec(rawkey);
    SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(algorithm);
    Key enkey = keyfactory.generateSecret(keyspec);
    Cipher c1 = Cipher.getInstance(algorithm);
    c1.init(Cipher.ENCRYPT_MODE,enkey);
    byte[] cipherByte=c1.doFinal(data);
    return cipherByte;
    catch(Exception e)
    return null;
    public static String decrypt(byte[] data,String key )
    try{
    byte[] rawkey = key.getBytes();
    DESedeKeySpec keyspec = new DESedeKeySpec(rawkey);
    SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(
    algorithm);
    Key enkey = keyfactory.generateSecret(keyspec);
    System.out.println("enkey="+enkey.getEncoded().length);
    Cipher c1 = Cipher.getInstance(algorithm);
    c1.init(Cipher.DECRYPT_MODE,enkey);
    byte[] b = c1.doFinal(data);
    return new String(b);
    }catch(Exception e){
    e.printStackTrace();
    return null;
    public static void main(String[] args){
    Des3 des = new Des3();
    byte[] b = des.encrypt("0123456789abcdefghijklmnopkrst".getBytes(),key);
    System.out.println("b len=" + b.length);
    for(int i=0;i<b.length;i++){
    System.out.print(","+b[i]);
    if(b!=null){
    String a = des.decrypt(b,key);
    System.out.println("a=" + a);
    }else{
    System.out.println("b=" + b);

  • Why do i get an "IllegalBlockSizeException"?

    I have a piece of code which encrypts a string and stores it into a txt file. But when i come to decrypt the file i get the following error
    Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length
    (with padding) not multiple of 8 bytes
    at com.sun.crypto.provider.DESCipher.a(DashoA6275)
    at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA6275)
    at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA6275)
    at javax.crypto.Cipher.doFinal(DashoA6275)
    at javamailerprogram.DES.decrypt(DES.java:110)
    at javamailerprogram.DES.main(DES.java:120)
    This is my code
    package javamailerprogram;
    import java.security.*;
    import java.security.*;
    import javax.crypto.*;
    import java.io.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import javax.crypto.spec.SecretKeySpec;
    import java.util.*;
    import java.security.interfaces.*;
    public class DES {
    static SecretKey newKey;
    static String ENCRYPTION_TYPE = "DES";
    static int KEY_SIZE = 56;
    static SecretKeySpec skeySpec;
    static SecretKeySpec spec;
    static Cipher fileCipher;
    public DES(){
    Provider sunJce = new com.sun.crypto.provider.SunJCE();
    Security.addProvider(sunJce);
    try {
    Security.addProvider(new com.sun.crypto.provider.SunJCE());
    KeyGenerator keyGen = KeyGenerator.getInstance(ENCRYPTION_TYPE);
    keyGen.init(KEY_SIZE);
    ObjectInputStream in = new ObjectInputStream(new FileInputStream("c:/des.key"));
    SecretKey bfSKey = (SecretKey)in.readObject();
    byte[] raw = bfSKey.getEncoded();
    skeySpec = new SecretKeySpec(raw, ENCRYPTION_TYPE);
    } catch (Exception e) {
    e.printStackTrace();
    public void encrypt(String fileName, String fileNameTo) throws Exception {
    byte[] encryptedText;
    BufferedReader d
    = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
    StringBuffer line = new StringBuffer("");
    String lines = "";
    while((lines = d.readLine()) !=null){
         line.append(lines);
    fileCipher = Cipher.getInstance(ENCRYPTION_TYPE);
    fileCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    encryptedText = fileCipher.doFinal(line.toString().getBytes());
    FileOutputStream out = new FileOutputStream(fileNameTo);
    out.write(encryptedText);
    System.out.println("Done");
    public String encryptMessage(String textToEncrypt, String fileNameTo) throws Exception {
    byte[] encryptedText;
    fileCipher = Cipher.getInstance(ENCRYPTION_TYPE);
    fileCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    encryptedText = fileCipher.doFinal(textToEncrypt.getBytes());
    FileOutputStream out = new FileOutputStream(fileNameTo);
    out.write(encryptedText);
    System.out.println("Done");
    return fileNameTo;
    public String encryptMessage(String textToEncrypt) throws Exception {
    byte[] encryptedText;
    fileCipher = Cipher.getInstance(ENCRYPTION_TYPE);
    fileCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    encryptedText = fileCipher.doFinal(textToEncrypt.getBytes());
    System.out.println("Done");
    return new String(encryptedText);
    public String decrypt(String fileName) throws Exception {
    byte[] decryptedText;
    fileCipher = Cipher.getInstance(ENCRYPTION_TYPE);
    BufferedReader d
    = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
    StringBuffer line = new StringBuffer("");
    String lines = "";
    while((lines = d.readLine()) !=null){
         line.append(lines);
    System.out.println(line.length());
    byte[] theDecryptedText = line.toString().getBytes();
    fileCipher.init(Cipher.DECRYPT_MODE, skeySpec);
    decryptedText = fileCipher.doFinal(theDecryptedText);
    return new String(decryptedText);
    public static void main(String[] args) throws Exception {
    new DES();
    //new DES().encrypt("c:\\encr.txt", "C:\\Encr2.txt");
    new DES().encryptMessage("dsgfkdsfdsfudsagifugsadfuigsalidguflasgdfulagsdgfldsagfldsu", "C:\\Encr3.txt");
    System.out.println(new DES().decrypt("C:\\Encr3.txt"));
    } // end main
    } // end SourceViewer2

    That's because this byte[] encryptedText;
    encryptedText = fileCipher.doFinal(textToEncrypt.getBytes());
    return new String(encryptedText); is illegal. You cannot create a String out of any random binary array. Take a look at the API documentation of the String(byte[]) constructor. The only byte arrays you can construct a String out of are ones that conform to a supported encoding scheme, such as ASCII, UTF-8, etc. Cipher.doFinal() returns a byte array that does not conform to any encoding scheme. If you absolutely have to turn your encrypted byte array into a String, then you will need to use Base64 encoding. There is a Base64 encoding package to be found here: http://ostermiller.org/utils/Base64.html .
    HTH
    - Daniel

  • Decrypting PEM file using Triple DES

    Hi all,
    I am trying to decrypt a Triple DES encrypted RSAPrivateKey stored in PEM format in a file. How do I get the DES key to initialize the Cipher. I am using the following code to get the IV from the file and get the DES key using pass phrase. But I get the message
    java.lang.SecurityException: Unsupported keysize or algorithm parameters
    Can someone help me.
    Thanks in advance,
    Trilok.
    // Gets the IV params from the RSAPrivate key PEM file.
    // Uses the last 16 digits in this line to get the IV.
    // DEK-Info: DES-EDE3-CBC,4A90C209D3A81791
    private IvParameterSpec getIV(String s) { // here s = 4A90C209D3A81791
    byte[] ivBytes = new byte[8];
    for (int j=0; j<8; j++) {
    ivBytes[j] = (byte)Integer.parseInt(s.substring(j*2, j*2 + 2), 16);
    return new IvParameterSpec(ivBytes);
    private SecretKeySpec getSecretKey(byte [] pwd, byte [] iv)
    throws NoSuchAlgorithmException {
         byte[] keyMat = new byte[24];
         MessageDigest md = MessageDigest.getInstance("MD5");
         md.update(pwd);
         md.update(iv);
         byte[] data = md.digest();
         System.arraycopy(data, 0, keyMat, 0, 16);
         md.update(data);
         md.update(pwd);
         md.update(iv);
         data = md.digest();
         System.arraycopy(data, 0, keyMat, 16, 8);
         return new SecretKeySpec(keyMat, encAlg);
    }

    Hi trilok,
    Please let me know what JCE provider you are using for decrypting the Key.
    Please make sure that you have made the static or dynamic registration properly.
    For Static registration:
    Please go to JAVA_HOME/jre/lib/security/java.security
    Please edit
    security.provider.1=sun.security.provider.Sun
    For Dynamic Registration
    Security.addProvider(new com.sun.crypto.provider.SunJCE());
    Also please refer this URL, which is the third party provider which supports RSA.
    http://www.bouncycastle.org/latest_releases.html
    I hope this will help you.
    Thanks
    Bakrudeen
    Technical Support Engineer
    Sun MicroSystems Inc, India

  • Javax.crypto.BadPaddingException in DES encrypt/decrypt algorithm

    I am using DES algorithm, the default provided by J2ME to encrypt and decrypt some text. My problem is that I can encrypt the text but when I decrypt I get javax.crypto.BadPaddingException. I used a sample code from this forum I suppose and modified it to some extend.
    Here's the output -
    Plain Text :debayandas
    Cipher Text :Ɩ2&#65533;Ü°*Yð´4}&#65533;f¥
    Recovered Plain Text :javax.crypto.BadPaddingExceptionAnd here's the J2ME code -
    Declaration part:
    private boolean midletPaused = false;
            private static String algorithm = "DES";
         private static byte[] secretKey = {(byte) 0x2b, (byte) 0x7e, (byte) 0x15, (byte) 0x16,
                                                      (byte) 0x28, (byte) 0xae, (byte) 0xd2, (byte) 0xa6 };
         private static String secretKeyAlgorithm = "DES";
         private static byte[] iv = "DES".getBytes();
         private static byte[] plainText = null;
         private Key key = null;
         private static Cipher cipher = null;
         private static int ciphertextLength = 512;
            private static byte[] cipherText = new byte[ciphertextLength];
            private static int decryptedtextLength = 1024;
            private static byte[] decryptedText = new byte[decryptedtextLength];commandAction:
    public void commandAction(Command command, Displayable displayable) {                                              
            if (displayable == form) {                                          
                if (command == exitCommand) {                                        
                    exitMIDlet();                                          
                } else if (command == okCommand) {
                    plainText=textField.getString().getBytes();
                    encrypt();
                    decrypt();                                                        
        } Encrypt:
    public void encrypt()
                try
                    key = new SecretKeySpec(secretKey,0,secretKey.length,secretKeyAlgorithm);
              cipher = Cipher.getInstance(algorithm);
                    cipher.init(Cipher.ENCRYPT_MODE, key);
                    cipher.doFinal(plainText, 0, plainText.length, cipherText, 0);
              System.out.println("Plain Text :"+new String(plainText));
              System.out.println("Cipher Text :"+new String(cipherText));
                catch(Exception e)
                    System.out.println(""+e);
        }Decrypt:
    public void decrypt()
            try
    //            cipher = Cipher.getInstance(algorithm);
                cipher.init(Cipher.DECRYPT_MODE,key);
                cipher.doFinal(cipherText,0,cipherText.length,decryptedText,0);
                System.out.println("Recovered Plain Text :"+new String(decryptedText));
            catch(Exception e)
                System.out.println(""+e);
        }Where am I going wrong?

    debayandas wrote:
    I am using DES algorithm, the default provided by J2ME to encrypt and decrypt some text. My problem is that I can encrypt the text but when I decrypt I get javax.crypto.BadPaddingException. I used a sample code from this forum I suppose and modified it to some extend.How did you get DES in J2ME?
    I am asking as there isn't one default implementation in J2ME and as far as I am aware it is not included in any Configurations or Profiles of J2ME.
    You might be using [Bouncycastle library|http://www.bouncycastle.org/java.html] or any other third party implementation of DES, in which case please refer to the documentation of it to see in which methods throw BadPaddingException and in what circumstances, in order to pinpoint the problem.
    Daniel

  • Incorrect DES File Decryption

    I am using the following code to create an encrypted file. I am doing some research for my thesis and really only care about the encrypted file, however,
    I wanted to test the encrypted file by decrypting it. The decrypted file is never correct. So the million dollar question is "What am I doing wrong?"
    private static void encrypted(
                   FileInputStream inputFile, FileOutputStream outputFile)
              Cipher DESCipher;
              Cipher TestDESCipher;
              try
                   SecretKey desKey = getDESKey();
                   DESCipher = Cipher.getInstance("DES");
                   TestDESCipher = Cipher.getInstance("DES");
                   // Initialize the cipher for encryption
                   DESCipher.init(Cipher.ENCRYPT_MODE, desKey);
                   TestDESCipher.init(Cipher.DECRYPT_MODE, desKey);
                   CipherOutputStream desCipherStream = new CipherOutputStream(
                             outputFile, DESCipher);
                   byte[] b = new byte[8];
                   int i = inputFile.read(b);
                   while (i > 0)
                        if (debug)
                             System.out.write(b);
                        desCipherStream.write(b, 0, i);
                        i = inputFile.read(b);
                   inputFile.close();
                   desCipherStream.close();
                   outputFile.close();
                   // //////////////////////////////////////////start decrypt test
                   FileInputStream decInFile = new FileInputStream(
                             "C:\\Documents and Settings\\Walter\\My Documents\\AFIT\\Thesis Work\\Encryption Work\\Text\\DES\\text test.txt");
                   FileOutputStream decOutFile = new FileOutputStream(
                             "C:\\Documents and Settings\\Walter\\My Documents\\AFIT\\Thesis Work\\Encryption Work\\Text\\DES\\text test decrypted.txt");
                   CipherInputStream desDecryptCipherStream = new CipherInputStream(
                             decInFile, TestDESCipher);
                   byte[] c = new byte[8];
                   i = desDecryptCipherStream.read(c);
                   while (i > 0)
                        System.out.write(c);
                        decOutFile.write(c, 0, i);
                        i = desDecryptCipherStream.read(c);
                   decInFile.close();
                            desDecryptCipherStream.close();
                   decOutFile.close();
                   // ////////////////////////////////////////// end decrypt test
              catch (Exception e)
                   e.getMessage();
                   e.printStackTrace();
         }Here is the contents of the plaintext input file:
    This is an example.Here is the contents of the encrypted file:
    ��3���f�g�b`��C��3��8wHere is the contents of the decrypted file:
    �P�e�a�C�v,(���The program encrypted and decrypted the following correctly:
    bytes[] plaintext = "This is an example.".getBytes();But when I tried to put the text in a file and tried to use CipherOutputStream the problem arises.
    I've tried to use a single cipher that was reinitialized to DECRYPT, and I've tried to use two separate ciphers, but the results were the same.
    I know I am using the same key and padding scheme, so what is going wrong?

    <snip>
    My intent was not to upset you! I didn't want to
    clutter the forum with 500 lines of code that won't
    help to discover the problem. Which is exactly why you should provide a short testable example. I had to add about 20 lines of code to get your method testable.
    The main method simply
    sets up the FileInputStream and the FileOutputStream
    and passes them to the encryptDES method posted in
    the original post. Exactly so why did you not post one?
    The getDESKey is just
    an abstraction for KeyGenerator, however, the key is
    stored in desKey variable and passed to both init
    methods, so I am assuming the key is not
    the issue, but here is the getDESKey method just in
    case.I agree.
    >
    private static final SecretKey getDESKey()
    throws NoSuchAlgorithmException,
    on, NoSuchPaddingException
              byte[] key = new byte[8];
    KeyGenerator desKeyGen =
    = KeyGenerator.getInstance("DES");
              SecretKey desKey = desKeyGen.generateKey();
    return desKey;
    I'm running JRE 1.5.0_04 and am using Eclipse3.2.1
    for Windows XP.
    So you are able to encrypt and decrypt from and
    to a
    file? Have your tried more complicated files? What is a 'more complicated' file?
    A 'more complicated' file is one containing more then
    just the simple phrase "This is an example." as
    stated in the
    original post.  Presumably this would be a 3-4 Kb
    text file.  Thus a file where the encryption
    algorithm would span
    several hundred blocks.My test file was about 10 KBytes so about 1,200 blocks.
    >
    >>>
    Assuming the code is working fine for you, thenwhat
    would prevent it from working for me?I have no real idea! That is why you need tocreate
    a test harness that shows exactly how you areusing
    it. One possibility is that your getDESKey()
    method
    returns a different key value each time it is
    called
    but without seeing the rest of your code how am I
    to
    know.
    You are correct, the getDESKey() does return a
    different key, but that is how I designed it. As
    stated earlier, this
    method is only called once and the results are stored
    in a local variable. OK.
    >
    I would be more than happy to send you a zip file
    containing the .java file and the file structure so
    you can
    further analysis the code. I just didn't see a way
    to attach a file to a post, so you can email me at
    [email protected] and I'll reply with the
    attached zip file.It is not a good idea to publish your email address on a public forum.
    >
    There was one thing I noticed that needed fixingbut
    it did does not cause a problem with encryptingand
    decrypting and that is that
    System.out.write(c);             
    decOutFile.write(c, 0, i);needs changing to
    System.out.write(c, 0, i);
    decOutFile.write(c, 0, i);but this will only show a problem with yourprintout,
    not your decrypted file. You did check the contentof
    the decrypted file didn't you?The System.out.write(c) will write the full
    length of the byte array to the output stream and is
    only being used for
    debugging purpose. So the System.out.write(c, 0,
    i) will prevent a repeat of old data from being
    printed out,
    but since this is not going to the output file it
    shouldn�t be causing any problems. Which is what I said but it does present an opportunity to misinterpret the output.
    >
    Yes I did check the decrypted file. In fact, the
    contents of each file were listed in the original
    post. What good is the ASCII of the encrypted data without knowledge of the the key used and the character code used to convert the encrypted bytes to a String.
    >
    Come on give me a little credit, I did graduate with
    distinction with a Bachelor Degree in Computer
    Science,
    and I am pursuing a Master's Degree in Computer
    Science with an emphases in Software Engineering
    while
    maintaining a GPA > 3.5.There are aspects to your code that don't indicate such good qualifications. For example, your encryption method takes a FileInputStream and a FileOuputStream. As part of a 'design to interface' policy I would expect these to be InputStream and OutputStream. Also, I would not expect you to close the OutputStream because the encryption method did not create the OutputStream and outside of the encryption method the user may want to provide a prefix and a suffix. This is what I do with RSA where my prefix is an IV and the RSA encrypted symetric key and the suffix is a hash.
    Also, I assume you know that it is very important to design for testability so I would have expect you to provide the test harness for this method. In this way you would not have has to post 500 lines.
    >
    And your credentials speak for themselves.I agree! I am one of life's 'has beens'. My MSc is now 34 years old and not worth the paper the certificate is printed on.

  • How to implement DES encryption and decryption in j2sdk1.3

    Does j2sdk1.3 API support DES encryption and decryption or any third-party library support it???
    thx a lot

    Read old posts, or the JCE docs.

  • Error in running encryption/decryption using DES in Websphere Dev't Client

    Hello!
    I have a code used to encrypt / decrypt a string (password). I have already tested it using Netbeans and it is working. But when I tried to add the java code to an existing web project using Websphere Development Client,, javax.crypto.* is not recognized. Then I imported JCE.jar.
    The java code contains no errors then, but when I started to run the project, it gives an Error 500. And below is the Console's error message:
    E SRVE0026E: [Servlet Error]-[javax.crypto.spec.PBEKeySpec: method <init>&#40;[C[BI&#41;V not found]: java.lang.NoSuchMethodError: javax.crypto.spec.PBEKeySpec: method <init>([C[BI)V not found[/b]
    Have I missed something to add? Or other things that I should do upon importing this jar file?
    Please help.
    Advance thanks for your reply.
    misyel

    I dont know what version of Java that my Websphere's using. But I am very sure that it is outdated. I am using Websphere 5.0. For Netbeans, it is JDK1.5.
    I imported the JCE from JDK 1.5 on Websphere.
    I think the code works perfectly fine. Actually it was my friend's code for encryption but they are using Eclipse for development (almost the same from Websphere but somehow different from it.)
    My idea is that I cant match the versions of the jarfiles used in my project. As much as I wanted to change the imported jar files, I couldn't for when I replaced the existing jar files, more and more errors occur.
    can we have any alternative ways of importing the jar files? or is there any other code that might help that will not use the JCE.jar?
    I really appreciate your response. thanks
    misyel

Maybe you are looking for

  • TS3297 there was an error in the itunes store.  Please try again later

    I keep getting this error that there was an error in the itunes store.  Please try again later.  I don't seem to have problems downloading music when purchased.  Does anyone know how to stop this pop up. It's making me crazy. m-

  • Coloring a table cell with swing

    Hello, I am trying to write a java program in swing. Basically I am setting up a table and adding labels to the table's cells. Rather than displaying the label, the table is inserting the labels' string value. Here is a compilable example: import jav

  • Ef 4.0 working on Windows XP - not  Windows 7 (32 bit)

    Installed the ODAC112021.zip (for Entity Framework 4.0). A small demo app works on Windows XP, but not on a Windows 7 (32-bit, virtual PC). They both access the same Oracle 11 server. On the virtual Win 7 pc I get this error: Unhandled Exception: Sys

  • My pc locks up when I try to upgrade itunes software

    I can't remember what itunes version I was on (I think it was 6 something) and it asked me if I wanted to upgrade to the newest version. I agreed to upgrade and it started downloading the upgrade, but it locked up my pc when it was copying the instal

  • Why doesn't my imbedded video play on iPad?

    Why doesn't my imbedded video play on iPad?