Need to encrypt string in ColdFusion and Decrypt in Flex

My company is developing a standalone, offline Flex/AIR application. When users of the Flex/AIR app. want to activate the application, we will send them an activation file that contains an encrypted string. The string will hold the unique set-up data for the specific copy of the Flex/AIR app. The activation file will need to be generated on our central system which is written in ColdFusion. The Flex/AIR application must read the file and decrypt the string.
Are there any encryption/decryption options that are compatible with ColdFusion 8 and Flex 4?
Thanks.
P.S. The Flex/AIR app. runs offline, so I am not referring to encryption of communications between a ColdFusion server and Flex.

srikanth n wrote:
> Can anybody help me to resolve this issue.
>
> Thanks in advance.
>
>
My first thought is CF's list functions. You can declare any
character(s) you want to be a list delimiter. In you example
I would
use '-' and 'x' as the delimiter. A couple of examples.
<cfset phoneString = '123-456-7890 x1234'>
<cfset delimList = '-x '>
<cfoutput>
Areacode: #listFirst(phoneString,delimList)#<br/>
Exchange: #listGetAt(phoneString,2,delimList)#<br/>
Number: #listGetAt(phoneString,3,delimList)#<br/>
Extension: #listLast(phoneString,delimList)#
</cfoutput>

Similar Messages

  • 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

  • MS ACCESS, ColdFusion and Image Problems

    I have done this before using PHP and Mysql and it was pretty
    simple. I now need to do this in ColdFusion and MS Access 2003.
    I want to store logos in a database. After reading up on it,
    I found that you store images in Access using the OLE Object
    Datatype - done. Now the real fun part starts.
    I am trying now to display these logos from the MS Access
    2003 database onto a webpage using Coldfusion. I have looked into
    it, and one article suggested using the BLOB type - which is what
    you do in MySQL, but in MS Access that option is not available. So
    I looked into it somemore, and it seems that there are three
    functions that you need to use, and they are in Visual Basic -
    provided in part by Microsoft, but it seems EXTREMELY way too
    complicated for simply displaying an image staored in a Database.
    Has anyone been able to store and display images using MS
    Access and Coldfusion before? If so, could you guide me?

    The reason for storing the image in the database is that our
    company wants it that way for portability reasons. Filenames
    change, directories get lost when moving from one system to
    another. Databases are easier to backup and are more efficient when
    it comes to searching metadata. We have over 300 logos we must
    store for our different organizations - having a directory for each
    is complicated.
    Has anyone had issues like this with Coldfusion and MS
    Access? If so could you guide me?
    -Thanks

  • 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]

  • Byte to String conversion for encryption and decryption

    Hi Friends ,
    I am trying to encrypt a password string and then decrypt it .
    The thing is i need to convert the encrypted String which is a byte array to a string . While decrypting i need to convert the encrypted string to a Byte .
    I tried using String.getBytes() for converting a string to byte array , but this is giving an exception
    javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipherPlease find below my code
    import java.security.Key;
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import sun.misc.BASE64Encoder;
    import sun.misc.BASE64Decoder;
    * @author rajeshreddy
    public class Encrypt
        public static void main(String[] args)
            try
            BASE64Encoder en = new BASE64Encoder();
            BASE64Decoder en1 = new BASE64Decoder();
                String password = "S_@!et";
                KeyGenerator kg = KeyGenerator.getInstance("DESede");
                Key key = kg.generateKey();
                Cipher cipher = Cipher.getInstance("DESede");
                cipher.init(Cipher.ENCRYPT_MODE, key);
                // Encrypt password
                byte[] encrypted = cipher.doFinal(password.getBytes());
                String e = new String(encrypted);
                byte[] toDecrypt  = e.getBytes();
                // Create decryption cipher
                cipher.init(Cipher.DECRYPT_MODE, key);
                byte[] decrypted = cipher.doFinal(toDecrypt);
                // Convert byte[] to String
                String decryptedString = new String(decrypted);
                System.out.println("password: " + password);
                System.out.println("encrypted: " + encrypted);
                System.out.println("decrypted: " + decryptedString);
            } catch (Exception ex)
                ex.printStackTrace();
    }I cab use sun.misc.BASE64Decoder and sun.misc.BASE64Encoder which avoids this error, but this packages are sun proprietery packages so there is a chance of removing these in future releases.
    Please suggest me the best way to tackle this

    1) The "Jakarta Commons Codec" project has Base64 and Hex encoders that are well tested and well regarded. Google is your friend.
    2) Since this is a new project, you should use AES rather than DESede.
    3) The defaults when generating the Cipher object using
    Cipher cipher = Cipher.getInstance("DESede");
                is for ECB block mode with PKCS5 padding. ECB is not a good block mode since it allows some limited forgery though splicing of ciphertext. Use one of the feedback modes such as CBC.
    4) Why are you encrypting passwords rather than just hashing them? While there are situations where encryption rather than hashing is required, it is not the norm and does normally require justification.
    5) Converting encrypted or hashed data to a String is not normally required. What are you doing with that requires this?
    Edited by: sabre150 on Dec 29, 2008 7:44 AM

  • Help needed in encrypting and decrypting a file

    Hello,
    I just started looking into the Java Security.I need to encrypt a file using any popular alogrithm like RSA or DES and write it to disk.and again decrypt this file at a later time when needed.
    I was checking out with different ways of doing so,but found it difficult to persist the key some where.
    Could some one help me in this regard,with a tutorial or a sample program where I will be able to give cleartext file as an input and get a ciphered text file as output and vice versa?

    Probably the simplest solution is to use password-based encryption (PBE). See http://java.sun.com/j2se/1.5.0/docs/guide/security/CryptoSpec.html#PBEEx
    for an example.

  • Problem in encryption and decryption

    hello everyone..
    I'm a new bee in this forum.I don't know weather it is the right place to put my query or some other place.I saw in this forum people putting up their problems regarding the java development.So i came up with my problem.
    I'm working on a web application using jdk1.5,struts 1.1,apache tomcat5.5 and mysql5.2.For user registering and loging i'm using a encryption /decryption code to encrypt the password to the database and decrypt it back during userid and password verification in the code.The code of the encryption/decryption is as follows...
    import java.util.Random;
    public class Crypt
         String key = "uy67jwq98JWPOI99dj9021032amiet";
         public String strencrypt(String str)
              String result="";
              int i = 0, current = 0;
              Random r = new Random();
              current = r.nextInt(30);
              if(current<10)     result = "0";
              result = result + current;
              if(((key.charAt(current)+ "").hashCode() + str.length()) < 10)
                   result = result + "0";
              result = result + (char)((key.charAt(current)+ "").hashCode() + str.length());
              while(i<str.length())
                   result = result + ( (char)( ((str.charAt(i)+"").hashCode()) + ((key.charAt(current++)+"").hashCode()) ) );
                   if(current==key.length())     current=0;
                   i++;
              while(i<key.length())
                   result = result + ( (char) ((r.nextInt(30)) + ((key.charAt(current++)+"").hashCode())) );
                   if(current==key.length())     current=0;
                   i++;
              return result;
         public String strdecrypt(String str)
              int current=0, len = 0, i = 0, header = 3;
              String result="", slen = "";
              current = Integer.parseInt(str.substring(0,2));
              slen = "" + (str.charAt(2)+"").hashCode();
              len = (Integer.parseInt(slen)) - ((key.charAt(current)+"").hashCode());
              i = header;
              while(i<(header + len))
                   result = result + ( (char) ((str.charAt(i)+ "").hashCode() - ((key.charAt(current++)+"").hashCode())) );
                   if(current == key.length())
                   current=0;
                   i++;
              return result;
    But the problem that i'm facing is regarding the the database mysql5.2 is installed in two operating system ie windows xp and windows 2000 server.When i try to connect my web application to the windows xp installed database mysql5.2 and try creating a new user and then try to login ,the loging fails.Even i have found out the reason.The above pasted code couldn't decrypt properly.Heres what i get when i System.out.println(""); the data retrived from the database...I'm pasting it also...
    s retriving from db=16l&#9574;&#9616;&#8976;?��??7pmofv??A?l?rNCdhhLAK
    password coming from welcome.jsp=gtplpune
    c.strencrypt(password)=14A��&#9560;&#9555;&#8976;��?LH7}?te???HG&#8962;??QFUkPj]
    c.strdecrypt(s)=gtp&#9788;pu&#9788;&#9792;
    encryption mismatch
    see that teh password coming from welcome/jsp is gtplpune
    and the password after decryption comingh from database is gtp&#9788;pu&#9788;&#9792;....
    where u can see some letter such as l,n,e could not be decrypted or in some other format....So the code is unable to validate teh user.....
    But teh strange thing is that when i'm using the mysql5.2 installed in windows 2000 server everything seems to work fine.There no problem in encryption or decryption and everything works fine...So anyone of you have any idea what can be the raeson for it.And what can be the probable solution to it.I'm waiting for ur replies which i guess will help me out.
    Thank you
    sabyasachi

    It's a shame nobody above gave you the correct.
    answer.
    You shouldn't encrypt passwords and store them in a
    database at all..
    You should digest them and store the digests,
    and digest whatever the user enters in the password
    field and compare the digests.
    The way you have it now is a major security
    problem.
    Hey i didn't know this..I encrypted the password in base 64 format and then store it in mysql db..then i retrive it frm db in encrypted format and then decrypt it and then match it when the user logs in..well thanks for ur approach..i will now try using the digest as u mentioned..well i'm not aware of it so i need to study this first...

  • Newbie need to encrypt/decrypt using password

    Hi all,
    I need to encrypt some data store it in database and retrieve it at another time and decrypt it. The user will supply the password. I have no idea on how to do it. This encryption must be very strong like PGP. I can use the jars provided by Sun.
    rgds
    Antony Paul

    package login.view;
    import java.io.UnsupportedEncodingException;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    //import org.myorg.SystemUnavailableException;
    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;
    import sun.misc.CharacterEncoder;
    public final class PasswordService
    private static PasswordService instance;
    private PasswordService()
    public synchronized String encrypt(String plaintext) throws Exception
    MessageDigest md = null;
    try
    md = MessageDigest.getInstance("SHA"); //step 2
    catch(NoSuchAlgorithmException e)
    throw new Exception(e.getMessage());
    try
    md.update(plaintext.getBytes("UTF-8")); //step 3
    catch(UnsupportedEncodingException e)
    throw new Exception(e.getMessage());
    byte raw[] = md.digest(); //step 4
    String hash = (new BASE64Encoder()).encode(raw); //step 5
    return hash; //step 6
    public static synchronized PasswordService getInstance() //step 1
    if(instance == null)
    return new PasswordService();
    else
    return instance;
    You can use this classas below.................
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    HttpSession session=request.getSession(true);
    //HttpSession session = new HttpSession();
    LoginBean login =(login.view.LoginBean) form;
    String LoginName= login.getLoginName();
    String LoginPassword = login.getLoginPassword();
    try
    session.setAttribute("LoginPassword",PasswordService.getInstance().encrypt(LoginPassword));
    catch(Exception e)
    session.setAttribute("LoginName",LoginName);
    return mapping.findForward("success");
    }

  • Problem in using socket streams with encryption and decryption

    Hi,
    I am developing a client/server program with encryption and decryption at both end. While sending a message from client it should be encrypted and at the receiving end(server) it should be decrypted and vice versa.
    But while doing so i got a problem if i use both encryption and decryption at both ends. But If i use only encryption at one (only outputstream) and decryption at other end(only inputstream) there is no problem.
    Here is client/server pair of programs in which i am encrypting the outputstream of the socket in client side and decrypting the inputstream of the socket in server side.
    serverSocketDemo.java
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.util.*;
    import java.util.zip.*;
    class serverSocketDemo
         public static void main(String args[])
              try
              {                    //server listening on port 2000
                   ServerSocket server=new ServerSocket(2000);
                   while (true)
                        Socket theConnection=server.accept();
                        System.out.println("Connecting from local address : "+theConnection.getLocalAddress());
                        System.out.println("Connection request from : "+theConnection.getInetAddress());
                        //Input starts from here
                        Reader in=new InputStreamReader(getNetInStream(theConnection.getInputStream()),"ASCII");
                        StringBuffer strbuf=new StringBuffer();
                        int c;
                        while (true)
                             c=in.read();
                             if(c=='\n' || c==-1)
                                  break;
                             strbuf.append((char)c);     
                        String str=strbuf.toString();
                        System.out.println("Message from Client : "+str);
                        in.close();               
                        theConnection.close();
              catch(BindException e)
                   System.out.println("The Port is in use or u have no privilage on this port");
              catch(ConnectException e)
                   System.out.println("Connection is refused at remote host because the host is busy or no process is listening on that port");
              catch(IOException e)
                   System.out.println("Connection disconnected");          
              catch(Exception e)
         public static BufferedInputStream getNetInStream(InputStream in) throws Exception
              // register the provider that implements the algorithm
              Provider sunJce = new com.sun.crypto.provider.SunJCE( );
              Security.addProvider(sunJce);
              // create a key
              byte[] desKeyDataDec = "This encryption can not be decrypted".getBytes();
              DESKeySpec desKeySpecDec = new DESKeySpec(desKeyDataDec);
              SecretKeyFactory keyFactoryDec = SecretKeyFactory.getInstance("DES");
              SecretKey desKeyDec = keyFactoryDec.generateSecret(desKeySpecDec);
              // use Data Encryption Standard
              Cipher desDec = Cipher.getInstance("DES");
              desDec.init(Cipher.DECRYPT_MODE, desKeyDec);
              CipherInputStream cin = new CipherInputStream(in, desDec);
              BufferedInputStream bin=new BufferedInputStream(new GZIPInputStream(cin));
              return bin;
    clientSocketDemo.java
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.util.*;
    import java.util.zip.*;
    class clientSocketDemo
         public static void main(String args[])
              try
                   Socket theConnection=new Socket("localhost",2000);
                   System.out.println("Connecting from local address : "+theConnection.getLocalAddress());
                   System.out.println("Connecting to : "+theConnection.getInetAddress());
                   //Output starts from here               
                   OutputStream out=getNetOutStream(theConnection.getOutputStream());
                   out.write("Please Welcome me\n".getBytes());
                   out.flush();
                   out.close();
                   theConnection.close();
              catch(BindException e)
                   System.out.println("The Port is in use or u have no privilage on this port");
              catch(ConnectException e)
                   System.out.println("Connection is refused at remote host because the host is busy or no process is listening on that port");
              catch(IOException e)
                   System.out.println("Connection disconnected");          
              catch(Exception e)
         public static OutputStream getNetOutStream(OutputStream out) throws Exception
              // register the provider that implements the algorithm
              Provider sunJce = new com.sun.crypto.provider.SunJCE( );
              Security.addProvider(sunJce);
              // create a key
              byte[] desKeyDataEnc = "This encryption can not be decrypted".getBytes();
              DESKeySpec desKeySpecEnc = new DESKeySpec(desKeyDataEnc);
              SecretKeyFactory keyFactoryEnc = SecretKeyFactory.getInstance("DES");
              SecretKey desKeyEnc = keyFactoryEnc.generateSecret(desKeySpecEnc);
              // use Data Encryption Standard
              Cipher desEnc = Cipher.getInstance("DES");
              desEnc.init(Cipher.ENCRYPT_MODE, desKeyEnc);
              CipherOutputStream cout = new CipherOutputStream(out, desEnc);
              OutputStream outstream=new BufferedOutputStream(new GZIPOutputStream(cout));
              return outstream;
    Here is client/server pair in which i use both encrypting outpustream and decrypting inputstream at both ends.
    serverSocketDemo.java
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.util.*;
    import java.util.zip.*;
    class serverSocketDemo
         private Cipher desEnc,desDec;
         serverSocketDemo()
              try
                   // register the provider that implements the algorithm
                   Provider sunJce = new com.sun.crypto.provider.SunJCE( );
                   Security.addProvider(sunJce);
                   // create a key
                   byte[] desKeyData = "This encryption can not be decrypted".getBytes();
                   DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
                   SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
                   SecretKey desKey = keyFactory.generateSecret(desKeySpec);
                   desEnc = Cipher.getInstance("DES");
                   desEnc.init(Cipher.ENCRYPT_MODE, desKey);
                   desDec = Cipher.getInstance("DES");
                   desDec.init(Cipher.DECRYPT_MODE, desKey);               
              catch (javax.crypto.NoSuchPaddingException e)
                   System.out.println(e);          
              catch (java.security.NoSuchAlgorithmException e)
                   System.out.println(e);          
              catch (java.security.InvalidKeyException e)
                   System.out.println(e);          
              catch(Exception e)
                   System.out.println(e);
              startProcess();
         public void startProcess()
              try
                   ServerSocket server=new ServerSocket(2000);
                   while (true)
                        final Socket theConnection=server.accept();
                        System.out.println("Connecting from local address : "+theConnection.getLocalAddress());
                        System.out.println("Connection request from : "+theConnection.getInetAddress());
                        Thread input=new Thread()
                             public void run()
                                  try
                                       //Input starts from here
                                       Reader in=new InputStreamReader(new BufferedInputStream(new CipherInputStream(theConnection.getInputStream(), desDec)),"ASCII");
                                       StringBuffer strbuf=new StringBuffer();
                                       int c;
                                       while (true)
                                            c=in.read();
                                            if(c=='\n'|| c==-1)
                                                 break;
                                            strbuf.append((char)c);     
                                       String str=strbuf.toString();
                                       System.out.println("Message from Client : "+str);
                                  catch(Exception e)
                                       System.out.println("Error caught inside input Thread : "+e);
                        input.start();
                        Thread output=new Thread()
                             public void run()
                                  try
                                       //Output starts from here
                                       OutputStream out=new BufferedOutputStream(new CipherOutputStream(theConnection.getOutputStream(), desEnc));
                                       System.out.println("it will not be printed");
                                       out.write("You are Welcome\n".getBytes());
                                       out.flush();
                                  catch(Exception e)
                                       System.out.println("Error caught inside output Thread : "+e);
                        output.start();
                        try
                             output.join();
                             input.join();
                        catch(Exception e)
                        theConnection.close();
              catch(BindException e)
                   System.out.println("The Port is in use or u have no privilage on this port");
              catch(ConnectException e)
                   System.out.println("Connection is refused at remote host because the host is busy or no process is listening on that port");
              catch(IOException e)
                   System.out.println("Connection disconnected");          
              catch(Exception e)
         public static void main(String args[])
              serverSocketDemo server=new serverSocketDemo();          
    clientSocketDemo.java
    import java.io.*;
    import java.net.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.util.*;
    import java.util.zip.*;
    class clientSocketDemo
         private Cipher desEnc,desDec;
         clientSocketDemo()
              try
                   // register the provider that implements the algorithm
                   Provider sunJce = new com.sun.crypto.provider.SunJCE( );
                   Security.addProvider(sunJce);
                   // create a key
                   byte[] desKeyData = "This encryption can not be decrypted".getBytes();
                   DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
                   SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
                   SecretKey desKey = keyFactory.generateSecret(desKeySpec);
                   desEnc = Cipher.getInstance("DES");
                   desDec = Cipher.getInstance("DES");
                   desEnc.init(Cipher.ENCRYPT_MODE, desKey);
                   desDec.init(Cipher.DECRYPT_MODE, desKey);               
              catch (javax.crypto.NoSuchPaddingException e)
                   System.out.println(e);          
              catch (java.security.NoSuchAlgorithmException e)
                   System.out.println(e);          
              catch (java.security.InvalidKeyException e)
                   System.out.println(e);          
              catch(Exception e)
                   System.out.println(e);
              startProcess();
         public void startProcess()
              try
                   final Socket theConnection=new Socket("localhost",2000);
                   System.out.println("Connecting from local address : "+theConnection.getLocalAddress());
                   System.out.println("Connecting to : "+theConnection.getInetAddress());
                   Thread output=new Thread()
                        public void run()
                             try
                                  //Output starts from here               
                                  OutputStream out=new BufferedOutputStream(new CipherOutputStream(theConnection.getOutputStream(), desEnc));
                                  out.write("Please Welcome me\n".getBytes());
                                  out.flush();
                             catch(Exception e)
                                  System.out.println("Error caught inside output thread : "+e);
                   output.start();     
                   Thread input=new Thread()
                        public void run()
                             try
                                  //Input starts from here
                                  Reader in=new InputStreamReader(new BufferedInputStream(new CipherInputStream(theConnection.getInputStream(), desDec)),"ASCII");          
                                  System.out.println("it will not be printed");
                                  StringBuffer strbuf=new StringBuffer();
                                  int c;
                                  while (true)
                                       c=in.read();
                                       if(c=='\n' || c==-1)
                                            break;
                                       strbuf.append((char)c);     
                                  String str=strbuf.toString();
                                  System.out.println("Message from Server : "+str);
                             catch(Exception e)
                                  System.out.println("Error caught inside input Thread : "+e);
                   input.start();
                   try
                        output.join();
                        input.join();
                   catch(Exception e)
                   theConnection.close();
              catch(BindException e)
                   System.out.println("The Port is in use or u have no privilage on this port");
              catch(ConnectException e)
                   System.out.println("Connection is refused at remote host because the host is busy or no process is listening on that port");
              catch(IOException e)
                   System.out.println("Connection disconnected");          
              catch(Exception e)
         public static void main(String args[])
              clientSocketDemo client=new clientSocketDemo();     
    **** I know that the CInput tries to read some header stuff thats why i used two threads for input and output.
    Waiting for the reply.
    Thank you.

    Do not ever post your code unless requested to. It is very annoying.
    Try testing what key is being used. Just to test this out, build a copy of your program and loop the input and outputs together. Have them print the data stream onto the screen or a text file. Compare the 1st Output and the 2nd Output and the 1st Input with the 2nd Input and then do a static test of the chipher with sample data (same data which was outputted), then do another cipher test with the ciphertext created by the first test.
    Everything should match - if it does not then follow the steps below.
    Case 1: IO Loops do not match
    Case 2: IO Loops match, but ciphertext 1st run does not match loop
    Case 3: IO Loops match, 1st ciphertext 1st run matches, but 2nd run does not
    Case 4: IO Loops match, both chiphertext runs do not match anything
    Case 5: Ciphertext runs do not match eachother when decrypted correctly (outside of the test program)
    Problems associated with the cases above:
    Case 1: Private Key is changing on either side (likely the sender - output channel)
    Case 2: Public Key is changing on either side (likely the sender - output channel)
    Case 3: Private Key changed on receiver - input channel
    Case 4: PKI failure, causing private key and public key mismatch only after a good combination was used
    Case 5: Same as Case 4

  • Are there any tools for data encryption and decryption ?

    Hi,
    i am using oracle 9i R2, i want encrypt my data. Are there any tools available in market.
    Please let me know the ways to do data encryption and decryption.
    Thanks in advance
    Prasuna.

    970489 wrote:
    using DBMS_OBFUSCATION_TOOLKIT.Encrypt /DESEncrypt we can't secure our password...So i am looking for an another alternative.As Blue Shadow said, what are you really trying to achieve?
    Encrypting a password is itself not secure. Anything that can be encrypted can be decrypted. That is why Oracle itself DOES NOT encrypt passwords.
    Surprised??
    Here's what Oracle does with passwords, and what others should be doing if they have to store them.
    When the password is created, the presented password - clear text - is concatenated with the username. The resulting character string is then passed through a one-way hashing function. It is that hashed value that is stored. Then when a user presents his credentials to log on to the system, the presented credentials are combined and hashed in the same manner as when the password was created, and the resulting hash value compared to the stored value.

  • Encrypt in javascript and decrypt in java

    hi guys,
    iam in a strange situation, my requirement is to encrypt the user entered details thr javascript and decrypt in those in java.
    i need some ideas
    thanku

    Why don't you just use SSL? Then the entire communication is encrypted.

  • How do I protect my FLV files? or How to encrypt and decrypt FLV files using AIR?

    Hi,
         I am working on an AIR application, which is developed on eLearning concept. The application mainly deals with flv files. The application contains a video player component, which will stream flv files from an Apache Server and played in my application. Here my concern is I would like to protect my flv files some how against users who may stream them from Apache Server and use them without my application.
         I thought of with an idea to do it. But I don't know whether it will work or not. So I am requesting for your suggestions and better ways to do this with a sample.
    Here is my thought:
    I would like to place the encrypted FLV files at Apache Server side [ Need to know how to encrpt the FLV files using Flex]
    As my AIR application send a request for a FLV file, the Apache server should send the decryption key and a stream of FLV file.
    AIR application should take the decryption key, stream of flv file and it should capable enough to decrypt the FLV file and play it in my application. [ But I don't know how to encrypt/decrypt FLV files through flex]
    I can do encryption of FLV files using Mac Address of Apache Server system and using Java. But I don't know how can I decrypt the same FLV file ( Encrypted using Mac Address and java ) at AIR application side.
    So I would be greatfull If any body help me in encrypting and decrypting of FLV file with a sample using Flex 3.0.
    Thanks
    Sudheer Puppala

    russellfromblackburn south wrote:
    Is it because the portable drive is NTFS format and the Mac wont recognise this? If so what do I do?
    Yes, this is exactly what is causing the problem. Macs cannot write to NTFS formatted drives, only read. You must move the documents to the internal HDD/SSD of the Mac to be able to edit them.
    Or, since you say you don't want to move the documents to the internal storage, you'll need to format the external HDD as FAT32.

  • Trying to encrypt and decrypt localy

    here is what i am doing
    import javax.swing.JOptionPane;
    import java.io.*;
    import javax.crypto.Cipher;
    import javax.crypto.BadPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.KeyGenerator;
    import java.security.Key;
    import java.security.InvalidKeyException;
    public class LocalEncrypter
         private static String algorithm = "DESede";
    private static Key key = null;
    private static Cipher cipher = null;
    private static void setUp() throws Exception
    //this next line gets an instance of the algm to encypt and generates the key for it
         key = KeyGenerator.getInstance(algorithm).generateKey();
         //this next line creates a cipher obj for the algm.
    cipher = Cipher.getInstance(algorithm);
    public static void main(String[] args) throws Exception
         setUp();//generates key and create cipher
    FileOutputStream fos = new FileOutputStream("test.obj");
         ObjectOutputStream oos = new ObjectOutputStream(fos);
    byte[] encryptionBytes = null;
    String input = JOptionPane.showInputDialog( "enter message to encrypt");
    encryptionBytes = encrypt(input);//encyrption being performed
    oos.writeObject(encryptionBytes);
    oos.flush();
    oos.close();
    System.exit(0);
    //this method encrypts the string inputed
    private static byte[] encrypt(String input) throws InvalidKeyException,
    BadPaddingException,IllegalBlockSizeException
    cipher.init(Cipher.ENCRYPT_MODE, key);//initialized the cipher to encyption mode
    //key is used to know how to encypt
    byte[] inputBytes = input.getBytes();//gets the byte array from the sting inputed
    inputBytes = cipher.doFinal(inputBytes);//create the ciphered byte array
    return inputBytes;//returns the byte array
    //////////////////other class
    import javax.swing.JOptionPane;
    import java.io.*;
    import javax.crypto.Cipher;
    import javax.crypto.BadPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.KeyGenerator;
    import java.security.Key;
    import java.security.InvalidKeyException;
    public class LocalDecrypter
         private static String algorithm = "DESede";
    private static Key key = null;
    private static Cipher cipher = null;
    private static void setUp() throws Exception
    //this next line gets an instance of the algm to encypt and generates the key for it
         key = KeyGenerator.getInstance(algorithm).generateKey();
         //this next line creates a cipher obj for the algm.
    cipher = Cipher.getInstance(algorithm);
    public static void main(String[] args) throws Exception
         setUp();//generates key and create cipher
    FileInputStream fis = new FileInputStream("test.obj");
         ObjectInputStream ois = new ObjectInputStream(fis);
    byte[] dencryptionBytes = null;
    dencryptionBytes = (byte [])ois.readObject();
    ois.close();
    for(int i=0 ; i < dencryptionBytes.length;i++)
    System.out.print(dencryptionBytes);
    System.out.println();
    String s = decrypt(dencryptionBytes);
    System.out.println(s);
    System.exit(0);
         //this method decyprts the string inputed.
    private static String decrypt(byte[] encryptionBytes) throws InvalidKeyException,
    BadPaddingException,IllegalBlockSizeException
    cipher.init(Cipher.DECRYPT_MODE, key);//initialze the cipher to decyption
    //key is used to know how to decrypt.
    byte[] recoveredBytes = cipher.doFinal(encryptionBytes);//recover the cipher text
    String recovered = new String(recoveredBytes);//create a string from the byte []
    return recovered;//return the new deciphered string.
    I encrypt fine but here is my error now i know for sure that this would work if i was using sockets cause the streams would be piped and set ok cause of tcp protocol.
    but saving it in a file or writing the object this exception occurs.
    any help guys
    C:\Documents and Settings\jimmy\Desktop\cipher>java LocalDecrypter
    -6052-5-39-33-412693
    Exception in thread "main" javax.crypto.BadPaddingException: Given final block n
    ot properly padded
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.DESedeCipher.engineDoFinal(DashoA6275)
    at javax.crypto.Cipher.doFinal(DashoA6275)
    at LocalDecrypter.decrypt(LocalDecrypter.java:56)
    at LocalDecrypter.main(LocalDecrypter.java:42)

    (your original classes with Base64 and key sharing funtionality added:)
    // ***************************************** ENCRYPT ********************************************** //
    import javax.swing.JOptionPane;
    import java.io.*;
    import javax.crypto.Cipher;
    import javax.crypto.BadPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import java.security.InvalidKeyException;
    import sun.misc.BASE64Encoder;
    import sun.misc.BASE64Decoder;
    public class LocalEncrypter {
         private static String algorithm = "DESede";
         private static SecretKey key = null;
         private static Cipher cipher = null;
         private static void setUp() throws Exception {
              //this next line gets an instance of the algm to encypt and generates the key for it
              key = KeyGenerator.getInstance(algorithm).generateKey();
              //this next line creates a cipher obj for the algm.
              cipher = Cipher.getInstance(algorithm);
         private static void saveKey(String filename) throws Exception {
              byte[] byteSeed = key.getEncoded();
              BASE64Encoder encoder = new BASE64Encoder();
              String seed = encoder.encodeBuffer(byteSeed);
              FileWriter fw = new FileWriter(filename);
              fw.write(seed);
              fw.close();          
         public static void main(String[] args) throws Exception {
              setUp();//generates key and create cipher
              FileOutputStream fos = new FileOutputStream("test.obj");
              ObjectOutputStream oos = new ObjectOutputStream(fos);     
              byte[] encryptionBytes = null;
              String input = JOptionPane.showInputDialog( "enter message to encrypt");
              encryptionBytes = encrypt(input);//encyrption being performed
              oos.writeObject(encryptionBytes);
              oos.flush();
              oos.close();
              saveKey("key.txt");
              System.exit(0);
         //this method encrypts the string inputed
         private static byte[] encrypt(String input) throws Exception {
              cipher.init(Cipher.ENCRYPT_MODE, key);//initialized the cipher to encyption mode
              //key is used to know how to encypt
              byte[] inputBytes = input.getBytes();//gets the byte array from the sting inputed
              inputBytes = cipher.doFinal(inputBytes);//create the ciphered byte array
              BASE64Encoder encoder = new BASE64Encoder();
              String ciphertextB64 = encoder.encodeBuffer(inputBytes);
              return ciphertextB64.getBytes();//returns the byte array
    // ***************************************** DECRYPT ********************************************** //
    import javax.swing.JOptionPane;
    import java.io.*;
    import javax.crypto.Cipher;
    import javax.crypto.BadPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import java.security.InvalidKeyException;
    import sun.misc.BASE64Decoder;
    public class LocalDecrypter {
         private static String algorithm = "DESede";
         private static SecretKey key = null;
         private static Cipher cipher = null;
         private static SecretKey loadKey(String filename) throws Exception {
              FileInputStream fis = new FileInputStream(filename);
              byte[] encKey = new byte[fis.available()];
              fis.read(encKey);
              fis.close();
              String seed = new String(encKey);
              BASE64Decoder decoder = new BASE64Decoder();
              byte[] byteSeed = decoder.decodeBuffer(seed);
              SecretKey myKey = new SecretKeySpec(byteSeed, algorithm);
              return myKey;
         private static void setUp() throws Exception {
              //this next line creates a cipher obj for the algm.
              cipher = Cipher.getInstance(algorithm);
         public static void main(String[] args) throws Exception {
              setUp();//generates key and create cipher
              key = loadKey("key.txt");
              FileInputStream fis = new FileInputStream("test.obj");
              ObjectInputStream ois = new ObjectInputStream(fis);
              byte[] dencryptionBytes = null;
              dencryptionBytes = (byte [])ois.readObject();
              ois.close();
              for(int i=0 ; i < dencryptionBytes.length;i++)
                   System.out.print(dencryptionBytes);
                   System.out.println();
                   String s = decrypt(dencryptionBytes);
                   System.out.println(s);
                   System.exit(0);
              //this method decyprts the string inputed.
              private static String decrypt(byte[] encryptionBytesB64) throws Exception {
              BASE64Decoder decoder = new BASE64Decoder();
              byte[] encryptionBytes = decoder.decodeBuffer(new String(encryptionBytesB64));
              cipher.init(Cipher.DECRYPT_MODE, key);//initialze the cipher to decyption
              //key is used to know how to decrypt.
              byte[] recoveredBytes = cipher.doFinal(encryptionBytes);//recover the cipher text
              String recovered = new String(recoveredBytes);//create a string from the byte []
              return recovered;//return the new deciphered string.

  • 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

  • Encrypt and Decrypt

    please help... i have this...
    main.cfm (test only)
    <cfset txtuserid = 123>
    <p> <A HREF = "test.cfm?txtuserid=<cfoutput>#URLEncodedFormat(Encrypt(txtuserid, "#txtuserid#"))#</cfoutput>">Click me</A>
    once you click the click me
    the url become: http://localhost/newl/main2.cfm?txtuserid=%25%2F5%3BW%5E%3C4%20%0A >>> so its working
    but once the test.cfm comes
    the output of the txtuserid instead of 123
    txtuserid is e P1
    i need the txtuserid be 123
    here's my sample code at main2.cfm
    <cfset txtuserid1 = #Decrypt(txtuserid, "#txtuserid#")#>
    <cfoutput>#txtuserid1#</cfoutput>
    thanks!!!

    In encryption
      Encrypt(txtuserid, "#txtuserid#")
    1st parameter is String to encrypt.
    2md parameter is  Key or seed used to encrypt the string.
    In decription
    encrypted_string
    String or a variable that contains one. String to decrypt
    seed
    String. The 32-bit key that was used to encrypt the string.
    main.cfm (test only)
    <cfset txtuserid = 123>
    <p> <A HREF = "test.cfm?txtuserid=<cfoutput>#URLEncodedFormat(Encrypt(txtuserid, "#txtuserid#"))#</cfoutput>">Click me</A>
    here key for encryption is 'txtuserid ' (123)
    so for decription same key must be used for encryption
    main2.cfm
    <cfset txtuserid1 = #Decrypt(txtuserid, "#txtuserid#")#>
    <cfoutput>#txtuserid1#</cfoutput>
    here the value of  txtuserid ie the 2nd parameter is the key for decryption that was not the same key for u used 4encryption .u have to use the same key for decryption also. if u change
    main2.cfm
    <cfset txtuserid1 = #Decrypt(txtuserid, "123")>
    <cfoutput>#txtuserid1#</cfoutput>
    u will get the answer as 123.
    Plz try this example below.. then u will get the IDEA
    main.cfm (test only)
    <cfset txtuserid = 123>
    <cfset key="key1">
    <p> <A HREF = "test.cfm?txtuserid=<cfoutput>#URLEncodedFormat(Encrypt(txtuserid, "#key#"))#</cfoutput>">Click me</A>
    main2.cfm
    <cfset key="key1">
    <cfset txtuserid1 = Decrypt(txtuserid, "#key#")>
    <cfoutput>#txtuserid1#</cfoutput>

Maybe you are looking for

  • Error 1 occurred when tried to install Flash Builder on Windows 8.  No files to uninstall.  Caught in loop

    I need to install Flash Builder 4.7 on my windows 8 computer.  I started the install process, but was soon stopped due to error 1.  The software wants me to uninstall/reinstall the software.  there is no program installed on the computer.  Cannot fin

  • How to a read an R/3 table while creating a CRM sales order.

    Hi! The problem is that I need to have the route field in CRM orders determined automatically during sales order creation. As CRM doesn't have the route determination in customizing, nor any route information, except the field route (with no possible

  • UVerse and E4200 v1

    I have my e4200 connected behind my Uverse RG (3801HGV).  It is connected properly following instructions at post 2 from: http://forums.att.com/t5/Residential-Gateway/U-verse-for-BUSINESS-2Wire-3600HGV-bridge-mode-or-anoth... I have had to turn off t

  • Assignment profit center on customer

    Hello, I want to know if it's possible to assign a profit center on customer and, when I create a post in customer order, this profit center is automatically entered in field "profit center" on tab "Account assignment" of the post data. I would there

  • Cumulative Balances in PCA Balance Sheet cube are not correct.

    Hi Could you please help me in sorting out this Issue. Cumulative Balances in PCA Balance Sheet cube are not correct. After doing a reconciliation my conclusions are: Opening balance for 2005 (fiscal period 009.2005) is not in BW Opening balance for