Diffie hellman algorithm

        try{
                BigInteger p = new BigInteger(1, primeA);
                BigInteger g = new BigInteger("5");
                KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
                DHParameterSpec dhSpec = new DHParameterSpec(p, g, 1024 );
                keyGen.initialize(dhSpec);
                KeyPair keypair = keyGen.generateKeyPair();
                PrivateKey privateKey = keypair.getPrivate();
                PublicKey publicKey = keypair.getPublic();
                byte[] pub = publicKey.getEncoded();
                byte[] priv = privateKey.getEncoded();
                System.out.println("PRIVATE KEY=" + priv.length + "   PUBLIC KEY=" +pub.length);
                X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pub);
                KeyFactory keyFact = KeyFactory.getInstance("DH");
                publicKey = keyFact.generatePublic(x509KeySpec);
                KeyAgreement ka = KeyAgreement.getInstance("DH");
                ka.init(privateKey);
                ka.doPhase(publicKey, true);
                byte []secretKey = ka.generateSecret();
                 System.out.println("------------------------------------"  +secretKey.length);
                convertByte2Hex(secretKey , "  secretKey  " ) ;
        } catch (java.lang.NumberFormatException nfe) {System.out.println("iNumber format exception");
        } catch (java.security.InvalidAlgorithmParameterException e) {
        } catch (java.security.NoSuchAlgorithmException e) {
        }catch(Exception e) {e.printStackTrace();System.out.println("MAIN EXCEPTION ");}I have 2 problems here.
The public and the private key arrays that are generated are of length 298 and 296 (keeps changing) . I want to set the size of these values to be 128 bytes How can i Do that ?
Do we need to provide the value of vendor public key at
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pub); !!!
Thanks
Sandesh

The public and the private key arrays that are generated are of length 298 and 296 (keeps changing) . I want to set the size of these values to be 128 bytes How can i Do that ?
I think, you can't. Using 1024 as "the size in bits of the random exponent (private value)" means that the encoding contains some additional bits of overhead plus the bits of p and g (or something like that). You'd have to use much shorted exponent in order to fit into 128 bytes. I wouldn't do it.
Do we need to provide the value of vendor public key at X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pub); !!!
Is it a question? I don't understand.
Btw., you should NEVER swallow exceptions.

Similar Messages

  • Diffie-Hellman Algorithm and Man-in-the-middle attack

    From the RSA Security site, it says that Diffie-Hellman Algorithm
    is susceptable to the Man-in-the-middle attack, because there
    is not mechanism to prove the authenticity of the public keys
    being exchanged.
    Is it true then, the only way to protect against this,
    is the use of a signed certificate?

    or rather, the only way to protect against
    the attack is to authenticate before generating the
    DH secret key.
    signed certificates are one way of authenticating,
    userid/password, hardware token, biometrics are others.
    i guess you could use any of these after looking at
    trade-offs between security/useability.

  • Diffie-Hellman algorithm hexadecimal

    Hello,
    I've made DH algoritm (link) but I need it to calculate in hex, can someone please show me how to tweek my code for that?
    Attachments:
    DH_algorithm_HEX.vi ‏14 KB

    HEX is a representation (in Base 16) of numeric (usually integer!!) data.  Your code shows Dbl (64-bit floats), which is not an "exact" numeric representation, so is unlikely to implement Diffie-Hillman.  I notice you use the remainder operator which is well-defined for integer representations, but whose meaning is unclear (to me) for floats.
    You should only need to use Hex to turn an input representation into an internal numeric form for computations, and to transform the output into a final representation.
    Rethink what you are doing.
    Bob Schor

  • About Diffie-Hellman Key Exchange Algorihtm

    Hi... experts. I've got a problem about Diffie-Hellman Key Exchange. Is that possible to actually exchange a secret session key via Diffie-Hellman Key Exchange? or the secret session key (g^xy) is actually generated after the exchange of g^x and g^y by the two parties? My project supervisor made me confused with it, he is sure that the first case can be done. Please give me some ideas... Thanks a lot!!!
    Regards,
    Yating

    ejp, thanks for the reply!
    What is exchanged is the
    means by which it can be independently and
    identically calculated by both parties.That's exactly what I learn from the Diffie-Hellman algorithm, but he kept saying that he wanted me to distribute a shared secret via the key exchange. I really have no idea about what he is talking about. Do you have any ideas?
    Regards,
    Yating

  • Can diffie hellman security algorithm be implemented on cpt?

    can diffie hellman security algorithm be implemented on cpt?

    The public and the private key arrays that are generated are of length 298 and 296 (keeps changing) . I want to set the size of these values to be 128 bytes How can i Do that ?
    I think, you can't. Using 1024 as "the size in bits of the random exponent (private value)" means that the encoding contains some additional bits of overhead plus the bits of p and g (or something like that). You'd have to use much shorted exponent in order to fit into 128 bytes. I wouldn't do it.
    Do we need to provide the value of vendor public key at X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pub); !!!
    Is it a question? I don't understand.
    Btw., you should NEVER swallow exceptions.

  • Diffie-Hellman Key Exchange Problem

    I am working on a program that will allow encrypted communication between two parties, and I am using the Diffie-Hellman key exchange to computer their secret keys, whenever I use this algorithm the key exchange goes fine but when I try to use KeyAgreement.doPhase() to perform the final phase I get an "InvalidKeyException: Incompatible Paramters" can anyone tell me what is going on, any help is greatly appreciated:
    //Server
    static void DHDoKeyExchange() {
              try {
                   PublicKey theirPublicKey = null;
                   System.out.println("Exchanging Keys...");
                   System.out.println("\t-Generating KeyPair.");
                   KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
                   kpg.initialize(dhparameters);
                   KeyPair keyPair = kpg.genKeyPair();
                   System.out.println("\t-Exchanging.");
                   theirPublicKey = (PublicKey)ois.readObject();
                   oos.writeObject(keyPair.getPublic());
                   KeyAgreement ka = KeyAgreement.getInstance("DH");
                   ka.init(keyPair.getPrivate());
                   ka.doPhase(theirPublicKey, true);
                   secret = ka.generateSecret();                              
                   System.out.println("\t-Done!\n");
              } catch(Exception e) {
                   e.printStackTrace();
    //Client
    static void DHDoKeyExchange() {
              try {
                   PublicKey theirPublicKey = null;
                   System.out.println("Exchanging Keys...");
                   System.out.println("\t-Generating KeyPair.");
                   KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
                   kpg.initialize(dhparameters);
                   KeyPair keyPair = kpg.genKeyPair();
                   System.out.println("\t-Exchanging.");
                   oos.writeObject(keyPair.getPublic());
                   theirPublicKey = (PublicKey)ois.readObject();
                   KeyAgreement ka = KeyAgreement.getInstance("DH");
                   ka.init(keyPair.getPrivate());
                   ka.doPhase(theirPublicKey, true);
                   secret = ka.generateSecret();
                   System.out.println("\t-Done!\n");
              } catch(Exception e) {
                   e.printStackTrace();
         }

    Given that the error is "Invalid Parameters", you might want to show us how "dhparameters" is being set up on both sides...
    Grant

  • Cisco SSH v2 support diffie-hellman-exchange-group-sha1 ?

    one of my router are scanned by Foundstone and get an alert :
    ""The SSH2 protocol specification requires that a SSH2 server support the
    diffie-hellman-group1-sha1 key exchange algorithm. This key exchange
    algorithm is considered strong, but faces a potential weakness in that the
    same prime number is used for all key exchanges."
    SO wanna check if cisco SSH2 can support the diffie-hellman-exchange-group-sha1? If yes, which IOS version required? ( have relevent link is appreciate)
    thx..
    ..peter cheung

    read http://www.cisco.com/en/US/docs/ios/sec_user_services/configuration/guide/sec_secure_shell_v2.html#wp1082528

  • Diffie Hellman withg JavaCars

    Dear,
    I kindly ask you if any card vendor or if the java-card_kit (versionn 2.2.1) support Diffie Hellman (DH) cryptographic algorithm?
    Sincerely

    Read the specs and you will see the answer. There's a reason SUN makes them available !
    The issue you will run into is finding a vendor that will have 2.2.x cards. I don't even know any vendors that are shipping 2.2 cards yet !
    It's not to say you can't develop solutions, but you won't have cards with 2.2.x JCRE/JCVM for deployment.

  • Diffie Hellman use

    Guys if i use Diffie Hellman to get a number
    What is the best way to use that number to encrypt the plain Text
    i was thinking if the number was S, and the plaintext we could get the encrypted text E
    by raisining T to the power of S mod n.
    Is there an algorithm to get back to the T if you knew E and S.
    If you know a better use of the number than that would be appreciated.

    Diffie-Hellman is an algorithm for sharing keys between two nodes over an insecure channel. DH is only an algorithm, not an application.
    In your case, assuming you want to transfer a text message securely, you need an application, not an algorithm.
    I suggest you use IPSec. IPSec supports Internet Key Exchange (IKE). IKE supports DH as the key establishment algorithm.
    There are IPSec application that are ready-to-use :
    www.freeswan.org or www.openswan.org (the two are more-or-less the same).
    To get DH working under IPSec, you will need to do is abit more work (more tricky). If all you want is to transmit a message securly between two nodes, then the easiest way is to use a pre-shared secret, which is also supported by IPSec.

  • Diffie-Hellman groups - ASA firewalls

    Hi all,
    A couple of questions I'm hoping you can help me with.
    Please can you tell me where I'd change the Diffie-Hellman group for phase 1 on an ASA firewall and can this be done on the ASDM?
    Also, do you have to enable PFS have to DH on phase 2?
    Many thanks
    Alex

    Hello Alex,
    You can change the Diffie-Hellman group for phase 1 on ASA by configuring the following command:
    crypto isakmp policy
         group
    To configure the same using ASDM, go to
    Configuration>Site-to-Site VPN>Connection Profiles>Add/Edit
    In IPsec Settings, you will find Encryption Algorithms .Click on "Manage" icon on the right  of "IKE Policy".Click OK.
    Click on Add/Edit and there will be an option to change the DH Group.
    And lastly in regard to the PFS query , you can enable PFS in  order to have DH in phase 2.Enabling PFS will force a new DH key  exchange for phase 2.
    Note:It is not mandatory , its optional .If its configured on one side , then it needs to be done on the remote side as well.
    Regards,
    Dinesh Moudgil

  • Need help with Diffie-Hellman key-exchange protocol

    How can i show that the Diffie-Hellman key-exchange protocol is vulnerable to a man-in-themiddle
    attack and Devise a protocol using digital signatures which overcomes this vulnerability

    Given that the error is "Invalid Parameters", you might want to show us how "dhparameters" is being set up on both sides...
    Grant

  • Diffie-hellman

    hello,
    I encrypted my data with symetric method (DES) and I would like to protect my key transfer by Diffie-hellman method.
    Diffie-hellman use this calcul: g^x * mod(p)
    on my card i have this code :
    public void genereCleDH(){
               clePrive = new byte[14];
               clePublic = new byte[29];
              KeyPair keypair = new KeyPair(KeyPair.ALG_EC_FP, (short)112);
              keypair.genKeyPair();
             privateKey = (ECPrivateKey) keypair.getPrivate();
             publicKey = (ECPublicKey) keypair.getPublic();
              publicKey.getW(clePublic, (short)0);
              privateKey.getS(clePrive, (short)0);
         public void envoyerClePublicDC(APDU apdu){
              apdu.setOutgoing();
              apdu.setOutgoingLength((short)clePublic.length);
              apdu.sendBytesLong(clePublic,(short) 0, (short) clePublic.length);
         }for my client I have this code:
         public byte[] initDH(){
             X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(apdu.dataOut);
             KeyFactory keyFact = KeyFactory.getInstance("DH");
             PublicKey clientpublicKey =  keyFact.generatePublic(x509KeySpec);
         DHParameterSpec dhParamSpec = (DHParameterSpec)((DHPublicKey)clientpublicKey).getParams();
            KeyPairGenerator clientKpairGen = KeyPairGenerator.getInstance("DH");
            clientKpairGen.initialize(dhParamSpec);
            KeyPair bobKpair = clientKpairGen.generateKeyPair();
            KeyAgreement clientKeyAgree = KeyAgreement.getInstance("DH");
            clientKeyAgree.init(bobKpair.getPrivate());
            clientKeyAgree.doPhase((Key) clientpublicKey, true);
            byte[] clientPubKeyEnc = bobKpair.getPublic().getEncoded();
            clientKeyAgree.doPhase((Key) clientpublicKey, true);
            byte[] bobSharedSecret = clientKeyAgree.generateSecret();
              return clientPubKeyEnc;
              return null;
         }but I have a problem at this line:
    PublicKey clientpublicKey =  keyFact.generatePublic(x509KeySpec);and a try catch show this error : "Inappropriate key specification".
    1) The problem come from of my card or my client?
    2) I send the public key data, and I built a new publicKey with X509EncodedKeySpec, but isn't it easer to give "A", "g" and "p" parameters ("x" is my private data, "A" my result of "g^x * mod(p))?
    3)
    {code}publicKey = (ECPublicKey) keypair.getPublic();{code}
    publicKey contains my public data "A","g" and "p": but which part of the array contains each data?
    4) My client (using java) can call X509EncodedKeySpec, but how can i do with my applet (when my client will send this public data)?
    5) When I will have the secret key with my applet and my client, how can I use it with my DES key?
    thank for your help.
    Alexis

    Alexis wrote:
    >
    The SunJCE implementation is kind enough to swallow the exception thrown by the DHPubliKey class when it attempts to decode the X.509 key data you pass in
    >
    I don't understand what you mean. The code snippet I posted is from OpenJDK source code. It catches any exception that is thrown from the call to create a DH public key from the X509 encoded key spec. new DHPublicKey(((X509EncodedKeySpec)keySpec).getEncoded()) If your encoding is incorrect then you will not know why. X509 encoded keys have a specific ASN.1 structure.
    >
    Considering you have the public key on the card, you should try using the javax.crypto.spec.DHPublicKeySpec using the three key components from the card key.
    >
    for that I need to know which value of my byte[] area corresponding to "y","p" and "g". In addition I think on my card I have create an elliptic curve for diffie-hellman method (KeyPair.ALG_EC_FP) and on my client (java) I use "DH" method.
    So I think the problem come from the differents method used ("ALG_EC_FP" and "DH"). But I don't find " ALG_EC_FP" on java.The problem is that you are getting one component of your key (getW). Can you post the hex dump of the key you are getting back?
    You would need to get 3 components of your key to use the DHKeySpec (getField getG and getW maybe?). This will give you three byte arrays representing BigIntegers that you could use to initialise your key.
    Cheers,
    Shane

  • Diffie Hellman Public Key from openSSL is throwing InvalidKeySpecException

    Ladies and Gents,
    I am trying to write a client application in Java to replace an existing client app that is written in C++. The current client and server use openSSL for the crypto. The client and server perform a Diffie Hellman Key exchange and then encrypt the data streams. Communication is via net sockets and is pure TCP.
    I can get a Java app to Java app DH key exchange to work as well as a C++/openSSL app to C++/openSSL app. A problem arises when I attempt to have a Java client perform a DH Key exchange with the C++/openSSL server.
    I have narrowed down the error to this codeblock (I added the line numbers for clarity):
    164       KeyFactory keyFac = KeyFactory.getInstance("DH");
    165       X509EncodedKeySpec dhKeySpec = new X509EncodedKeySpec(peerPublicKeyBytes);
    166       DHPublicKey peerPublicKey = (DHPublicKey) keyFac.generatePublic(dhKeySpec);Here is the error thrown:
    java.security.spec.InvalidKeySpecException: Inappropriate key specification
         at com.sun.crypto.provider.DHKeyFactory.engineGeneratePublic(DashoA13*..)
         at java.security.KeyFactory.generatePublic(Unknown Source)
         at jClient.crypto.DHCipher.bytesToPublicKey(DHCipher.java:166)Now based on the error given, I can guess that the format of the Public Key I received is somehow incorrect. The server sends its generated public key in the following manner:
    keyLen(4 bytes), keyBytes (keyLen bytes)
    Which is simple enough, so I assumed that simply stripping off the first 4 bytes off the byte[] would yield a viable PublicKey, but I get the above error.
    Additionally, I have tried to modify the code to use a DHPublicKeySpec instead of a X509EncodedKeySpec:
    163       KeyFactory keyFac = KeyFactory.getInstance("DH");
    164       BigInteger peerPubKeyBI = new BigInteger(peerPublicKeyBytes);
    165       DHPublicKeySpec dhKeySpec = new DHPublicKeySpec(peerPubKeyBI, this.p, this.g);
    166       DHPublicKey peerPublicKey = (DHPublicKey) keyFac.generatePublic(dhKeySpec);This seems to accept the openSSL generated public key, but ultimately results in non-matching client and server SecretKeys.
    I normally don't post for help, choosing instead to just keep hammering away at a problem till I win, but this is going on 3 weeks and I have a deadline coming up. Any help would be appreciated. If anymore information is needed, just say so.
    Thanks in advance,
    Dave
    Edited by: claymore1977 on May 26, 2009 4:47 PM

    claymore1977 wrote:
    Which is simple enough, so I assumed that simply stripping off the first 4 bytes off the byte[] would yield a viable PublicKey, but I get the above error.Too simple. If you look at the Javadocs for X509EncodedKeySpec, you can see that it is much more complicated beast that contains object IDs in addition to the DH public bytes. You could try to get openssl to build the more complicated X509EncodedKeySpec, but I see below that you have found a simpler solution.
    >
    >
    Additionally, I have tried to modify the code to use a DHPublicKeySpec instead of a X509EncodedKeySpec:
    163       KeyFactory keyFac = KeyFactory.getInstance("DH");
    164       BigInteger peerPubKeyBI = new BigInteger(peerPublicKeyBytes);
    165       DHPublicKeySpec dhKeySpec = new DHPublicKeySpec(peerPubKeyBI, this.p, this.g);
    166       DHPublicKey peerPublicKey = (DHPublicKey) keyFac.generatePublic(dhKeySpec);
    This looks reasonable, the only thing I can see wrong is the BigInteger constructor you are using. If the data sent is "negative", the resulting BigInteger will be negative and you'll get wrong answers. See if using the sign=magnitude constructor works better for you, i.e. BigInteger peerPubKeyBI = new BigInteger(1, peerPublicKeyBytes);

  • Diffie Hellman Key Agreement

    Hi All,
    Can some one help me with a example to encrypt a string using Diffie hellman key agreement protocol
    Thanks &Regards
    Murali

    There are plenty of samples provided with the Javadoc.

  • Diffie-Hellman (D-H) key Exchange problem

    Hi,
    I have generated a certificate for Tomcat 6.0.14 using command:
    keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -sigalg SHA256withRSATomcat is using JDK 1.6.0_03 with unlimited strength java cryptography extension policy
    and now when I try to connect to my site using Opera 9.24 I get warring �low encryption level�. The detected protocol by Opera is TLS v1.0 256 bit AES (768 bit DHE_RSA/SHA). The problem is 768 bit DHE (Diffie-Hellman key exchange) which is used for exchanging session key, opera issue a warring when key is sorter than 900 bits � more details on:
    http://my.opera.com/yngve/blog/2007/10/22/new-w-not-in-kestrel-dhe or
    http://my.opera.com/community/forums/topic.dml?id=207440I have two questions:
    1) How to change size of DHE key?
    2) If changing size of DHE key is not possible, than how to disable DHE to get pure RSA/SHA?

    I add to tomcat java options -Dhttps.cipherSuites=TLS_RSA_WITH_AES_256_CBC_SHA and I still got TLS v1.0 256 bit AES (768 bit DHE_RSA/SHA), but it lead me to connector configuration � after adding in server.xml:
    <Connector protocol="org.apache.coyote.http11.Http11Protocol"
          ciphers="TLS_RSA_WITH_AES_256_CBC_SHA" />opera gave me TLS v1.0 256 bit AES (2048 bit RSA/SHA) :) . The doc says that without this attribute all ciphers are available, maybe it overrides https.cipherSuites � either way problem solve
    Cheers

Maybe you are looking for

  • SOAP Error in PRC

    I am trying to add a remote document to multiple folders in the KD as well as set its customized properties, we are using Plumtree v 5.02. My Java code is as follows: import com.plumtree.remote.prc.*; import java.net.*; import java.util.*; import com

  • Combining Photographs in a grid

    How can I create one very large photograph by combining multiple, equally sized photographs in columns and rows with no spacing between the photos? Each photo has a black background. I tried the contact sheet function and it always puts white spacing

  • Rounding text size to nearest whole number?

    I've had to rescale some artwork, but now I'm left with type sizes that are 71.68px tall, 34.51px tall, etc. Is there a script that'll snap all the text in a document to it's nearest whole number or 0.1 decimal?

  • Creating ImageIcon from .ICO files

    Can i use an icon (.ICO) to create an Icon or an ImageIcon for a JButton? Thank you

  • ISL best practice

    Hello All, I have 2 MDS 9509 sitting across two sites on a same fabric with Intersite DWDN link = 1 Gbps I have 48 port blades and 12 port blades. Since the ISL max theoritical bandwidth is 1 Gbps, i think of locking the switch ISL ports at 1 Gbps (E