Encrypt data with public key?

I am trying to find a class that support encryption with PublicKey.
In the class Signature there is a method "initSign" that takes a PrivateKey as argument, but that is used for signing certificates.
What I am looking for is to make A encrypt some data with B' public key that B can decrypt with its private key...is there any class for this scenario?

You might want to check out these, if you haven't already:
http://java.sun.com/j2se/1.5.0/docs/guide/security/CryptoSpec.html
http://java.sun.com/j2se/1.5.0/docs/guide/security/jce/JCERefGuide.html
http://java.sun.com/j2se/1.5.0/docs/api/javax/crypto/package-summary.html
http://java.sun.com/j2se/1.5.0/docs/api/javax/crypto/interfaces/package-summary.html
http://java.sun.com/j2se/1.5.0/docs/api/javax/crypto/spec/package-summary.html

Similar Messages

  • How encrypt msg with Public Key ?

    I want to encrypt my Session Key with the public key of the recipient but how can I do ?
    I know how to encrypt with the Secret Key but not with the Public Key.
    Thanks for response
    Nicolas

    It depends on the cryptosystem of which the public key you are having.
    If it is of RSA then you have to get the cipher of RSA and pass the session key bytes as input to it.

  • Encrypt/Decrypt data, multiple public keys using Bouncy castle api?

    Hi all.
    I need to implement encrypt/decrypt functionality of some data with many public keys using bouncy castle api and EnvelopedData class in java 1.4 SE.
    Could someone give me examples how to do it. I searched whole the internet and i could not find simple example.

    Hi thanks very much.
    I had a quick look at the examples. I will see if they could help me.
    Here is more specific what i want:
    Encrypt data with multiple public keys that are kept in .pkcs12 file.
    And decrypt the data using coresponding private key after that.
    I must use bouncy castle api for java 1.4 se.
    Best regards
    Edited by: menchev on Nov 13, 2008 8:26 AM

  • Optimal read write performance for data with duplicate keys

    Hi,
    I am constructing a database that will store data with duplicate keys.
    For each key (a String) there will be multiple data objects, there is no upper limit to the number of data objects, but let's say there could be a million.
    Data objects have a time-stamp (Long) field and a message (String) field.
    At the moment I write these data objects into the database in chronological order, as i receive them, for any given key.
    When I retrieve data for a key, and iterate across the duplicates for any given primary key using a cursor they are fetched in ascending chronological order.
    What I would like to do is start fetching these records in reverse order, say just the last 10 records that were written to the database for a given key, and was wondering if anyone had some suggestions on the optimal way to do this.
    I have considered writing data out in the order that i want to retrieve it, by supplying the database with a custom duplicate comparator. If I were to do this then the query above would return the latest data first, and I would be able to iterate over the most recent inserts quickly. but Is there a performance penalty paid on writing to the database if I do this?
    I have also considered using the time-stamp field as the unique primary key for the primary database instead of the String, and creating a secondary database for the String, this would allow me to index into the data using a cursor join, but I'm not certain it would be any more performant, at least not on writing to the database, since it would result in a very flat b-tree.
    Is there a fundamental choice that I will have to make between write versus read performance? Any suggestions on tackling this much appreciated.
    Many Thanks,
    Joel

    Hi Joel,
    Using a duplicate comparator will slow down Btree access (writes and reads) to
    some degree because the comparator is called a lot during searching. But
    whether this is a problem depends on whether your app is CPU bound and how much
    CPU time your comparator uses. If you can avoid de-serializing the object in
    the comparator, that will help. For example, if you keep the timestamp at the
    beginning of the data and only read the one long timestamp field in your
    comparator, that should be pretty fast.
    Another approach is to store the negation of the timestamp so that records
    are sorted naturally in reverse timestamp order.
    Another approach is to read backwards using a cursor. This takes a couple
    steps:
    1) Find the last duplicate for the primary key you're interested in:
      cursor.getSearchKey(keyOfInterest, ...)
      status = cursor.getNextNoDup(...)
      if (status == SUCCESS) {
          // Found the next primary key, now back up one record.
          status = cursor.getPrev(...)
      } else {
          // This is the last primary key, find the last record.
          status = cursor.getLast(...)
      }2) Scan backwards over the duplicates:
      while (status == SUCCESS) {
          // Process one record
          // Move backwards
          status = cursor.getPrev(...)
      }Finally another approach is to use a two-part primary key: {string,timestamp}.
    Duplicates are not configured because every key is unique. I mention this
    because using duplicates in JE has more overhead than using a unique primary
    key. You can combine this with either of the above approaches -- using a
    comparator, negating the timestamp, or scanning backwards.
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Signing code with Public Key

    Hi guys,
    I'm working on my thesis,and my prof. told me that I have to sign a
    java object with a public key.
    Looks to be impossible, but I asked him again and he confirmed what he
    said.
    How do I create a digital signature of a java object using a Publik
    Key??
    Thanks a Lot guys!!!
    Bye!

    How do I create a digital signature of a java object using a Public Key??Well as my fellow poster said it makes no sense siging (Encrypting) an Object using a Public Key as it would be available for access.
    If it is about Siging an Object with a Single Key where there is concept having a public / private key i think most of the Symmentric Encryption Algorithms come into picture. where there would be a single key used for both encrypting & decrypting data.
    However, you can very well have a look of the specified links below to recheck on things.
    http://www.unix.org.ua/orelly/java-ent/security/ch12_01.htm
    http://www.developer.com/java/other/article.php/630851
    http://mindprod.com/jgloss/digitalsignatures.html
    Hope these might be of some help...
    REGARDS,
    RaHuL

  • Allow privilleged users to enter into EXEC mode on login not working with public keys

    Hi,
    I have recently updated one of my Cisco ASA to v9.2(1) and noticed a function to get the perform authorization for exec shell access can do a auto-enable when logging in from ssh.
    The problem is that if I use a private/public key authentication with a user it won't do the auto-enable feature. If I login without keys and using my password, it jumps into privilleged exec mode as it should.
    Anyone else had this issue?
    Config:
    aaa authentication ssh console LOCAL
    aaa authorization exec LOCAL auto-enable
    username user password xxxxxx encrypted privilege 15
    username user attributes
     ssh authentication publickey 22:af:xxxxxx hashed
    Any answer will be highly appreciated. 
    P.S I'm totally new in this forum.

    Would you be able to open a TAC SR and once you do , Email me the SR no and i will look into this issue.
    [email protected]
    Thanks and Regards,
    Vibhor Amrodia

  • Problem with public key ssh login

    Weird problem just appeared. Home computer has two accounts (A and B). I allow ssh login to both accounts via public key login (ssh-keygen). Two remote computers with accounts A' and B' on one, and A" and B" on the other.
    I can ssh into the home computer account B from account B' on one computer. I can log into the home computer account B from account B" on the other computer. I cannot ssh into the home computer account A from either A' or A", but I could last week.
    Here is what the .ssh directories look like:
    Home computer, account A:
    total 8
    drwx------ 4 userA groupA 136 Jan 30 11:51:38 2006 .
    drwxrwxr-x 25 userA groupA 850 Nov 8 20:05:58 2006 ..
    -rw-r--r-- 1 userA groupA 1216 Jan 10 13:20:20 2006 authorized_keys2
    -rw-r--r-- 1 userA groupA 447 Sep 25 15:28:42 2006 known_hosts
    Home computer, account B:
    total 16
    drwx------ 5 userB groupB 170 Oct 2 09:52:02 2006 .
    drwxr-xr-x 23 userB groupB 782 Nov 9 08:26:03 2006 ..
    -rw------- 1 userB groupB 6148 May 19 17:54:58 2006 .DS_Store
    -rw-r--r-- 1 userB groupB 1228 Jan 10 13:24:15 2006 authorized_keys2
    -rw-r--r-- 1 userB groupB 242 Oct 2 09:52:02 2006 known_hosts
    Remote computer 1, account A':
    total 16
    drwx------ 6 userA' groupA' 204 Nov 9 09:55:12 2006 .
    drwxr-xr-x 29 userA' groupA' 986 Nov 9 09:41:21 2006 ..
    -rw-r--r-- 1 userA' groupA' 41 Mar 13 12:13:17 2006 config
    -rw------- 1 userA' groupA' 736 Nov 20 13:38:54 2005 id_dsa
    -rw-r--r-- 1 userA' groupA' 607 Nov 20 13:38:54 2005 id_dsa.pub
    -rw-r--r-- 1 userA' groupA' 246 Jan 10 09:41:27 2006 known_hosts
    Remote computer 1, account B':
    total 16
    drwx------ 5 userB' groupB' 170 Nov 9 08:23:04 2006 .
    drwxr-xr-x 18 userB' groupB' 612 Nov 9 09:52:11 2006 ..
    -rw------- 1 userB' groupB' 6148 Nov 9 08:23:04 2006 .DS_Store
    -rw------- 1 userB' groupB' 668 May 25 08:51:51 2006 id_dsa
    -rw-r--r-- 1 userB' groupB' 2481 Oct 30 09:00:57 2006 known_hosts
    Remote computer 2, account A":
    total 12
    drwx------ 5 userA" groupA" 170 Jan 25 10:59:54 2006 .
    drwxr-xr-x 20 userA" groupA" 680 Nov 9 08:19:30 2006 ..
    -rw------- 1 userA" groupA" 736 Jan 10 13:14:16 2006 id_dsa
    -rw-r--r-- 1 userA" groupA" 609 Jan 10 13:14:16 2006 id_dsa.pub
    -rw-r--r-- 1 userA" groupA" 3376 Oct 31 19:48:25 2006 known_hosts
    Remote computer 2, account B":
    total 12
    drwx------ 5 userB" groupB" 170 Jan 25 11:41:48 2006 .
    drwx------ 22 userB" groupB" 748 Nov 9 10:33:00 2006 ..
    -rw------- 1 userB" groupB" 736 Jan 10 13:11:50 2006 id_dsa
    -rw-r--r-- 1 userB" groupB" 615 Jan 10 13:11:50 2006 id_dsa.pub
    -rw-r--r-- 1 userB" groupB" 2947 Nov 7 10:18:27 2006 known_hosts
    I had copied the A' id_dsa.pub from remote computer 1 to the home computer account A authorized_keys2, then I copied the A" id_dsa.pub from remote computer 2 and had appended it to the home computer account A authorized_keys2. I had done a similar thing with accounts B', B", and B on their respective computers.
    All worked great for many months, until today, when ssh connections from A' or A" into A give me the dreaded
    Permission denied,gssapi-keyex,gssapi-with-mic) error message. Pretty certain that it was as recent as earlier this week I made the A'-->A ssh connection and all was well. Meanwhile, ssh connections from B' or B" into B still work fine.
    As near as I can tell, file ownerships and permissions look okay. While ssh'ed into B from B' I even did a
    cat /Users/userA/.ssh/authorized_keys2
    and then in another Terminal window, local to the remote computer, I did a
    cat /Users/userA/.ssh/id_dsa.pub
    In the terminal windows, each key wraps over about five-and-a-half lines, and I spotchecked like the last half-dozen characters, on each Terminal window line, of remote computer 1, account A' id_dsa.pub and the first pub key entry in authorized_keys2 in home computer account A. They all match.
    I even keep a clone backup of my hard drive, and the date/timestamp of /etc/sshd_config hasn't changed (although, I'm a bit mystified why it is dated as recently as it is -- Sep 29 2006 -- don't remember doing anything to it)
    So, I'm really confused, and not sure what to try or where to look next.
    2001 Quicksilver G4 (M8360LL/A)   Mac OS X (10.4.8)  

    Hi j.v.,
    Home computer, account A:
    total 8
    drwx------ 4 userA groupA 136 Jan 30 11:51:38 2006 .
    drwxrwxr-x 25 userA groupA 850 Nov 8 20:05:58 2006 ..
    The parent directory ".." of the directory ".ssh", i.e. home directory of account A, is group-writeble. SSH considers this as "insecure". You should make it writable only by the owner.
    A@Home$ cd (cd to the home directory)
    A@Home$ chmod g-w .
    HTH
    PowerMac G4   Mac OS X (10.4.7)  

  • How to send Encrypted message using public key in Business Service

    Hi,
    I have one public key (abc.cer) which is given by provider. I have to send encrypted message to Provider using public key. How to achieve it in OSB??
    Thanx
    Edited by: Vinit Ahuja on Jun 16, 2011 3:17 AM

    These are the steps needed to accomplish this:
    1. Import the public certificate in the TrustStore of the OSB Weblogic Server.
    2. Export the public certificate in PEM format. (This will be needed to embed in the custom ws policy)
    3. Create a custom WS policy, with the necessary encryption configuration information. I have placed a sample WS - Policy that I have used @ http://dl.dropbox.com/u/19901533/Sample_Custom_WSPolicy_Encryption.doc for your reference.
    Use a unique value for the wsu:Id in the policy.
    4. Apply this custom policy on the business service in the Request section (assuming you only need to encrypt the request fields)
    5. Activate the changes and then test the business service. You can enable tracing on the BS to validate the encrypted content in the logs.
    Hope this helps.
    Thanks,
    Patrick

  • How to encrypt data with PublicKey???

    Hi, I need to know how I can encrypt data (in byte[ ]) with a PublicKey instance.... I'm using BouncyCastle....
    THANKS...
    Andres

    http://javaalmanac.com/egs/javax.crypto/pkg.html#Encrypting%20and%20Decrypting

  • Encrypting data with TDE

    Hi Folks,
    This is my firs post here.
    I have following task.
    We need to encrypt bulk of data.
    The biggest table for encrypt has 545,155,800 rows and on test system(not production) encryption had got 58:07:34.32. We have not this time. Only 6 hours in maintenance window.
    Can you suggesting me what Oracle functionals to use for resolve our issue?
    May be any step by step script??
    Any suggesting at all :)

    Is there a reason that the entire encryption process needs to happen during the downtime window?
    My bias would be to create a new table in which the column is encrypted (assuming that encrypting the column rather than encrypting the tablespace is the right decision) and then copy the data from the old table to the new table while the system is active. You'll need some way of either tracking changes or identifying changed rows. If you have a column that tracks when a row was modified, you could probably use that. Or you could use one of the various change detection technologies Oracle provides (CDC, Streams, etc.). Or you could let the DBMS_REDEFINITION package handle tracking changes via materialized view logs. During your downtime window, you would then just need to copy whatever data still needs to be copied to the new table (presumably a handful of rows) and do whatever DDL is necessary to drop the old table and rename the new table, recreate any foreign key constraints, etc.
    Justin

  • How to setup an ikev2 VPN with public key authentica​tion with your BB10 device

    This setup will allow you to run a VPN between your BB10.2 (and probably BB10.1) device and a debian linux computer (I am running the testing stream).  You will need to tweak this config (and possibly install strongswan server on your LAN's gateway) to get access to network resources, or access the internet via the VPN.  I have created this setup with the intention of accessing files/services on the debian computer only.
    1.  Install strongswan on your debian machine(I have v4.6.4 installed, I think the current testing version is v5.1.  If you install v5+, some lines in the config may be obsolete), and install any other extra packages you are prompted to install: 
    apt-get install strongswan strongswan-ikev1 strongswan-ikev2 strongswan-starter openssl ipsec-tools
    2.  Generate certificates on your debian server in any, starting with a certificate authority.  Edit the C= O= CN= fields to whatever you want:
    ipsec pki --gen --outform pem > caKey.pem
    ipsec pki --self --in caKey.pem --dn "C=CA, O=none, CN=Certificate-Auth" --san="Certificate-Auth" --ca --outform pem > caCert.pem
    Generate a server keypair (again, editing the same fields as I indicated above.  The CN= field should be lan ip address of your strongswan server.  I would also put this as the address in --san=, or you can specify your hostname(if you have one, i.e. mydomainname.com):
    ipsec pki --gen --outform pem > serverKey.pem
    ipsec pki --pub --in serverKey.pem | ipsec pki --issue --cacert caCert.pem --cakey caKey.pem --dn "C=CA, O=none, CN=192.168.1.100" --san="192.168.1.100" --flag serverAuth --outform pem > serverCert.pem
    Generate a keypair for your BB10 device (choose a CN=, and use it in the --san field @your server lan ip or hostname:
    ipsec pki --gen --outform pem > userKey.pem
    ipsec pki --pub --in userKey.pem | ipsec pki --issue --cacert caCert.pem --cakey caKey.pem --dn "C=CA, O=none, CN=bb10" --san "[email protected]"  --flag serverAuth --outform pem > userCert.pem
    3.  After generating your keys, package the client keys for your BB10 device(you will be asked to create a password): openssl pkcs12 -export -in userCert.pem -inkey userKey.pem -out bb10.pfx
    Copy the bb10.pfx file, and serverCert.pem to your BB10 device and import the certificates into the certificate store(Open Settings --> Security and Privacy --> Certificates --> Import)
    4. Move the certificates into the appropriate folders on your debian server: 
    mv caKey.pem /etc/ipsec.d/private
    mv caCert.pem /etc/ipsec.d/cacerts
    mv serverKey.pem /etc/ipsec.d/private
    mv serverCert.pem /etc/ipsec.d/certs
    5. Enable ip forwarding on your debian machine:
    edit /etc/sysctl.conf - change the following value as follows:
    net.ipv4.ip_forward=1
    Close the file and save changes.  To enable changes, type:  sysctl -p /etc/sysctl.conf
    6.  Edit config files:
              ipsec.secrets:
    : RSA serverKey.pem
            ipsec.conf:
    config setup
            strictcrlpolicy=no
            uniqueids=yes
    conn %default
            ikelifetime=60m
            keylife=20m
            rekeymargin=3m
            keyingtries=1
            keyexchange=ikev2
            leftfirewall=yes
            dpddelay=30
            dpdtimeout=120
            dpdaction=clear
    conn bb10
            mobike=yes
            ike=aes256-sha1-sha1-modp1024!
            esp=aes256-sha1!
            left=%defaultroute
            leftid="C=CA, O=none, CN=192.168.1.100"
            leftcert=serverCert.pem
            right=%any
            rightsourceip=10.10.0.1
            rightid="C=CA, O=none, CN=bb10"
            rightauth=pubkey
            leftauth=pubkey
            pfs=yes
            auto=add
    7. Start the ipsec service on your debian machine: service ipsec stop; service ipsec start
    8. Set up the VPN connection on your blackberry: Settings -->Network Connections --> VPN --> Add.
    a) Profile Name:  Give your VPN a name
    b) Server Address:  Enter your server's address
    c) Gateway Type: Generic IKEv2 VPN Server
    d) Authentication Type: PKI
    e) Authentication ID Type:  Identity Certificate Distinguished Name
    f) Client Certificate: The client certificate you imported should show up in the dropdown
    g) Gateway Auth Type: PKI
    h) Gateway Auth ID Type: Identity Certificate Distinguished Name
    i) Gateway CA Certificate:  Find the certificate authority you imported.  If you used the same name as I did above when creating the certificate, if will be called "Certificate-Auth".
    j) Perfect forward secrecy : ON
    k) Change IKE Lifetime to 3600
    l) Change IPSEC lifetime to 1200
    You can leave everything else on default settings.  Save your VPN profile.
    9. Connect to your VPN.  You should now be able to ping both ways between your blackberry and debian host.  Using the above configuration, your blackberry device will have the ip address of 10.10.0.1.

    There have been numerous bb10 updates (now 10.2.1.2977) since I first posted this mini how-to-I am not sure if it was the bb10 updates, or updates to strongswan (now v5.2.0) or my linux kernel (v3.15.3), though I am now able to use stronger hash and elliptic curve key exchange.  I am using sha384 in my example, though have also got it working with sha512.  Give it a try:
    Simply use the same process I detailed before, though change the following lines in ipsec.conf:
    ike=aes256-sha1-sha1-modp1024!
    esp=aes256-sha1!
    to
    ike=aes256-sha384-ecp521
    esp=aes256-sha384-ecp521
    Be sure to restart strongswan after you change these lines in the config.
    After this is done, change 'Automatically determine algorithm' to off in the VPN profile settings of your VPN connection profile on your blackberry.  I'm not sure why it doesn't work automatically.  State the following in this section:
    IKE DH Group:  21
    IKE CIpher: AES (256-bit key)
    IKE Hash: SHA384
    IKE PRF: HMAC-SHA384
    IPSec DH Group: 21
    IPSec Cipher: AES (256-bit key)
    IPSec Hash: SHA384

  • Encrypting a vote with a servers public key...HELP!

    Hey, I really need some help( online voting application)....what I want to do it allow a voter to be able to submit a ballot(vote) via servlets, they encrypt the ballot with the servers public key and then the ballot is stored in a database, where at another time the administrator may decrypt the ballot(s) using the servers private key. I have already sorted the voters authentication(MD5), and at the moment the servlet submits the ballot in an unencrypted form....so I just need a little help from here. I enclose my code and I would be truly grateful of someone could give me a hand.
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.* ;
    public class CastVote extends HttpServlet{
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException,IOException{
    try {
    String jmulligan= request.getParameter("jmulligan");
    String pkelly=request.getParameter("pkelly");
    String mjones=request.getParameter("mjones");
    response.setContentType("text/html");
    PrintWriter out=response.getWriter();
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection ("jdbc:odbc:evoting");
    Statement stmt = con.createStatement();
    stmt.executeUpdate(
    "INSERT INTO Ballot (JMulligan, PKelly, MJones)"
    + "VALUES ('"+jmulligan+"','"+pkelly+"','"+mjones+"') ");
    stmt.close();
    out.println("<HTML>\n"+
    "<HEAD><TITLE>EVoting</TITLE></HEAD>\n"+
    "<BODY BGCOLOR=\"127734\">\n"+
    "<H1>Your Ballot has been entered as follows</H1>\n"+
    "<H1>J Mulligan got "+ jmulligan +"</H1>\n"+
    "<H1> M Jones got "+ mjones +"</H1>\n"+
    "<H1> P Kelly got "+ pkelly +"</H1>\n"+
    "</BODY></HTML>");
    catch( Exception e ) {
    System.out.println(e.getMessage());
    e.printStackTrace();
    thanks
    Jacinta
    PS I have ssl configured, with a self signed cert.

    Hey!
    I am also in the middle of doing an en=voting application as part of my thesis! Its interesting to see the way other people do the voting. Well, my experience so far is that I cannot get public/private key encryption to work. I have posted many topics on this forum regarding it and the reason it wont work is that the ballot that I am trying to enctypt is too large for the ballot object . I used the RSA algoithm and it wasn't able to handle my large object. So instead I have just used a symmetric algorithm and that works fine. I think its the DES algorithm. The only problem with this is that you are using the same key to encrypt and decrypt the ballot. I dont think this is secure. It has been reccomended to me that I use this symmetric algorithm as it is, but that I then use public/private key to encrypt the symmetric key! I still have a problem with this because if the key is still encrypted with public key, the user must have acces to the private key to decrypt the symmetric key to decryt the ballot. See where I'm going?
    I would love to know of an asymmetric algorithm that can encrypt large objects. That would solve the whole security issue. I will post a replyhere if I find out the answer.
    By the way, how is your project going?
    All the best,
    Chris Moltisanti

  • Send encryption data through network

    I'm doing encryption data exchanging project. I can describe my scenario anyone can give me good suggestion.
    I use RSA Key pair. Client side encrypt the data using private key and server decrypt those data using particular public key. I store my keys in keystore. For one attempt I use public and private keys belong to one alias. My problem is when doing decryption in server side I got error message (BadPaddingException: Data must start with zero). But if I do encryption and decryption in same class using same keys without any client/server connection it works properly.
    So, if anyone can give me any advice or suggestion, I'm very appreciat

    ivanovpv wrote:
    I think problem is somewhere in data transmission. During transmission either server or client adds extra padding information.No. For symmetric block based encrypted the clear text has to be padded to make it a full block. This is normally done as part of the encryption process using PKCS5 padding. Padding is also reqired for RSA encryption so as to make sure the cleartext ^ public_exponent is greater than the modulus. This is normally done using PKCS1 padding.
    If the encrypted data is corrupt then one normally gets a exception such as BadPaddingException when decrypting using a symmetric algorithm or an exception indicating that the padded data should start with a zero in the case of RSA encryption.
    It is almost certain that the OP has corrupted his encrypted data or his key, possibly by converting to a String without using Hex or Base64 encoding. Without seeing his code we will probably never know.
    >
    I would suggest just get your public key (i hope it's just a long/String probably wrapped within some class) then explicitly convert it into character array (best is to use UTF-8 encoding) - then transmit through network. On other side decode from UTF-8 character array into long/String - probably you'd need to instantiate public key object from your long/String and enjoy!String should never be used as a container for binary data and keys are binary data. Just converting them to a String specifying utf-8 will almost certainly corrupt them. If one must have a String version of any binary data whether it be a key or cipher text one should reversibly encode it using something like Base64 or Hex.

  • Encrypting data J2ME

    Hi
    I am developing a number of applications using J2ME. They run on mobile phones and need to be able to send data to a server. I need to encrypt this data as it contains personal information about the user. I cant use HTTPS because some of the applications use MIDP 1.0 and only support HTTP.
    So I want to encrypt the data myself and I was wondering if you could help me with my approach and answer some questions...
    I think the best way is to use RSA public/private keys in combination with a symmetric encrypting algorithm. So the mobile will have the public key part and the server will have the private key. The data will be encrypted using a symmetric algorithm. The key used in the encryption will then be encrypted using the public key. Both the encrypted key and the encrypted data will then be sent to the server. The server uses its private key to decrypt the key and then use the key to decrypt the data.
    How does that sound? I will be using Bouncy Castle crypto. What is the best way to generate a public/private key pair? I then need to somehow include the public key with the application. Should I randomly generate the symmetric key myself?
    Also what algorithm would you suggest for encrypting the data. Remember that it is on a resource constrained mobile device.
    If you have any other comments I would like to hear them. Thanks for your time.

    Thanks for the pointer. The thing is we changed our minds. We discovered strong encryption was not needed since our scheme is like the DVD encryption. The data is unencrypted by the application used by the person that does not have to know the data.
    We went with Rot13. jeje
    Thanks anyway.

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

Maybe you are looking for