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.

Similar Messages

  • Encryption in javascript and how to decrypt in java

    Hi all,
    I have encrypted password entered by user in javascript using the code shown below and then how can i decrypt the password in java to move further.
    function Encrypt(theText) {
    alert("---");
    output = new String;
    Temp = new Array();
    Temp2 = new Array();
    TextSize = theText.length;
    for (i = 0; i < TextSize; i++) {
    rnd = Math.round(Math.random() * 122) + 68;
    Temp[i] = theText.charCodeAt(i) + rnd;
    Temp2[i] = rnd;
    for (i = 0; i < TextSize; i++) {
    output += String.fromCharCode(Temp, Temp2[i]);
    return output;
    thanks in advance.

    Could you please tell me which algorithm can i use can you suggest me with the code .
    My requirement is
    I want to encrypt password before submitting the form and then i want to pass the decrypted value into the scriptlets java code of same jsp could you please suggest me.

  • Re: encrypting in c#, decrypting in java

    Hello,
    I am trying to use RSA so I can encrypt in c# (encrypt a password) and decrypt it in my web service to check the password.
    But, I am having some problems when I try to read in the file with my private key. I am currently getting an error of: too much data for RSA block.
    I am using bouncycastle for the algorithms.
    Has anyone seen any example of encrypting in C# and decrypting in Java?
    Thanx.

    Your C# may be using padding without your knowledge...
    This is from the docs for C# RSACryptoServiceProvider:
    public byte[] Encrypt(
    byte[] rgb,
    bool fOAEP
    rgb The data to be encrypted
    fOAEP true to perform direct RSA encryption using OAEP padding (only available on a computer running Microsoft Windows XP or later); otherwise, false to use PKCS#1 v1.5 padding.
    It looks like Bouncy Castle's RSA can use either no padding or OAEP (please correct me if Im wrong,
    I couldnt find documentation for this). So you'll have to figure out how to sync the two up.

  • Encrypt  and Decrypt  function modules

    Hi
    Please tell the function module names to Encrypt the code with key and Decrypt code with key.
    i know these function module names
    'FIEB_PASSWORD_ENCRYPT' and 'FIEB_PASSWORD_DECRYPT'
    but its not working.
    Is there any other function modules?
    if it is not there please tell the documentation of the to create  encrypt function module and decrypt function module.
    Thanks.
    Edited by: Craig Cmehil on Jul 18, 2008 10:01 AM

    try this it will do little bit closer to encription and decription
    DATA:
    g_key TYPE i VALUE 26101957,
    g_slen TYPE i,
    g_pwd type string VALUE 'Pass1234',
    g_pwd1 type xstring ,
    obj type ref to cl_http_utility.
    CREATE OBJECT obj.
    CALL METHOD obj->if_http_utility~encode_utf8
      EXPORTING
        unencoded         = g_pwd
      receiving
        encoded           = g_pwd1
      EXCEPTIONS
        conversion_failed = 1
        others            = 2
    IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
               WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    CALL METHOD obj->if_http_utility~decode_utf8
      EXPORTING
        encoded           = g_pwd1
      receiving
        unencoded         = g_pwd
    EXCEPTIONS
       conversion_failed = 1
       others            = 2
    IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
               WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    write:/ g_pwd.

  • Parameters b/w javascript and JSp

    how i can pass values between javascript and jsp .
    ( java script varaible in the JSP part & jsp object in the javascript code )

    Since Java script is on the client side , to get the value of a java script variable into jsp, u have to set some form field variable and submit it to the server again. So, it can be something like:
    <script>
    function submit()
         var scriptVar = 12;
         document.form1.formVariable.value=scriptVar;
         document.form1.submit();
    </script>
    <%
    System.out.println("Script variable value = " +request.getParameter("formVariable"));
    %>
    <form name="form1" method="post">
    <input type="hidden" name="formVariable" value=""/>
    <input type="button" name="bSubmit" value="Submit" onclick="javascript:submit()" />
    </form>
    The first time this jsp is called, the value of formVariable will be null.
    The next time, when u click on submit button, the value will be 12.
    I have not tested this. There might be some syntax errors. Just try it out. Also, make sure that u don't end up submitting the form in an infinite loop by using the submit() generally in the script. Hope this helps.

  • Question regarding encryption and decryption

    Hi all,
    I am doing a authentication project. In which I do encryption and decryption (AES 128 bit) in two different methods. At the time of encryption (for eg a text file ), I store the key in dat file (key.dat). And at the time of decryption, I read the key.dat and extract the key and do the decryption. This works fine. No problem with that.
    But the problem is, that the client requires that
    "No encryption keys will be written to the hard drive."
    I have to store the key somewhere to decrypt the encrypted file. Right. Without storing the key, I cannot decrypt.
    The question is (though its a foolish question) with out storing the key, can i encrypt and decrypt (in two different methods) the text file ?
    Thank You.
    Regards,
    Jay

    Hi Grant,
    Thanks for the reply. ( I am the one whom you helped to solve the encryption and decryption problem using AES )
    I will give you an overview of my project. Its an Two Factor Authentication using an USB Flash Drive.
    Admin Side : ( currently developing this part )
    Through an CPP executable file ( writen by John Hyde USB By Example author), I retrive the Manufature ID, Product ID and Serial number of the USB Flash Drive from a text file which is generated when the executable file is executed.
    From my Java application, i retrive the Manufature ID, Product ID and Serial number.The admin (through an dialog box ) enters an usernam and password . All this information ( Manufature ID, Product ID, Serial number , username and password ) using AES 128 bit encryption i write these information to encrypted file in the USB Flash drive along with the the encryption key used at the time of decryption.
    User Side: ( not yet devleoped )
    When the user plugs in the USB Flash drive, an dialog box is shown where the user enters the username and password ( assigned earlier by the admin). This username and password is checked along with the Manufature ID, Product ID and Serial number encrypted earlier and stored in the USB Flash drive. If username password ,Manufature ID, Product ID and Serial number (retrieved again by exectuing the CPP excutable file ) are correct the user is granted access.
    Whats your suggestion reagrading of storing the encryption key? I have to store the key in the USB Flash drive along with the encrypted file. But then wont an intruder (for eg ) if he gets the key and decrypt the file ?
    Client has mentioned to use AES 128 Bit encryption.
    Thank You.
    Regards,
    Jay.

  • 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

  • Encrypt in C - Decrypt in Java

    Hi,
    I need to encrypt a message in C and decrypt it in Java using DES algorithm. When trying to decrypt the message im getting :
    javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA6275)
    at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA6275)
    I'm using the same key for encryption and decryption(maybe the C program using the key differently than the Java program).
    Is it possible to encrypt a message in C and decrypt it in Java ?
    Thanks in advance for your help.
    Nir.

    Can you decrypt in C? It sounds as if the encryption hasn't been performed correctly in C or like the key being used doesn't correspond to the decryption key. I'd initially get it working in C first both encryption and decryption then try to get it working in Java. I don't see any problem with getting C to encrypt and Java to decrypt as they should both be working to the same standard practices.
    The last time I had a problem with a bad padding exception the answer lay in the key I was using and the keystore I was retrieving the key from.

  • Encrypt and Decrypt files using PGP and GPG

    Dear members, We have a customer that need to process files received through sFTP, FTPs and FTP over SSL encrypted with PGP and GPG methods.
    We Know that those encryption Method are not supported out of the box in Oracle SOA Suite and WCC but We need to Know if some of you have some workaround about that, maybe using a valve in FTP adapter, B2B or any other method in WCC.
    Thanks in advance

    >
    Meiying Yang wrote:
    > I have scenarions FTP-->ABAP proxy and ABAP proxy --> FTP. I need to put and get encrypted files to and from FTP server. Does anybody know how I can decrypt file when I get it from FTP server and encrypt file before I send to FTP server? Thanks.
    Hi,
    Have a look at these blogs.It would be helpful.
    1. SAP XI/PI Encode Outgoing Payload using Adapter Module
    /people/farooq.farooqui3/blog/2008/09/24/sap-xipi-encode-outgoing-payload-using-adapter-module
    2. Decode Base64 Incoming Encoded information in SAP XI/PI using Java Mapping
    /people/farooq.farooqui3/blog/2008/05/22/decode-base64-incoming-encoded-information-in-sap-xipi-using-java-mapping
    Regards,
    Chandra

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

  • 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

  • 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

Maybe you are looking for