How to sign the data with DHPrivateKey

I am testing DH key exchange protocol. When I run the following code, it works.
import java.io.*;
import java.math.BigInteger;
public class DH2 {
    private DH2() {}
    public static void main(String argv[]) {
        try {
            String mode = "USE_SKIP_DH_PARAMS";
            DH2 keyAgree = new DH2();
            if (argv.length > 1) {
                keyAgree.usage();
                throw new Exception("Wrong number of command options");
            } else if (argv.length == 1) {
                if (!(argv[0].equals("-gen"))) {
                    keyAgree.usage();
                    throw new Exception("Unrecognized flag: " + argv[0]);
                mode = "GENERATE_DH_PARAMS";
            keyAgree.run(mode);
        } catch (Exception e) {
            System.err.println("Error: " + e);
            System.exit(1);
    private void run(String mode) throws Exception {
        DHParameterSpec dhSkipParamSpec;
        if (mode.equals("GENERATE_DH_PARAMS")) {
            // Some central authority creates new DH parameters
            System.out.println
                ("Creating Diffie-Hellman parameters (takes VERY long) ...");
            AlgorithmParameterGenerator paramGen
                = AlgorithmParameterGenerator.getInstance("DH");
            paramGen.init(512);
            AlgorithmParameters params = paramGen.generateParameters();
            dhSkipParamSpec = (DHParameterSpec)params.getParameterSpec
                (DHParameterSpec.class);
        } else {
            // use some pre-generated, default DH parameters
            System.out.println("Using SKIP Diffie-Hellman parameters");
            dhSkipParamSpec = new DHParameterSpec(skip1024Modulus,
                                                  skip1024Base);
        System.out.println("ALICE: Generate DH keypair ...");
        KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
        aliceKpairGen.initialize(dhSkipParamSpec);
        KeyPair aliceKpair = aliceKpairGen.generateKeyPair();
        System.out.println("ALICE: Initialization ...");
        KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH");
        aliceKeyAgree.init(aliceKpair.getPrivate());
        byte[] alicePubKeyEnc = aliceKpair.getPublic().getEncoded();
        KeyFactory bobKeyFac = KeyFactory.getInstance("DH");
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec
            (alicePubKeyEnc);
        PublicKey alicePubKey = bobKeyFac.generatePublic(x509KeySpec);
        DHParameterSpec dhParamSpec = ((DHPublicKey)alicePubKey).getParams();
        System.out.println("BOB: Generate DH keypair ...");
        KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
        bobKpairGen.initialize(dhParamSpec);
        KeyPair bobKpair = bobKpairGen.generateKeyPair();
        System.out.println("BOB: Initialization ...");
        KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH");
        bobKeyAgree.init(bobKpair.getPrivate());
        byte[] bobPubKeyEnc = bobKpair.getPublic().getEncoded();
        KeyFactory aliceKeyFac = KeyFactory.getInstance("DH");
        x509KeySpec = new X509EncodedKeySpec(bobPubKeyEnc);
        PublicKey bobPubKey = aliceKeyFac.generatePublic(x509KeySpec);
        System.out.println("ALICE: Execute PHASE1 ...");
        aliceKeyAgree.doPhase(bobPubKey, true);
        System.out.println("BOB: Execute PHASE1 ...");
        bobKeyAgree.doPhase(alicePubKey, true);
        byte[] aliceSharedSecret = aliceKeyAgree.generateSecret();
        int aliceLen = aliceSharedSecret.length;
        byte[] bobSharedSecret = new byte[aliceLen];
        int bobLen;
        try {
            bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 1);
        } catch (ShortBufferException e) {
            System.out.println(e.getMessage());
        bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 0);
        System.out.println("Alice secret: " +
          toHexString(aliceSharedSecret));
        System.out.println("Bob secret: " +
          toHexString(bobSharedSecret));
        if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret))
            throw new Exception("Shared secrets differ");
        System.out.println("Shared secrets are the same");
        System.out.println("Return shared secret as SecretKey object ...");
        bobKeyAgree.doPhase(alicePubKey, true);
        SecretKey bobDesKey = bobKeyAgree.generateSecret("DES");
        aliceKeyAgree.doPhase(bobPubKey, true);
        SecretKey aliceDesKey = aliceKeyAgree.generateSecret("DES");
        Cipher bobCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        bobCipher.init(Cipher.ENCRYPT_MODE, bobDesKey);
        byte[] cleartext = "This is just an example".getBytes();
//        Signature signature = Signature.getInstance("SHA1withDSA");
//        signature.initSign(bobKpair.getPrivate());
//        signature.update(cleartext);
//        byte[] data = signature.sign();
        byte[] ciphertext = bobCipher.doFinal(cleartext);
        Cipher aliceCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        aliceCipher.init(Cipher.DECRYPT_MODE, aliceDesKey);
        byte[] recovered = aliceCipher.doFinal(ciphertext);
        if (!java.util.Arrays.equals(cleartext, recovered))
            throw new Exception("DES in CBC mode recovered text is " +
              "different from cleartext");
        System.out.println("DES in ECB mode recovered text is " +
            "same as cleartext");
        bobCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        bobCipher.init(Cipher.ENCRYPT_MODE, bobDesKey);
        cleartext = "This is just an example".getBytes();
        ciphertext = bobCipher.doFinal(cleartext);
        byte[] encodedParams = bobCipher.getParameters().getEncoded();
        AlgorithmParameters params = AlgorithmParameters.getInstance("DES");
        params.init(encodedParams);
        aliceCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        aliceCipher.init(Cipher.DECRYPT_MODE, aliceDesKey, params);
        recovered = aliceCipher.doFinal(ciphertext);
        if (!java.util.Arrays.equals(cleartext, recovered))
            throw new Exception("DES in CBC mode recovered text is " +
              "different from cleartext");
        System.out.println("DES in CBC mode recovered text is " +
            "same as cleartext");
}I want to sign the data with Signature,So i add the following code to the sample.
        byte[] cleartext = "This is just an example".getBytes();
     Signature signature = Signature.getInstance("SHA1withDSA");
        signature.initSign(bobKpair.getPrivate());
        signature.update(cleartext);
        byte[] data = signature.sign();
        byte[] ciphertext = bobCipher.doFinal(cleartext);Run the code again, the output is
Error: java.security.InvalidKeyException: No installed provider supports this key: com.sun.crypto.provider.DHPrivateKey
What's wrong with the code, It seems that the bob's private key is not instance of DSAPrivateKey but DHPrivateKey.
what's your comment? thanks a lot.

slamdunkming wrote:
thank sabre150 for your reply. But the key pair is generated when I use DH to exchange the secret key. Yes! It is a DH key pair and cannot be used for signing. The DH key pair can only be used for secret sharing.
If I can not use this private key to sign the data, what can i do?Do I have to generate another key pair for signature? In that way, I will have two key pair. Yep. You can generate a DSA or an RSA key pair to be used for signing.
Because I use http protocol to exchange the key to get the shared secret key, Yep.
If I generate another key pair, how can i send the public key to server? Since public keys are 'public' then you can send them in the open to anyone you like. In fact, if you don't publish your public keys then they are pretty much a waste of time. The biggest problem one has with public key is proving 'ownership' - if someone sends me a public key how do I know that the sender is actually who they say they are?.
I am confused.Some reading might help. A pretty good starting point is "Beginning Cryptography with Java" by David Hook published by Wrox.

Similar Messages

  • How to seperate the data with comma seperator ??

    Hi,
      How to seperate the data with comma seperator ??
    E.g i havea row like
    Userid,number of days,Total Records
    user1,10,100000
    So,i will get 10,10000 in the same field and i need to seperate 10 and 10000 so what is the abap function for that
    Praff

    like this ...
    SPLIT field AT ',' INTO
       userid
       days
       records.
    is this what you need?
    Mike

  • How to submit the Data with Business rule auto executed with VBA in excel?

    Anyone knows how can I submit the data into planning with the business rule auto executed in planning?
    Currently, I am using HypExecuteCalcScriptEx () + HypSubmitData() in my program that auto executed the business rule prior saving the data into planning.
    However when it try to run HySubmitData(), the Business rule window pops up again and ask user to run the business rule again.
    Therefore, is there a way that I can submit the data with auto execute the business rule?
    many thanks, highly appreciate !!!!!!

    Hi Rafeek,
    One solution is to set the column width after manually or programmatically refresh the PivotTable, for example:
    Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)
    Dim ws As Worksheet
    Set ws = Application.ActiveWorkbook.ActiveSheet
    ws.Columns("A").ColumnWidth = 10
    End Sub
    Another option is to set the column width, then protect the columns from been updated by the user, before refreshing the PivotTable, unprotect the worksheet. For example:
    Public Sub LockColumnA()
    Dim ws As Worksheet
    Set ws = Application.ActiveWorkbook.ActiveSheet
    ws.Columns("A").ColumnWidth = 10
    ws.Columns("A").Locked = True
    ws.Protect "123"
    End Sub
    Public Sub UnprotectWorksheet()
    Dim ws As Worksheet
    Set ws = Application.ActiveWorkbook.ActiveSheet
    ws.Unprotect ("123")
    End Sub
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to sign the applet with verisign certificate?

    Hi,
    I got a test certificate from the Verisign.
    Now I want to know, how to sign my applet with that certificate?
    Thanks,
    Siva E.

    Hi!
    You have to create a keystore wich contains the certificate. I think you call keystore -import "verisign.cert"Try the command, and it will tell you what it needs.
    To do the acutal signing of an applet (jar-file), you write somehting like this:
    jarsigner  -keystore "NameOfKeystore" -keypass "PasswordToPrivKey"  -storepass "PasswordToStore" "YourJarFile.jar" "CertAlias"The cert alias is an alias you created when importing the certificate. Hope it Helps!
    Henrik

  • How to check  the date with current day after 5 days

    Hello,
    I need to make the visible of delete button in my struts application. I've application in which user can be deactivated. If the user is deactivated and the admin can't delete the user for the specific period of time (set in property file). while deactivating the user, system time is set. and 5 days after the system time's set, i need to make the button visible.
    This is my code.
    Calendar cal = Calendar.getInstance();
    Date deActivatedDate = null;
    deActivatedDate =new Date(userData.getDeActivatedTime().getTime());// Set it in the Calendar object
    cal.setTime(deActivatedDate);                    // Add 5 days
    cal.add(Calendar.DATE, 5);// get the current date
    Calendar currentCal = Calendar.getInstance();
    Date currentDate = new Date();
    currentCal.setTime(currentDate);// check if the de-activation time is over.
    if (cal.get(Calendar.DATE) < currentCal.get(Calendar.DATE)) {
    userData.setDeletionAllowed(true);}
    can anyone help to solve this issue?

    What's the problem with the code that you posted?

  • How to analyse the data with &without free form of planning

    Hello Expert's,
    I am new to this concept's and I want to know the difference between with Free form &without Free form in SmartView of Planning data.I need a navigation path to know the difference between these two.
    Thanks in advance

    Thanks, i think i figured it out. I changed the cpx files in my client projects to point to the new data source.
    And i also added the new data source on the Application Server: I added a new data source for each BC4J module (with the Enterprise Manager UI) and i also changed the data-sources.xml files in the directory j2ee/application-deployment and j2ee/applications.

  • How to restrict the data with Filter in Query - Updated the description

    Hi all,
    Free Characteristics: u2018Service Orderu2019 & u2018Statusu2019.
    Key Figures: u2018Response Timeu2019 & u2018Data Record Counteru2019.
    Calculated Key Figure: u2018Resp Time > 1 hru2019.
    Only u2018Plantu2019 is in ROWS and u2018Resp Time > 1 hru2019 & u2018Data Record Counteru2019 are in COLUMNS section.
    The report looks like the below:
    Plant---Resp Time > 1 hr -
    Data Record Counter
    100--1--
    2
    101--1--
    3
    After dragging the u2018Service Ordersu2019 from u2018Free Characteristicsu2019 , the report looks like the below:
    Plant---Service Order -
    Resp Time > 1 hr ---Data Record Counter
    100--111--
    1
    100--120--
    1
    101--130--
    1
    101--141--
    1
    101--150--
    1
    I want only records whose u2018STATUSu2019 is u2018Yu2019. The u2018STATUSu2019 is u2018Blanku2019 for Service Orders 12, 13 & 15
    and those records should not be there in the report.
    The report should be like the below:
    After dragging the u2018Service Ordersu2019 from u2018Free Characteristicsu2019, the report looks like the below:
    Plant---Service Order -
    Resp Time > 1 hr ---Data Record Counter
    100--111--
    1
    101--141--
    1
    After creating the Restricted KF u2018Countu2019 on u2018Data Record Counteru2019 by restricting u2018STATUSu2019 to u2018Yu2019 and
    dragging the u2018Service Ordersu2019 from u2018Free Characteristicsu2019, the Count shows ZERO :
    Plant---Service Order -
    Resp Time > 1 hr ---Count
    100--111--
    0
    100--120--
    0
    101--130--
    0
    101--141--
    0
    101--150--
    0
    If I keep the Filter (globally) on 'STATUS = Y' then it returns 'NO Data'.
    If I keep the u2018Service Ordersu2019 is in u2018Rowsu2019 and the Filter on u2018STATUSu2019 (u2018Yu2019) then it works fine, but the report should be based on PLANT.
    Thanks in advance.
    Reagrds,
    Venkat.

    Hi Gurus,
    Thanks for u r all prompt replies...
    Got the Solution...
    Actually no need to work at query level...
    iN Multiprovider.... we can select the WBS element Char for which ever cube data we want... just drop down the char in to the dimension which we need and R/click the Char select identification of participating char.. un-select the check box for char WBS element for the Cubes which we dont require the data......
    Thanks to all
    Cheers
    Lajwanth
    Edited by: Lajwanth Singh on Apr 27, 2010 10:41 PM

  • How to spool the data with out space

    Hi, My version is 10g. I am trying to spool the file. this is my sql file looks like.
    set pagesize 0
    set heading on
    set verify off
    set linesize 32767
    set trimspool on
    set feedback off
    set termout off
    set colsep '~'
    set underline off
    set echo off
    set term off
    sET NEWPAGE 0
    --SET SPACE 0
    SET MARKUP HTML OFF SPOOL OFF
    spool C:\text0728.txt;
    SELECT DISTINCT a.m_name, a_code, a.p_id, a.p_name,
    a.p_type, e._name, e.s_list from mname a,slist e
    where a.p_id=e.p_id;
    spool off;
    my spool file looks like this
    codename~matrix        ~888~nametarget           ~in~todao~~
    codename1~matrix1        ~879~name           ~in~todao~
    If we see matrix value have space *~matrix ~*
    I want the value to spool with out the space i.e *~matrix~*
    What to set for my requirment in sql file?
    Thanks.

    select a.m_name,
             regexp_replace(a_code,'[[:space:]]matrix[[:space:]]','matrix') as a_code,
             a.p_id,
             a.p_name,
             a.p_type,
             e._name, e.s_list *
    from
         mname a,slist e
    where
        a.p_id=e.p_id;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to take the data from excel list to sap r/3(with time interval)

    hi experts,
       how to transfer the data from a third party system(if it is in format of excel) to sap r/3.with that in a particular time interval,it will delete the data from excel sheet.

    Hi
    use the Fm
    'ALSM_EXCEL_TO_INTERNAL_TABLE'
           EXPORTING
                filename                = p_path
                i_begin_col             = '1'
                i_begin_row             = '2'
                i_end_col               = '2'
                i_end_row               = '500'
          giving the starting row and column and passing the ending row and column name
    Reward points if useful........
    Regards,
    Nitin Sachdeva

  • My Mac Pro tower quad core crashed and is showing a NO sign (the circle with a slash through it). How do I safely get it to come back up ? Model A1186

    My Mac Pro tower quad core crashed and is showing a NO sign (the circle with a slash through it). How do I safely get it to come back up ? Model A1186

    General purpose Mac troubleshooting guide:
    Isolating issues in Mac OS X
    Creating a temporary user to isolate user-specific problems:
    Isolating an issue by using another user account
    Identifying resource hogs and other tips:
    Using Activity Monitor to read System Memory and determine how much RAM is being used
    Starting the computer in "safe mode":
    Mac OS X: What is Safe Boot, Safe Mode?
    To identify potential hardware problems:
    Apple Hardware Test
    General Mac maintenance:
    Tips to keep your Mac in top form
    Troubleshooting: My computer won't turn on
    https://support.apple.com/kb/TS1367
    Where are your bootable backups and clones stored?
    What do you have to boot from to restore or attempt to recovery files that are not backed up?
    It won't be a PowerMac. People tend to think they look alike? or mean the same thing.
    http://www.everymac.com/systems/apple/mac_pro/specs/mac-pro-quad-2.66-specs.html
    Try zap PRAM and SMC Reset. If you have ATI 5770 which many have upgraded to you won't be able to use older DVD or systems than 10.6.5

  • HT1212 Using the "if you have never synched with itunes" instructions, will I lose all data on the phone? That is the most important information, how to recover the data. The phone is fungible.

    Using the "if you have never synched with itunes" instructions, will I lose all data on the phone? That is the most important information, how to recover the data. The phone is fungible.

    Thanks @ KiltedTim, but losing "only" any data is really not acceptable and, in this case, the phone had not been backed up, but thanks for taking the time. Also, yes, fungible means what I think it means. An iphone is a completely substitutible commodity, unlike my data, so instructions that inform me as to how to fix a phone I could replace for a small sum of money while failing to address the more important issue of the data are almost useless - they potentially save me the $99 it would cost me to replace the phone if I were so inclined to trust another apple product. Not worth the hour it took to find them or the 35 minutes on the phone to confirm my suspicions about the data.

  • How to pass the data from a input table to RFC data service?

    Hi,
    I am doing a prototype with VC, I'm wondering how VC pass the data from a table view to a backend data service? For example, I have one RFC in the backend system with a tabel type importing parameter, now I want to pass all the data from an input table view to the RFC, I guess it's possible but I don't know how to do it.
    I try to create some events between the input table and data service, but seems there is no a system event can export the whole table to the backend data service.
    Thanks for your answer.

    Thanks for your answer, I tried the solution 2, I create "Submit" button, and ser the mapping scope to  be "All data rows", it only works when I select at least one row, otherwise the data would not be passed.
    Another question is I have serveral imported table parameter, for each table I have one "submit" event, I want these tables to be submitted at the same time, but if I click the submit button in one table toolbar, I can only submit the table data which has a submit button clicked, for other tables, the data is not passed, how can I achieve it?
    Thanks.

  • How to get the data from mysql database which is being accessed by a PHP application and process the data locally in adobe air application and finally commit the changes back in to mysql database through the PHP application.

    How to get the data from mysql database which is being accessed by a PHP application and process the data locally in adobe air application and finally commit the changes back in to mysql database through the PHP application.

    If the data is on a remote server (for example, PHP running on a web server, talking to a MySQL server) then you do this in an AIR application the same way you would do it with any Flex application (or ajax application, if you're building your AIR app in HTML/JS).
    That's a broad answer, but in fact there are lots of ways to communicate between Flex and PHP. The most common and best in most cases is to use AMFPHP (http://amfphp.org/) or the new ZEND AMF support in the Zend Framework.
    This page is a good starting point for learning about Flex and PHP communication:
    http://www.adobe.com/devnet/flex/flex_php.html
    Also, in Flash Builder 4 they've added a lot of remote-data-connection functionality, including a lot that's designed for PHP. Take a look at the Flash Builder 4 public beta for more on that: http://labs.adobe.com/technologies/flashbuilder4/

  • How to validate the dates in the table control ?

    How to validate the dates in the table control ?
    Can I write like this ?
    LOOP AT it_tab .
    CHAIN.
    FIELD : it_tab-strtdat,it_tab-enddat.
    module date_validation.
    ENDCHAIN.
    ENDLOOP.
    Module Date_validation.
    ranges : vdat type sy-datum.
    vdat-sign = 'I'.
    VDAT-LOW = it_tab-STRTDAT.
    VDAT-HIGH = it_tab-ENDDAT.
    VDAT-OPTION = 'BT'.
    APPEND VDAT.
    WHAT CODE I have to write here to validate ?
    and If I write like this How can we know which is the current row being add ?
    It loops total internal table ..?
    Bye,
    Muttu.

    Hi,
    I think there is no need to put chain endchain.
    To do validation you have to write module in PAI which does required validations.
    Thanks
    DARSHAN PATEL

  • How to delete the data from partition table

    Hi all,
    Am very new to partition concepts in oracle..
    here my question is how to delete the data from partition table.
    is the below query will work ?
    delete from table1 partition (P_2008_1212)
    we have define range partition ...
    or help me how to delete the data from partition table.
    Thanks
    Sree

    874823 wrote:
    delete from table1 partition (P_2008_1212)This approach is wrong - as Andre pointed, this is not how partition tables should be used.
    Oracle supports different structures for data and indexes. A table can be a hash table or index organised table. It can have B+tree index. It can have bitmap indexes. It can be partitioned. Etc.
    How the table implements its structure is a physical design consideration.
    Application code should only deal with the logical data structure. How that data structure is physically implemented has no bearing on application. Does your application need to know what the indexes are and the names of the indexes,in order to use a table? Obviously not. So why then does your application need to know that the table is partitioned?
    When your application code starts referring directly to physical partitions, it needs to know HOW the table is partitioned. It needs to know WHAT partitions to use. It needs to know the names of the partitions. Etc.
    And why? All this means is increased complexity in application code as this code now needs to know and understand the physical data structure. This app code is now more complex, has more moving parts, will have more bugs, and will be more complex to maintain.
    Oracle can take an app SQL and it can determine (based on the predicates of the SQL), which partitions to use and not use for executing that SQL. All done totally transparently. The app does not need to know that the table is even partitioned.
    This is a crucial concept to understand and get right.

Maybe you are looking for

  • Loading lag when browsing images?

    When in the Aperture viewer as I scroll through my photos using the arrow keys I see a loading icon on each image for 3-5 seconds.  What is Aperture doing while I wait for the loading icon?  Reprocessing my RAW image?  Loading an existing preview fro

  • Color Laserjet pro MFP M176n control panel not working

    the control panel in the Color Laserjet pro MFP M176n is not working, is all blank, i can´t see anithhing in it. Is there a reset button or should i take it to the store where i buy it for a checkup? thank you

  • Hyperion Shared Services Question

    Hi, I need to see the filters that have been assigned to a particular group in HSS. We have a folder called projects in the tree where the analytic server is added, but when I go to the corresponding application under that analytic server to check, t

  • JDeveloper 11.1.1.5.0 and the Fusion Order Sample Application

    Hi all I am trying to explore SOA Suite 11g features, particularly the BPM part. I am unable to find any tutorials relating to this feature (can someone point me to some?) and therefore am trying to simply install the Fusion Order demo to have a look

  • Problems with Acer AL2216Wd

    I purchased a new wide screen Monitor for work today, and now having some trouble with it. Using DVI: When I connect the MacMini and the Acer 22" Monitor using DVI connection I get "No Signal" on boot. If I boot using another monitor, and then connec