Generating symmetric key with RSA

Hello,
I have a problem. I want to generate symmetric keys with the use of RSA. But RSA is not supported by Java 1.4.2 except for the signature class.
My question is can I generate symmetric keys using RSA and Bouncy Castle provider??? Or is there a way around ???
Thanks a lot,
Ravi

Or write your own RSA. here is some working code:
///////////////// class BigIntegerRSA /////////////////
import java.math.*;
import java.util.*;
public class BigIntegerRSA {
  int bits;
  BigInteger p, q, n, nPrime, e, d;
  public BigIntegerRSA(int _bits, BigInteger _p, BigInteger _q) {
    bits=_bits;
    p=_p;
    q=_q;
    n = p.multiply(q);
    nPrime = p.subtract(BigInteger.ONE).multiply( q.subtract(BigInteger.ONE));
    e=BigInteger.ZERO;
    BigInteger TEN=new BigInteger(""+10);
    for( e = nPrime.divide(TEN); !BigIntegerUtil.gcd( e, nPrime ).equals(BigInteger.ONE); e=e.add(BigInteger.ONE)){
    d = BigIntegerUtil.inverse( e, nPrime );
  public static BigIntegerRSA generate(int _bits) {
    BigIntegerRSA rsa= null;
    boolean verified=false;
    while(!verified){
      BigInteger p=BigInteger.probablePrime(_bits/2+1,new Random(System.currentTimeMillis()));
      BigInteger q=BigInteger.probablePrime(_bits/2+1,new Random(System.currentTimeMillis()));
      rsa= new BigIntegerRSA(_bits,p,q);
      verified= rsa.verify();
    return rsa;
  public BigIntegerRSAPublicKey getPublicKey(){
    return new BigIntegerRSAPublicKey(bits,e,n);
  public BigIntegerRSAPrivateKey getPrivateKey(){
    return new BigIntegerRSAPrivateKey(bits,d,n);
  public boolean verify() {
    //e * d % ( nPrime ) == 1
    BigInteger multiplied=e.multiply(d).mod(nPrime);
    if(!multiplied.equals(BigInteger.ONE)){
      return false;
    //test random
    BigIntegerRSAPublicKey pub=getPublicKey();
    BigIntegerRSAPrivateKey priv=getPrivateKey();
    BigInteger message, encoded, decoded;
    //random
    message=new BigInteger(bits-2, new Random(System.currentTimeMillis()));
    encoded=pub.code(message);
    decoded=priv.decode(encoded);
    if(!message.equals(decoded)){
      System.out.println("Failed to encode and decode "+message);
      return false;
    return true;
  public static void main( String [ ] args ){
    BigIntegerRSA rsa=BigIntegerRSA.generate(512);
    BigIntegerRSAPublicKey pub=rsa.getPublicKey();
    BigIntegerRSAPrivateKey priv=rsa.getPrivateKey();
    BigInteger message=new BigInteger("2938798723423429020");
    System.out.println( "message: " + message );
    BigInteger code = pub.code(message);
    BigInteger decode = priv.decode(code);
    System.out.println( "Code: " + code );
    System.out.println( "Decode: " + decode );
///////////////// class BigIntegerRSAPublicKey /////////////////
import java.math.*;
import java.util.*;
public class BigIntegerRSAPublicKey{
  int bits;
  BigInteger e,n;
  public BigIntegerRSAPublicKey(int _bits, BigInteger _e, BigInteger _n) {
    bits=_bits;
    e=_e;
    n=_n;
  public BigInteger code(BigInteger message) {
    if(message.bitLength()>bits){
      return null;//"Cannot encode anything with more bits than bits while message had message.bitLength() bits
    return message.modPow(e,n);
///////////////// class BigIntegerRSAPrivateKey /////////////////
import java.math.*;
import java.util.*;
public class BigIntegerRSAPrivateKey {
  int bits;
  BigInteger d, n;
  public BigIntegerRSAPrivateKey(int _bits, BigInteger _d, BigInteger _n) {
    bits=_bits;
    d=_d;
    n=_n;
  public BigInteger decode(BigInteger code)  {
    if(code.compareTo(n)>0){
      return null;//Cannot decode anything greater than n while code was code
    return code.modPow(d,n);
///////////////// class BigIntegerUtil /////////////////
import java.math.*;
import java.util.*;
public class BigIntegerUtil {
  // Internal variables for fullGcd
  private static BigInteger x;
  private static BigInteger y;
  public static BigInteger gcd( BigInteger a, BigInteger b )
    if( b.equals(BigInteger.ZERO) )
      return a;
    else
      return gcd( b, a.mod(b) );
  public static BigInteger inverse( BigInteger a, BigInteger n )
    fullGcd( a, n );
    return x.compareTo(BigInteger.ZERO)>0 ? x : x.add(n);
  private static void fullGcd( BigInteger a, BigInteger b )
    BigInteger x1, y1;
    if( b.equals(BigInteger.ZERO) )
      x = BigInteger.ONE;
      y = BigInteger.ZERO;
    else
      fullGcd( b, a.mod(b) );
      x1 = x; y1 = y;
      x = y1;
      y = x1.subtract(( a.divide(b) ).multiply(y1));
}And since BigInteger has the methods .toByteArray() and new BigInteger(byte[] b) this is perfect for encrypting and decrypting anything, eg a DES key or some other symmetric encryption

Similar Messages

  • Generate DES key with java card with JCRE 2.1.2

    Hi everyone,
    I want to generate DES key in my applet . my card supports GP 2.0.1 and JCRE 2.1.2 .
    I have tested my applet with JCRE 2.2.1 and used this JCSystem class functions to generate DES key and it compiles and works correctlly .
    but when I want to compile my applet with JCRE 2.1.2 I recieve an error which says that API 2.1.2 doesn't support JCSystem class .
    so I'll really appreciate it if anyone could tell me how can I generate DES key with JCRE 2.1.2
    and also I use JCSystem class functions to get my card's persistent and transistent memory , so with this class not working on JCRE 2.1.2 I have problem to read my free memories too .
    So I'll appreciate your help on this matter too.
    Best Regards,
    Vivian

    Hi Vivian,
    I don't seem to have any problem with the code you posted. What is the error you are getting? Is it with the compiler or with the CAP file converter? If it is a compiler error, you will need to ensure that the Java Card API jar is in your build path.
    Here is a simple class that works with JC 2.1.1 (which will work with JC 2.1.2 as well). I have confirmed that this applet compiles and will return encrypted data to the caller.
    package test;
    import javacard.framework.APDU;
    import javacard.framework.Applet;
    import javacard.framework.ISO7816;
    import javacard.framework.ISOException;
    import javacard.framework.JCSystem;
    import javacard.security.DESKey;
    import javacard.security.KeyBuilder;
    import javacard.security.RandomData;
    import javacardx.crypto.Cipher;
    * Test JC2.1.1 applet for random DES key.
    * @author safarmer - 1.0
    * @created 24/11/2009
    * @version 1.0 %PRT%
    public class TestApplet extends Applet {
        private DESKey key;
        private Cipher cipher;
         * Default constructor that sets up key and cipher.
        public TestApplet() {
            RandomData rand = RandomData.getInstance(RandomData.ALG_SECURE_RANDOM);
            short lenBytes = (short) (KeyBuilder.LENGTH_DES / 8);
            byte[] buffer = JCSystem.makeTransientByteArray(lenBytes, JCSystem.CLEAR_ON_DESELECT);
            key = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES, false);
            rand.generateData(buffer, (short) 0, lenBytes);
            key.setKey(buffer, (short) 0);
            cipher = Cipher.getInstance(Cipher.ALG_DES_CBC_ISO9797_M1, false);
        public static void install(byte[] bArray, short bOffset, byte bLength) {
            // GP-compliant JavaCard applet registration
            new TestApplet().register(bArray, (short) (bOffset + 1), bArray[bOffset]);
        public void process(APDU apdu) {
            // Good practice: Return 9000 on SELECT
            if (selectingApplet()) {
                return;
            byte[] buf = apdu.getBuffer();
            switch (buf[ISO7816.OFFSET_INS]) {
                case (byte) 0x00:
                    cipher.init(key, Cipher.MODE_ENCRYPT);
                    short len = cipher.doFinal(buf, ISO7816.OFFSET_CDATA, buf[ISO7816.OFFSET_LC], buf, (short) 0);
                    apdu.setOutgoingAndSend((short) 0, len);
                    break;
                default:
                    // good practice: If you don't know the INStruction, say so:
                    ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
    }Cheers,
    Shane

  • Message Digest with symmetric key

    Hi,
    I am new to Java Cryptography.
    My requirement is i want to digest a message using RSA generated 128 bit key and i am not able to find any functions to generate Symmetric key and also to digest a message with key. Can any one please tell me how to do. Any help would be appreciated. This is very urgent requirement.
    Thanks in advance.
    Cheers,
    Sreedhar Gupta

    RSA use a key pair :
    you can sign with the private key
    and you verify signature with public key.
    for this use class : java.security.Signature
    To have a "message digest" with a symmetric key
    use the class : javax.crypto.MAC

  • Web Services Security - Symmetric Keys

    I am writing my first web service and I have some questions regarding security.
    From what I understand I have two options. Communicate with my clients with us both having private/public key pairs (which I did manage to get working) or to use symmetric keys.
    Rather than have each of my clients create a key pair and send me their public key it would be beneficial I believe to use symmetric keys?
    Using the synchronous (symmetric key) method I would give my client my public key. Before my client connects to my web service they will generate a symmetric key and use that to encrypt their request and send the symmetric key with the request?
    My web service will then use my private key to decrypt the symmetric key they sent and I will use that key to decrypt their request as well as encrypt the response?
    The only way to use the symmetric key is to code that in on the client and server side using Java 2 Security?
    I am using WebSphere wizards for version 5.1 to create the service and the client. The tutorials I've seen are just for public/private key pairs it would seem because you create two keystores, export each certificate, then trust them with each other.

    Hi Soni,
    Yes, you could.
    Two options I can think of:
    - Program WS-Security for your specific web service
    - Use Oracle Web Services Manager
    With respect to the latter: I believe there is no OWSM policy step to handle your requirement out of the box. OWSM comes with policy steps for file-based authentication as well as for authenticating against Active Directory or a generic LDAP directory.
    In this case you could opt for the creation of a custom policy step.
    Hope this help.
    Sjoerd

  • HTTP Basic Auth and Username Authentication with Symmetric Key

    Hi,
    I have a webservice happily running on tomcat 5.5 using "Username Authentication with Symmetric Key" I have certificates setup and everything works fine. I can even connect a .net client and use the service.
    Now I have an additional requirement of authorization per operation basis so I'm planning on using the roles. My current setup uses tomcat-users.xml to configure users but I seem unable to identify the role of the user from within my code as wsContext.isUserInRole("briefing") always returns false even when it clearly isn't. Where wsContext = @Resource private WebServiceContext wsContext.
    So I figure perhaps I need to add HTTP Basic Auth to tomcat for it to gather this information so I added security-constraints to the web.xml and this seems to do the trick: at least it does for my .net client.
    If I do:
      Service service = new Service();
      Port client = service.getPort();
      BindingProvider bp = (BindingProvider)client;
      bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "myusername");
      bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "mypassword");Then it all works fine. However, I'd like a little less transparency: I don't want to have to do this every time I make a call.
    My question(s) is:
    1) Am I going about this the right way (perhaps I am somehow getting the incorrect reference to the WebServiceContext)
    2) If I am going about this the right way I imagine the whole BindingProvider code needs to be added to as a policy configuration but I'm really not sure where to start especially as I'm using wsimport to generate everything: I'm not even sure where to configure this so it will not get overwritter.
    Thanks for any help.

    Doh! Ok So I've added a SOAP Handler to automatically add the username and password for the HTTP Basic Auth.
    All in all does this setup sound right?

  • Failure to generate key with keytool

    I tried to use keytool to generate a key on Linux. It was successful on other Linux machines, but it is strange that it is failure on my production server.
    # /usr/java/jdk/bin/keytool -genkey -v -alias test2 -keyalg RSA
    Enter keystore password: changeit
    What is your first and last name?
    [Unknown]:
    What is the name of your organizational unit?
    [Unknown]:
    What is the name of your organization?
    [Unknown]:
    What is the name of your City or Locality?
    [Unknown]:
    What is the name of your State or Province?
    [Unknown]:
    What is the two-letter country code for this unit?
    [Unknown]:
    Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct?
    [no]: yes
    Generating 1,024 bit RSA key pair and self-signed certificate (MD5WithRSA)
    for: CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown
    And then the keytool keeps running but cannot generate a key.
    My production server is:
    - Intel Pentinum III 850 with 256MB RAM
    - RedHat Linux 7.2
    - Java 2 SDK build 1.4.0-beta3-b84
    Remark: I tried with same version of Linux distro and Java SDK on other machine, but it was successful.

    Chances are it is hung on the SecureRandom's use of the /dev/random
    device. If I recall right the proper /dev/random on linux is really
    /dev/urandom. So what you need to do is edit the
    <java_home>/jre/lib/security/java.security file a change the property
    to /dev/urandom instead of its default /dev/random value.....

  • Problem generating Key  with keytool command

    Hi Everyone;
    I'm having problems generating a key.
    Here's my output.
    C:\>keytool -genkey -alias learningIdeas -keysize 1024 -validity 365 -keyalg RSA
    Enter keystore password: changeit
    keytool error: java.io.IOException: Keystore was tampered with, or password was incorrect
    note i already did something with the keystore such that i have generated a key and placed this in server.xml
    <Connector className="org.apache.tomcat.service.PoolTcpConnector">
    <Parameter name="handler" value="org.apache.tomcat.service.http.HttpConnectionHandler"/>
    <Parameter name="port" value="8443"/>
    <Parameter name="socketFactory" value="org.apache.tomcat.net.SSLSocketFactory" />
         <Parameter name="keystore" value="C:/stephen" />
         <Parameter name="keypass" value="changeit"/>
         <Parameter name="clientAuth" value="false"/>
    </Connector>
    any ideas on what I can do to generate this key?
    stephen

    I have almost resolved this problem. I'm at the last step and getting an error message when trying to import the certificate that I received from verisign into my keystore.
    here's my error.
    C:\>keytool -import -alias mycompanyname123 -keystore STEPHEN4 -file mycompanyname.cer
    Enter keystore password: changeit
    keytool error: java.security.cert.CertificateException: Unsupported encoding
    but when I double click on this file mycompanyname.cer (which is exactly what I received from verisign, up comes the appropriate certificate
    i was able to succesfully able to install it into the microsoft browser and i see it correctly represented and displayed in the certificates section for OTHER PEOPLE.
    But I think i have to successfully import it into the keystore for it to work properly right when I start up the tomcaat app is that correct?
    any ideas?
    Stephen

  • Generate SSL cert with stronger signature algorithm such as RSA-SHA 1 or SHA 2 from Certificate Authority Version: 5.2.3790.3959

    We have a Certificate Authority (Version: 5.2.3790.3959) configured on  Windows 2003 R2 server in our environment. How do i generated SSL cert with stronger signature algorithm such as with SHA1 or SHA2
    Currently i am only able to generate SSL cert with md5RSA.

    Hi,
    Since you are using Windows Server 2003 R2 as CA, the hash algorithm cannot be changed, while in Windows 2008 and 2008 R2, changing the hash algorithm is possible.
    Therefore, you need to build a new CA to use a new algorithm.
    More information for you:
    Is it possible to change the hash algorithm when I renew the Root CA
    http://social.technet.microsoft.com/Forums/windowsserver/en-US/91572fee-b455-4495-a298-43f30792357e/is-it-possible-to-change-the-hash-algorithm-when-i-renew-the-root-ca?forum=winserversecurity
    Changing public key algorithm of a CA certificate
    http://social.technet.microsoft.com/Forums/windowsserver/en-US/0fd19577-4b21-4bda-8f56-935e4d360171/changing-public-key-algorithm-of-a-ca-certificate?forum=winserversecurity
    modify CA configuration after Migration
    http://social.technet.microsoft.com/Forums/windowsserver/en-US/0d5bcb76-3a04-4bcf-b317-cc65516e984c/modify-ca-configuration-after-migration?forum=winserversecurity
    Best Regards,
    Amy Wang

  • Can't read load RSA public key with JDK 1.4.2_08?

    We have been using Bouncy Castle's provider to provide RSA encryption and decryption of a login name and password for several years ... with JDKs in the 1.4.2 series up through 1.4.2_07.
    Recently, however, Sun released JDK 1.4.2_08, and suddenly any of our Java Web Start client applications are unable to successfully load the public key that we use to encrypt their login name and password before shipping it to the server for authentication with the 1.4.2_08 JRE. But, if we revert back to 1.4.2_07, everything works again.
    This public key itself has been in use for several years and the same code to read the public key has been in use for a long time ... including multiple versions of the BouncyCastle provider and all versions of the JDK up through 1.4.2_07. But suddenly things appear to break with JDK 1.4.2_08.
    This smells like a problem with JDK 1.4.2_08 so I thought that I'd check on this forum to see if any other Bouncy Castle users have experienced this problem. Is there anything further that I can do to check this out? Has any Bouncy Castle user successfully loaded a RSA public key from a byte stream with JDK 1.4.2_08? Or have people using other providers seen any problems reading similar public keys with JDK 1.4.2_08?
    The code that is failing on the client side is:
    try {
       encKey = new byte[this.publicKeyInputStream.available()];
       this.publicKeyInputStream.read(encKey);
       spec = new X509EncodedKeySpec(encKey);
       keyFactory = KeyFactory.getInstance("RSA",  "org.bouncycastle.jce.provide.BouncyCastleProvider");
       myPublicKey = keyFactory.generatePublic(spec);
       return myPublicKey;
    catch (Exception e) {
       e.printStackTrace();
    }The stack trace that I'm getting includes ...
    java.security.spec.InvalidKeySpecException: java.lang.IllegalArgumentException: invalid info structure in RSA public key
       at org.bouncycastle.jce.provider.JDKKeyFactory$RSA.engineGeneratePublic(JDKKeyFactory.java:330)
       at java.security.KeyFactory.generatePublic(Unknown Source)
       at org.opencoral.util.Encryption.loadPublicKey(SourceFile:450)
       at org.opencoral.util.Encryption.<init>(SourceFile:119)
       at org.opencoral.main.Coral.<init>(SourceFile:338)
       at org.opencoral.main.Coral.main(SourceFile:1919)
       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
       at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
       at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
       at java.lang.reflect.Method.invoke(Unknown Source)
       at com.sun.javaws.Launcher.executeApplication(Unknown Source)
       at com.sun.javaws.Launcher.executeMainClass(Unknown Source)
       at com.sun.javaws.Launcher.continueLaunch(Unknown Source)
       at com.sun.javaws.Launcher.handleApplicationDesc(Unknown Source)
       at com.sun.javaws.Launcher.handleLaunchFile(Unknown Source)
       at com.sun.javaws.Launcher.run(Unknown Source)
       at java.lang.Thread.run(Unknown Source)While it clearly indicates that it thinks that there is an "invalid info structure in RSA public key", I believe that nothing has changed in the structure of our key ... and this same key still works properly if I revert to JDK 1.4.2_07.
    Any thoughts or insights?
    Thanks,
    John Shott

    I'm facing the same Exception here,
    With JDK 1.5 (SUNJce) i'm getting --
    Exception in thread "main" java.security.spec.InvalidKeySpecException: java.secu
    rity.InvalidKeyException: Invalid RSA public key
    at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(Unknown Source)
    With BouncyCastle i'm getting --
    Exception in thread "main" java.security.spec.InvalidKeySpecException: java.lang
    .IllegalArgumentException: invalid info structure in RSA public key
    at org.bouncycastle.jce.provider.JDKKeyFactory$RSA.engineGeneratePublic(
    JDKKeyFactory.java:345)
    Any Solution?

  • Finding generated keys with batch updates

    Is it possible to combine reading generated keys with batch updates?
    In trying to improve performance of inserts into a database, I am using the addBatch functionality of the JDBC driver to insert several rows at once. Unfortunately some of my tables have auto numbered fields and I need to know what values they are taking so I can update my in-memory representation of the object in the database.
    The getGeneratedKeys functionality works fine when I insert one row at a time, but when I try to insert a batch of rows, the method returns null.
    I am using DB2 with the com.ibm.db2.jcc driver, though I have a hunch that this is a limitation of the JDBC spec. Can anyone confirm this? Does anyone have any ideas about a workaround?

    What is "several"?
    And have you actually measured the speed difference?
    Since returning generated keys is a rather recent addition to JDBC I doubt that it exists for batch updates.

  • How to encrypt more than 117 bytes with RSA?

    Hi there,
    I am struggling to encrypt more than 117 bytes of data with a 1024 bit RSA key.
    If I try to encrypt (write to my OutputStreamWriter) 118 Bytes ("A"s) or more, the file I am writing to is just empty and I get an exception whe trying to read it.
    I know the encryptable bytes (blocksize) are related to the key length: blocksize = keylength / 8 -11
    I also know RSA encryption of large files is discouraged, because it is like 100x slower than for instance AES and was originally only intended to exchange symmetric keys.
    Still I need to be able to asymmetrically encrypt at least 5kb of Data.
    I am out of ideas here and have no understanding of why the block size is limited (i know from hours of "googling" that it is limited as described above though).
    So, I would be very glad If somebody could point out a way how I could encrypt more than 117 bytes (without using a longer key of course).
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.FileOutputStream;
    import java.io.Reader;
    import java.io.Writer;
    import java.io.OutputStreamWriter;
    import java.security.PublicKey;
    import java.io.IOException;
    import java.security.InvalidKeyException;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.NoSuchAlgorithmException;
    import java.security.PrivateKey;
    import javax.crypto.*;
    public class strchrbty {
         public static void main(String[] args) {
              //generate Keys
              PublicKey publicKey = null;
              PrivateKey privateKey = null;
              try {
                   KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
                   kpg.initialize(1024);
                   KeyPair kp = kpg.generateKeyPair();
                   publicKey = kp.getPublic();
                   privateKey = kp.getPrivate();
              } catch (NoSuchAlgorithmException e) {
                   e.printStackTrace();
              //------ENCODE------
              try {
                  //initialize cipher
                  Cipher cipher = Cipher.getInstance("RSA");  
                   cipher.init(Cipher.ENCRYPT_MODE, publicKey);   
                   OutputStream cos = new CipherOutputStream(new FileOutputStream("c:\\test.txt"), cipher);
                  Writer out = new OutputStreamWriter(cos);
                  // 1024 bit (key length) / 8 bytes - 11 bytes padding = 117 Bytes Data.
                  //  for 118 Bytes (or more) Data: c:\\test.txt is empty annd no Data is read.
                  for(int i = 0; i<117; i++) {
                       out.write("A");
                  out.close();
                  cos.close();
             } catch (InvalidKeyException e) {
                  e.printStackTrace();      
             } catch (NoSuchPaddingException e) {
                  e.printStackTrace();           
             } catch (NoSuchAlgorithmException e) {
                  e.printStackTrace();      
             } catch (IOException e) {
                  e.printStackTrace();
             //------DECODE------
             try {
                  StringBuffer buf = new StringBuffer();
                  Cipher cipher2 = Cipher.getInstance("RSA"); 
                  cipher2.init(Cipher.DECRYPT_MODE, privateKey);
                  //read char-wise
                  InputStream cis = new CipherInputStream(new FileInputStream("c:\\test.txt"), cipher2);
                  Reader in = new InputStreamReader(cis);
                  for(int c = in.read(); c != -1; c = in.read()) {
                    buf.append((char)c);
                  //output
                  System.out.println(buf.toString());
                  in.close();
                  cis.close();
              } catch (InvalidKeyException e) {
                  e.printStackTrace();      
             } catch (NoSuchPaddingException e) {
                  e.printStackTrace();           
             } catch (NoSuchAlgorithmException e) {
                  e.printStackTrace();      
              } catch(IOException e) {
                 e.printStackTrace();
    }Regards.
    Edited by: junghansmega on Sep 10, 2008 3:41 PM
    Sorry about the bad autoformating.... It only occurrs in here, in my eclipse it looks fine =(

    junghansmega wrote:
    Hi there,
    I am struggling to encrypt more than 117 bytes of data with a 1024 bit RSA key.
    If I try to encrypt (write to my OutputStreamWriter) 118 Bytes ("A"s) or more, the file I am writing to is just empty and I get an exception whe trying to read it.
    Good, it should be painful.
    >
    Still I need to be able to asymmetrically encrypt at least 5kb of Data.
    In this forum, 99.999% of the time this kind of claim is due to a lack of understanding of the role of public key cryptography.
    I am out of ideas here and have no understanding of why the block size is limited (i know from hours of "googling" that it is limited as described above though).
    It should not be difficult to break up the input into 117 byte chunks and encrypt each chunk through a newly initted cipher object. Of course you will have to be very careful in properly encoding the output. You might naively think that the output is always 128 bytes, but is that true? Might it be 127 bytes sometimes? Maybe even 126 bytes?

  • SSL & generated private key

    I generated a CSR with the certificate servlet. I modified
    config.xml in order to set the right files :
    <SSL Enabled="true" ListenPort="7002" Name="test2" ServerCertificateChainFileName="config/mydomain/cacrt.pem"
    ServerCertificateFileName="config/mydomain/servercert.pem"
    ServerKeyFileName="config/mydomain/serverkey.der"/>
    The serverkey.der is a copy of the file generated by the
    certificate servlet.
    At startup the following error occurs :
    <30 juil. 01 20:23:26 CEST> <Alert> <WebLogicServer> <Security configuration problem
    with certificate file config/mydomain/serverkey.der, java.io.EOFException>
    java.io.EOFException
    at weblogic.security.Utils.inputByte(Utils.java:133)
    at weblogic.security.ASN1.ASN1Header.inputTag ASN1Header.java:125)
    at weblogic.security.ASN1.ASN1Header.input(ASN1Header.java:119)
    at weblogic.security.RSAPrivateKey.input(RSAPrivateKey.java:119)
    at weblogic.security.RSAPrivateKey.<init>(RSAPrivateKey.java:91)
    at weblogic.t3.srvr.SSLListenThread.<init>(SSLListenThread.java:397)
    at weblogic.t3.srvr.SSLListenThread.<init>(SSLListenThread.java:300)
    at weblogic.t3.srvr.T3Srvr.initializeListenThreads(T3Srvr.java:1028)
    at weblogic.t3.srvr.T3Srvr.initialize(T3Srvr.java:475)
    at weblogic.t3.srvr.T3Srvr.run(T3Srvr.java:197)
    at weblogic.Server.main(Server.java:35)
    More over the conversion of the serverkey.der in serverkey.pem
    with openssl gives the following error :
    openssl rsa -in serverkey.der -outform PEM -out serverkey.pem
    read RSA key
    unable to load key
    1276:error:0906D06C:PEM routines:PEM_read_bio:no start line:./crypto/pem/pem_lib
    .c:662:Expecting: ANY PRIVATE KEY
    and reading the file by the default W2K reader gives an error too.
    Need help !

    Agree with S Guna, the ISP/Certificate Authority won't generate the private key, the request from your Lync server does.  So the private key is already sitting on your Lync 2010 Server.  Once you import the certificate generated by the certificate
    authority, the private key and certificate should be paired and can be assigned to Lync.
    Please remember, if you see a post that helped you please click "Vote As Helpful" and if it answered your question please click "Mark As Answer".
    SWC Unified Communications

  • Keytool seems to generate private key outside of HSM

    I am investigating integration with LunaSA (Safenet HSM) and JDK.
    LunaSA rejects key generation through JDK PKCS#11 wrapper.
    When I execute "keytool" command, then, PKCS#11 wrapper seems to generate
    private key outside of the HSM.
    Actually, the PKCS#11 log show the private key objects like this:
    14:10:12 01868-3212:STRTCreateObject {Sesn=1 AttrList={CKA_SENSITIVE="01"
    CKA_EXTRACTABLE="00" CKA_DECRYPT="01" CKA_SIGN="01" CKA_UNWRAP="01"
    CKA_TOKEN="01" CKA_CLASS="03000000" CKA_PRIVATE="01" CKA_KEY_TYPE="00000000"
    CKA_ID="iText"
    CKA_MODULUS="866b89f28013b0dd1217189a1f1adea2c23d3d20c0ee11b3360b2988869a8d1
    ccbead99f7d8111eea74ff7791196c1173ed732cadce517381163c5320af4486a3bd174cd581
    645eb2b39e4fe2d9aa92c7723303271e9e27ef2f994e668be0bd1d8fd3fda7cbe654e7934553
    4493c58a032c558a3a49e771b1c72c8d01e4adb6e09c17d2816a1f2ea054f074d63e6961b477
    4d60ed23995a596d102e24f65c7c29593b3c1e5536083b6023e97a1181d8466796e72debea5f
    19150d3b933629579fc3f3588843455d6b16db17f6e40dc7e69f0fdd3bee9d3acace845d075f
    1df72704c4a8169d6802e289ed5b15597b0bccd63e83f725a2d3d4c0319880de7b319"
    CKA_PRIVATE_EXPONENT="6a82617ee61f3420278a67730fbc81b6a38454a0545f0f655a2844
    13aadc617df4d234f81c411e4d6503870ac67616afed9a24e3fb5e0724e51a921111fef8363d
    09bdac4be4f227e24b70783af8769e0614bac6edde2e1afb39e9d31c21a249f7cecb3ebb633d
    f08d377b5fffbbb259d580ebb856e33d6b1d0292bddd92e104cc5465def444f28ff1e28512ba
    2429ebc7a350b78f54cafad66cb60a608c752fd566454a5a1b7eb4d530d80587220fe7cc8915
    66bd7d2bbf74ab93d4e4a42468513426c59e65963a001bfa85ff533c266f625203550f8e4b0b
    1030f3503b46b1412910464aa5fbccf256f320801d31528275d2e4f43dc43207d759f32a0070
    51" CKA_PUBLIC_EXPONENT="010001"
    CKA_PRIME_1="c63c1c1fb8e34cf9139887e237282c3c6aa506b91ea977526b6a86836653334
    26529637223b3f73376c6fed5d19b58596e035bc8207c1b4b0fc63f9bc5dc8ace695322022d8
    dd471b9650a2f4115bf3e1bda5d8ed41bf8417008d0d6093eee6917d94b69cc3eeb82549a448
    80dc6ce5fc24c007aaebb5866de0105bb3d57fb5d"
    CKA_PRIME_2="ad96fcc0f3c9f177648415f1b68e9faa36e0fe538978742f2a474ff66cd8df8
    05bd8ac86850575964a4ba787173e258a96414df7ef4706ccb33a8bac3cb2d7f1f56d629fe9d
    a7cb915a46ff399aea4e58011674704560e5c4efe62f14766ef240e516fe63823e68cfc936cf
    6e1c53ba2461128dce65a3107ecc0688cffa216ed"
    CKA_EXPONENT_1="02fe99762936d5ccd56cf2708a60c2fa4eaa1b85e45eaefcc1bea4358bf0
    29d010f3251b6e4aa3ab555a00337ead181291c4df3810b58f3bfd0b039ef8c832189822b75a
    cd115d6a3260c25ca06111b8807735fe9859abd0613ee0d8badf067ef3eb46665cbd7e95436d
    e9271cfe29d3ec7d756c6503537c8a51fda22c750dc9"
    CKA_EXPONENT_2="a4285cedbb9e05937aa2ce7dbebe318fae46273ca88c189361cffe767388
    c41386c7e89f6dbc33eee4639711d1911bbf6b48668b48e44a31da6c4b199e6d2279d6369345
    d6c89f9a0835710955142b2c3d6837da98e728bd72966ecaed5312636e86e4e339c3f98aea70
    2063782e24aed8c3f178b4fe25cff0bc2422f2bc3e21"
    CKA_COEFFICIENT="6b26b189f84fe75ce38220fa49c5e76ffd9ffabfdc311606dedce7b16e1
    0c10f201fb4332f6497a7d26052e9f17b930fd574ae152047fce783516cd5b75b8d8927875b2
    2c12393795d4f397d736f1cf6eb81d4e2252a227455f93c1587c6b881837fe9e0cf9dd01a972
    6a15830e5bc83e4e0047f3d1d8c3858bfe5adf12834a2" } }
    14:10:12 01868-3212:FINICreateObject
    ***CKR_TEMPLATE_INCONSISTENT***(26328ms) {Obj=0 }
    The command I tried is:
    C:\Program Files\Java\jdk1.6.0_21\jre\bin>keytool -v -genkey -alias iText -keystore NONE -keyalg RSA -keysize 2048 -dname "CN=test,O=GlobalSign,C=JP" -storetype pkcs11
    Is it specification of keytool?

    Well, yes, exporting a PrivateKeyEntry to a PKCS12 keystore does save (or, backup) your keypair as a copy on your disk, and it's quite a standard format. In fact, quite a lot of people get their keypair this way, and they can run -importkeystore to import (for you, restore) it into their JKS keystore.

  • Why are Symmetric keys shorter than ASyemmetric keys and provide the same level of security.

    Hello
    Can someone please help me with the following question.
    Can someone please give me a brief (if possible) why Symmetric Keys which are much shorter than Asymmetric keys provide a similar level of security (e.g. take as long to crack).
    I understand RSA and can to the math with a piece of paper and the Windows advanced calculator (e.g. encrypt and decrypt a sort message using a couple of small prims likes 53 and 59).
    I also understand ( to a very basic level) AES e.g. 128bit block cypher (I believe a CBC cypher using an unpredictable IV)
    Is there a simple answer if someone says why are Symmetric keys shorted and just as secure or it is just how it is? due to the different math?
    Thank you
    AAnoterUser__
    AAnotherUser__

    Symmetric Key is used for same key for encrypsion & decryption but ASyemmetric key is used two keys (Public & private key) for
    encrysion & decryption.
    ASyemmetric
    1. If Public key is used for  encrypsion then private key is used for decryption
    2. If private key is is used for  encrypsion then public key is used for decryption.
    3. It is more secure than Syemmetric
    Regards,
    Biswajit
    MCTS, MCP 2003,MCSA 2003, MCSA:M 2003, CCNA, Enterprise Admin, ITIL F 2011
    Blog:
      Script Gallary:
      LinkedIn:
    Note: Disclaimer: This posting is provided & with no warranties or guarantees and confers no rights..

  • Generating crypto keys for SSH support

    Hi,
    I'm having no problems getting SSH to work using the CLI crypto key command but I've noticed one thing. The crypto key command does not show up in the config...is it hidden somehow? The reason I ask is when I take an AP(1121 in this case) right out of the box and copy an existing config into it (where this config had the RSA keys already config'd)....it works with SSH? How do the keys get generated on this new AP when there is no crypto key command in the config I just loaded into it?
    .....thanks.........J

    you need to use a K9 image that supports crypto features
    For ssh dont copy and paste the config.
    Create a domain name and generate a key.

Maybe you are looking for