How does a public/private key encrypt and decrypt each other?

I understand the logic that when a communication takes place both parties pass their public keys to each other which is used to encrypt all messages. Once the party receives the messages the private key is used to decrypt them however I'm wondering how a private key is generated from a public key. If the private key is based on an algorithm wouldn't each party be able to generate what the other person's private key would be based on the public? Wouldn't a third party?

How the public and private keys are generated depends on what public key cryptosystem is being used, but in general the private key cannot be derived from the public with a computationally feasable algorithm, while the public key can be derived from the private key very quickly. Two examples:
RSA: private keys are 2 primes, p and q, and an encryption exponent d. Public key is the product p*q, and an encryption exponent e. How does the attacker get p and q, or d, from n and e? The best attack known against this (for properly chosen p, q, and d) is factoring. Factoring can be made infeasable by choosing the primes to be large enough.
Diffie-Hellman: a prime modulus p and a base g < p is known by everyone (including the attacker). The private key is an integer x chosen randomly, 2 <= x < p-1 (there are better ways to choose x). The public key is g^x mod p. How does the attacker get x from g^x mod p? Again, the best known attack is one that is computationally roughly equal to factoring a composite number of about the size of p.

Similar Messages

  • How to retrieve public/ private from iKey token using Sun PKCS#11 provider

    Dear all,
    I'm trying to access one rainbow iKey 2032 token in Java 1.5 (Windows Environment) using Sun PKCS#11 provider. Token is stored with certificate. There is no problem to logging into the token using java.
         Provider p = new sun.security.pkcs11.SunPKCS11(configName);
         Security.addProvider(p);
         KeyStore ks = null;
         try{
              char[] pin = {'P','A','S','S','W','O','R','D'};
              ks = KeyStore.getInstance("pkcs11");
              ks.load(null,pin);
    catch(Exception e) {}
    Now I am wondering how to retrieve a public and private from token, so that I can encrypt and decrypt a plain text file. Could anyone give me a sample program for this?
    Your help is very much appreciated!!

    Hi Fred13
    1. I have the same pkcs.cfg and get the following trace. Can you help me understand? Does this imply a bad dkck201.dll? I would really like to get this working for my implementation. tia.
    lException in thread "main" java.security.ProviderException: Initialization failed
         at sun.security.pkcs11.SunPKCS11.<init>(SunPKCS11.java:175)
         at sun.security.pkcs11.SunPKCS11.<init>(SunPKCS11.java:76)
         at com.mkp.jce.chap1.ProviderDetail.main(ProviderDetail.java:38)
    Caused by: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_TOKEN_NOT_RECOGNIZED
         at sun.security.pkcs11.wrapper.PKCS11.C_GetTokenInfo(Native Method)
         at sun.security.pkcs11.Token.<init>(Token.java:105)
         at sun.security.pkcs11.SunPKCS11.initToken(SunPKCS11.java:555)
         at sun.security.pkcs11.SunPKCS11.<init>(SunPKCS11.java:169)
    2. (If I can be so indulgent of your time) Can you provide more information on cbp? I have done a search and there is little on it. It appears to be a new authentication framework tied in with sasl unique to 1.5. Any links for self education would be appreciated.

  • Deleted the public/private keys installed by iPCU & untrusted the certs

    Hi;
    it's early in the morning and i couldn't quite figure what was going on
    when:
    - new public and private keys "appeared" in keychain
    - a certificate was installed almost as soon as a plugged
    an iphone in while running iPhone Config Util (iPCU i now
    realize)
    From the console:
    Tue Jun 30 02:39:45 unknown mcmobiletunnel[363] <Warning>: added object <NSCFType: 0x1073d0> to keychain as iPCUHost-D3FA2B23-E0D0-4C42-A48B-DFXXXXXXXX-HostCert success 1 error 0
    What it looks like is on connecting the iPhone "phoned home" and snagged a certificate and public and private keys to install on my MacBook Pro.
    I deleted these not realizing who iPCUHost was (an earlier cert was marked as untrusted on a pass trhough my certs earlier).
    OK: so *how* do i recreate the public/private keys? the Certificates in Keychain?
    Tried: downloading and re-installing iPCU
    Tried: Time Machine to earlier version if iPCU & using Software update to Update.
    This is where things look unhappy in the iPCU console:
    Tue Jun 30 03:42:36 unknown mcmobiletunnel[432] <Warning>: received request 4: (\n RequestType\n), keys {\n RequestType = GetProfileList;\n}
    Tue Jun 30 03:42:36 unknown mcmobiletunnel[432] <Warning>: processing request 4: ((\n RequestType\n))
    Tue Jun 30 03:42:36 unknown mcmobiletunnel[432] <Warning>: sending reply {\n OrderedIdentifiers = (\n );\n ProfileManifest = {\n };\n ProfileMetadata = {\n };\n Status = Acknowledged;\n}
    Tue Jun 30 03:42:36 unknown mcmobiletunnel[432] <Error>: receive_message: Could not receive size of message: 0 Operation not permitted
    Tue Jun 30 03:42:36 unknown mcmobiletunnel[432] <Warning>: received request 4: (null), keys (null)
    Tue Jun 30 03:42:36 unknown mcmobiletunnel[432] <Error>: main: Could not receive request from host.
    Tue Jun 30 03:48:21 unknown /usr/libexec/notification_proxy[426] <Error>: Could not receive size of message
    Tue Jun 30 03:48:21 unknown /usr/libexec/notification_proxy[426] <Error>: Could not receive message
    Tue Jun 30 03:51:02 unknown mcmobiletunnel[446] <Warning>: received request 4: (\n RequestType\n), keys {\n RequestType = GetProfileList;\n}
    Tue Jun 30 03:51:02 unknown mcmobiletunnel[446] <Warning>: processing request 4: ((\n RequestType\n))
    Tue Jun 30 03:51:02 unknown mcmobiletunnel[446] <Warning>: sending reply {\n OrderedIdentifiers = (\n );\n ProfileManifest = {\n };\n ProfileMetadata = {\n };\n Status = Acknowledged;\n}
    Tue Jun 30 03:51:02 unknown mcmobiletunnel[446] <Error>: receive_message: Could not receive size of message: 0 Operation not permitted
    Tue Jun 30 03:51:02 unknown mcmobiletunnel[446] <Warning>: received request 4: (null), keys (null)
    Tue Jun 30 03:51:02 unknown mcmobiletunnel[446] <Error>: main: Could not receive request from host.
    Thx
    Jim

    I'm in the same situation here. While trying out the iPCU, I noticed my test devices were showing up with a certificate of "iPCUHost...". I was hoping to replace this default cert with one from our own CA, and in the process of messing around I tried deleting all of those certs from my Keychain. They deleted just fine, and after a sync the cert also disappeared from the connected iPhone. Unfortunately, there is no obvious way to replace that cert and as of now, I cannot install any profile to the device that has had the cert removed. If I select the device and click "Install" on a profile, nothing happens... no errors, no console messages, it just does nothing.
    I'm not quite sure how to replace the missing cert, and in particular how to replace it with one of our own rather than the default. Surely we don't have to actually develop a web service just to install certs... (see page 21 of the Enterprise Deployment Guide)
    -mike

  • Is a Public/Private Key Pair possible in SAP?

    I have a web service that I would like to run as part of a nightly script. I currently use username/password authentication, but it is not acceptable to have them hard coded, due to Sarbanes-Oxley rules. SAP's site claims to support authentication with x.509 certificates, but is unclear on the implementation details. How could I go about setting up and using a public/private key pair in SAP?

    Not really a portal question, and maybe you'll get a better result in a security forum...
    However, briefly, yes, the AS Java supports X509 certificates as an authentication mechansm. You need to use Visual Admin to generate a server side certificate, then you need the client side to register its own X509 certificate and then in the Java user admin you need to associate the client certificate with a known user. Now when the client executes the web service call it can pass the certificate and the AS Java will back translate the certificate to a real username.

  • Public/private keys

    How to create a private/public keys?
    Fred

    Hi Fred,
    Following are the steps required are to create a Public/Private Keys:
    1. Load the security provider (if not configured in $JAVAHOME/jre/lib/security/java.security)
    2. Obtain a handle to a secure random number generator.
    3. Obtain a handle to KeyPairGenerator for a specific public key algorithm.
    4. Generate the public/private key pair
    5. Extract the public and private keys
    The following example shows how to generate public and private keys using the KeyPairGenerator and KeyPair interfaces using JCSI's security provider.
    import java.security.*;
    // Load JCSI's JCA security provider
    Security.addProvider(new com.dstc.security.provider.DSTC());
    // Seed random number generator using the default seeding
    // "SHA1PRNG" = SHA1 Pseudo-random number generator
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    // Initialise KeyPairGenerator to create 1024-bit RSA keys.
    // PK Algorithm = "RSA", Security Provider = "DSTC" (Wedgetail)
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "DSTC");
    keyGen.initialize(1024, random);
    // Generate RSA pulic/private key pair
    KeyPair keyPair = keyGen.genKeyPair();
    // Extract public and private keys
    PrivateKey privKey = keyPair.getPrivate();
    PublicKey pubKey = keyPair.getPublic();
    Hope this will help you.
    Regards,
    Anil.
    Techncial Support Engineer.

  • Generate public private keys inside smart card

    Dear all,
    I am using this code to generate public and private key inside the smart card.
    KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_512);
    kp.genKeyPair();
    PrivateKey prikey = kp.getPrivate();
    PublicKey pubkey = kp.getPublic();
    This code is executing without errors.
    I need to get out the public key from the smart card. So I need to get public key to a byte array.
    But I can't get those keys to plain text byte array.
    The methods that I can get for pubkey object are
    pubkey.clearKey();
    pubkey.equals(obj);
    pubkey.getSize();
    pubkey.getType();
    pubkey.isInitialized(); only these.
    I am using
    Eclipse Version: 3.4.1 (Compiler complience level = 1.4)
    Jcop plugin (to communicate with the actual card and to test the java code in virtual card provided by JCOP)
    OmniKey5321 card reader (In contactless type)
    What is the reason to get only those above methods to pubkey object? Is it a version problem?
    How can I get the public key to plain byte array? Is it possible?
    If it is not possible Is there a way to get public key as a export certificate or something other solution?
    If my scenario is not a possible strategy, How can I use public private keys to send specific data to applet? Is there a better way to do this?
    Edited by: 863766 on Jun 6, 2011 12:16 AM

    Thank you very much!
    I used this code
    RandomData rand = RandomData.getInstance(RandomData.ALG_SECURE_RANDOM);
              short lenBytes = (short) (KeyBuilder.LENGTH_DES/8);
              byte[] buffer = JCSystem.makeTransientByteArray(lenBytes,JCSystem.CLEAR_ON_DESELECT);
              DESKey key = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES , KeyBuilder.LENGTH_DES,false);
              rand.generateData(buffer, (short) 0 ,lenBytes);
              key.setKey(buffer, (short) 0 ) ;
              byte keyData[]= new byte[256];
              key.getKey(keyData, (short) 0);
    Now I know how to initialize the key...
    Thank you again.
    Regards,
    Dushantha
    Edited by: 863766 on Jun 6, 2011 3:52 AM

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

  • How does firefox guarantee User data privacy and protection?

    As I understand Firfox Sync Service will store user data on its personal servers, i have 2 doubts then -
    1: If a user stores his passwords to Firfox server and there is a security breach on that server and User's private data has gone to wrong hands then who would take responsibility of such incidence?
    How secure is the server that firfox uses in general !!
    2: Once this data store grows in size, Firfox would have to use better and reliable technology, that comes with a cost tag, so would Firfox start charging those users who have no idea of this right now?

    With only the password it is impossible to read the data that is on the servers since the data is encrypted. The data is encrypted on your computer before it is sent to the Mozilla servers, and if downloading the data from Mozilla it is decrypted on your computer. To encrypt and decrypt the data the secret phrase is required, and that is on your computer.
    As far as I am aware Firefox sync will always be free.

  • I wanted to know how does technical support work via icloud and is there any new technology out that helps providing technical support

    i wanted to know how does technical support work via icloud and is there any new technology out that helps providing technical support?

    basically I’m doing a project were I wanted to find out if there are recent technology  out that provides technical support for example they do it with remote access but is they any new ways that  they can support us and just wanted to find out if icloud gives technical support then how?

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

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

    Read old posts, or the JCE docs.

  • 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

  • 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

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

  • 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

  • Packets not getting encrypt and decrypt IPSEC

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

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

Maybe you are looking for

  • New Mac Mini and 802.11n 5Ghz - Does it work?

    Does anyone know if this works? It states that it is 802.11a compatible which uses 5Ghz so I am guessing it does. I don't want to have to use a third party internal card like I do now with a separate external antenna. Thanks.

  • Error 3253 Network Connection was reset

    This is my first experience with iTunes and it may be my last! I am trying to download from iTunes. Several times the download has progressed for 9 minutes, but then when I reach 7.8 of 7.9MB completed the download stops and it gives me "error 3253."

  • My iPhone 5 keeps on freezing and shutting down

    Hi guys. Around the end of April we decided to get an iPhone 5 from dialaphone.com. The phone was totally fine until about last week, when it started to lag and then, after a few minutes after being switched on, black out. We have tried to restore it

  • Installer silent install - modify Setup config

    Hi all, Using LV 2009.  Built installer which includes my own licence agreement. Upon installation by the user my own licence agreement (not NI's) is all I want them to see, then my application and LV run-time should install (silently). Can I achieve

  • Document() not returning a useable node set?

    If I open another document during a transform, I can dump out the file using xsl:message, but can't match any tags in the loaded file. If I replace the Sun implementation with the apache implementation of xalan with -Xbootclasspath/p, the code runs f