My RSA Algorithm

Hi there, hope someone can help me out alittle here.
I pretty new to encryption, but I'm trying to code my own RSA algorithm in java, and have a few questions about it.
*I want the encryption level to be 1024bit, so I should aim to get 2 primes at 512bit ?
*What bit-level of 'e' (relative prime to phi_n) should I aim for? If I aim for a 1024bit 'e', will this increase security ?
*I have got a java version of the MersenneTwister psuedorandom number generator, as I thought it would be better than the standard java version (new Random()), is it 'safe' to even use this to calculate the 2 random primes and 1 random 'e' using the BigInteger constructor as so :
new BigInteger(bit-size, primecertainty, new MersenneTwister())
or do I need to come up with another way of randomly generating these 3 values ? ie:is any random number generator not suitable for secure encryption?
I was thinking about having a JFrame, and telling the user to move the mouse around while grabbing the mouse coordinates at certain intervals, and using these values in some way to generate the values.
Thanks for any help you can give me

I'm a bit of a noob when it comes to this so please correct anything I'm saying wrong.
To my limited understanding, RSA is a way of cryptography using the public/private (assymetric) key system. I'm just trying to implement it myself. The reason I'm doing this is two-fold.
Firstly, to my understanding java implementations of encryption are limited to 256bit (is this correct?), I don't want to be restricted to this limit.
Secondly, this is mainly for self education purposes as I did a short short course of cryptography in general and they teach you the basics of loads of things, and so gain a decent understanding of none.
Is there a algorithm written in java already out there, that is proven to be "air-tight"?, as you are correct designing my own probably would have weaknesses and as I'm not a mathematician checking it for vulnerabilities wouldn't be ideal for me.
I basically am looking for a good way to generate 2 large primes, and then randomly generate 'e'.
At first, my 'e' was the first value it found, incrementing up from 2 until it found one. I'm currently trying to get a reliable method of a randomly generated 'e'.
Any help in these areas would be appreciated.

Similar Messages

  • Compability problem with Java and Python  RSA algorithm implementation

    I have client server application. Server is writtein in python, client in java. Client receives messages from server encrypted with RSA (http://stuvel.eu/rsa), and I'm unable to decrypt it. It seems that this is RSA algorithm compatibility problem. I'm using algorithm from java.security package, instatinating Cipher object like this: c = Cipher.getInstance("RSA"); . I noticed that this algorithm produces for input blocks of lengtrh <=117 ouput block of length 128. Server I guess uses the most triviall impelentation of RSA ( (1 byte is encrypted to 1 byte) So i want to make my java algorithm compatibile with this one which server uses. How to do that ? Do i have to instatinate Cipher object in different way ? Or use another library ?

    azedor wrote:
    First you said it was no good because it could only handle <= 117 byte inputs, now you say it is no good because it produces a 128-byte output. You're not making sense.First i said that this two RSA implementations are not compatibile, and first reason i noticed firstly is that Python imlementation for input of length N produces cryptogram of the same length. Not true. In general, the RSA encryption of any number of bytes less than the length of the modulus will produce a result of length near that of the modulus. When N is less than the length of the modulus, it is rare that N bytes of cleartext produces N bytes of ciphertext.
    Java implementation for data block of length <=117 produces alwasy 128 bytes of output.Pretty much correct and very much desirable. This is primarily a function of the PKCS1 padding which is used to solve two basic problems. First, as I alluded to in my first response, it is the nature of the algorithm that leading zeros are not preserved and second when the cleartext is very small (a few bytes) the exponentiation does not roll over and it is easy to decrypt the result. Both these problems are addressed by PKCS1 padding.
    >
    >
    After what sabre150 said i think of giving up idea of translating Python code to Java and considering to use another assymetric cryptography algorithms on both sides. Can you recommend me sth what should be compatibile with Python ?This seems to be at odds with your statement in reply #3 "Also have acces only to client code so i have to change sth in java." ! This statement is why I said "I suspect ... you have dug a deep hole".
    In your position I would use the Python bindings for openssl. Once more, Google is your friend.

  • RSA Algorithm

    Whether it is possible to encrypt a String Message using RSA Algorithm??

    It wouldn't be much use if it wasn't possible, would it?

  • Implement RSA algorithm

    Hello, everyone,
    For some reason, I have to write a program to implement RSA algorithm by myself, instead of get RSA from some provider. In RFC3447(PKCS#1), there is a step during the RSA encryption, which is called 'EME-OAEP encoding'. Actually, the main purpose of this 'EME-OAEP encoding' is to do the 'padding' thing for plaintext.
    I am just wondering, is there any class or method in java which can do the 'EME-OAEP encoding'? (I just don't want to implement the whole 'EME-OAEP encoding' process by myself)
    Thank you for any help
    Regards

    I don't think any of the crypto pieces are available
    "standalone" - they're all internal to the Cipher
    impls.
    GrantHi, I found this link:
    http://www.informatik.tu-darmstadt.de/TI/Forschung/FlexiProvider/docs/flexiprovider/docs/de/flexiprovider/core/rsa/PKCS1Operations.html
    I will take a look at this link later, don't know if it works or not.

  • Implementing RSA algorithm

    Dear All,
    I want to implement RSA algorithm by using java.tell me whether we can implement RSA by using JCE or any different functionalities is there. i want some soft copy related to RSA pls help me out.

    Hello,
    I do not know how much do you know about implementing algorithms and what are you exactly watching for.
    Some days ago I find this information about (I can not remind where did I take it, maybe was from this forum) for install JCE and BouncyCastle software for encryption.
    You should first download change the policy of the JCE By downloading this
    http://java.sun.com/j2se/1.4.2/download.html just JCE a and unzip in a folder read the read me doc so you should cut that 2 file and put here C:\j2sdk1.4.2_02\jre\lib\security
    and here C:\Program Files\Java\j2re1.4.2_02\lib\security
    done this then download the bouncy jar file from http://www.bouncycastle.org/latest_releases.html take the bcprov-jdk14-120.jar and put in following directories
    C:\j2sdk1.4.2_02\jre\lib\ext
    C:\Program Files\Java\j2re1.4.2_02\lib\ext
    then you need to change the environment variable so in the following directories open "java.security" in both
    C:\j2sdk1.4.2_02\jre\lib\security
    C:\Program Files\Java\j2re1.4.2_02\lib\security
    and edit it and add the extra line
    security.provider.numberProvider=org.bouncycastle.jce.provider.BouncyCastleProvider
    Then you should test if everything is good installed:
    import java.security.Provider;
    import java.security.Security;
    import java.util.Set;
    import java.util.Iterator;
    public class Verifica {
         public static void main(String[] args) {
              Provider[] providers = Security.getProviders();
              for (int i = 0; i < providers.length; i++) {
                   Provider provider = providers;
                   System.out.println("Provider name: " + provider.getName());
                   System.out.println("Provider information: " + provider.getInfo());
                   System.out.println("Provider version: " + provider.getVersion());
                   Set entries = provider.entrySet();
                   Iterator iterator = entries.iterator();
                   /*while (iterator.hasNext()) {
                        System.out.println("Property entry: " + iterator.next());
    And you will see if there is RSA. (It should)
    An example:
    Encription:
    //Object Cipher to encript data.
    Cipher encriptDatos = Cipher.getInstance("RSA", "BC");
    encriptDatos.init(Cipher.ENCRYPT_MODE, servidorPub); //servidorPub is the server public key you should have or generate
    //data encryption
    byte[] datosEncriptados = encriptDatos.doFinal(b);
    Desencryption:
    Cipher Cipherdesencriptacion = Cipher.getInstance("RSA", "BC");
    Cipherdesencriptacion.init(Cipher.DECRYPT_MODE, servidorPriv); //ServidorPriv is the server public key
    //data desencryption
    byte[] datosClaros = Cipherdesencriptacion.doFinal(datos); //datos = encripted data.I am sure you can find many examples of encrypt and decrypt. But hope this help as introduction.
    - Susana

  • Algorithm RSA

    Hi,
    Since the 1 of January, 2011 all portuguese invoices must be signed up digitally and registered.
    We have come up to the following solution:
    With the help of OPENSSL generate a private key:
      OPENSSL GENRSA -OUT privatekey.PEM 1024
    It must fulfill the following requisites of RSA algorithm:
    -> Format = x.509
    -> Charset = UTF-8
    -> Encoding = Base-64
    -> Endianess = Little Endian
    -> OAEP Padding = PKCS1 v1.5 padding
    -> Length private key = 1024 bytes
    -> Mensage Format Hash  = SHA-1
    Then on the basis of the private key a public key should be generated:
        OPENSSL RSA -IN privatekey.PEM - OUT publickey.PEM -OUTFORM PEM -PUBOUT
    With the help pf the HOST command I create the signatures for the invoice registry:
    cmd> echo TEXT.TXT | openssl dgst -sha1 -sign privatekey.pem | openssl enc -base64
    where the file TEXT.TXT is: "2010-05-18;2010-05-18T11:22:19;FAC 001/14;3.12;"
    It has been an horrible, but efficient solution.
    It functions well when you register an invoice, but it gets complicated when you want to verify if the signatures are correct.
    Reasons:
    - You have to filter all the documents and all the registries must execute the Host command in the background.
      The command will open and create files for each verification.
      When you delete these files it continues in the registry...
    What I´m asking is whether there is a better, more efficient way to generate signatures in pl/sql as well as their verification?
    Regards
    Jomar

    Hi Jomar,
    correct me if I'm wrong, but from your post it looks like what you are doing is capturing the ouput from an OS command to manipulate within the database. If you search this forum or google for something like "execute OS command from PL/SQL" you will get lots of hits. Also, have you searched to see if there is a java based equivalent to openssl which could be compiled in and called from the Oracle database.
    Andre

  • Algorithms such as ALG_RSA_ISO9796

    How can I know what EXACTLY this algorithm does ?
    The documentation says "Cipher algorithm ALG_RSA_ISO9796 provides a cipher using RSA. Input data is padded according to the ISO 9796 (EMV'96) scheme.".
    I know EMV and RSA pretty well, what I want to know is what EXACTLY is done. In that case, I would guees that it computes a SHA hash on the message, splits i, add a header and a trailer and then sign (like in EMV).
    Where can I find :
    1) the exact definition of the ciphers (this one and others)
    2) test vectors
    Thanks in advance.

    EMV'96 not only defines the use of the RSA algorithm for digital signature. It also can be used to cipher general data.
    See annex E (for digital signature) and F (for ciphering).
    From my point of view, ALG_RSA_ISO9796 doesn't pad the data (excepts for the 0's adding) for odd exponents, but it have a different ciphering behaviour for even exponents.
    That is what this contant define.

  • Simple RSA decryption error

    Hi All
    I am trying a very simple RSA implementations. I am not able to decrypt the data correctly. Please find my code below,
    import java.math.BigInteger;
    import java.util.Random;
    public class SimpleRSA {
         public static BigInteger p, q, N, v, k, d;
         public static void main(String[] args) {
              // p & q are prime numbers
              Random myRandom = new Random(0);
              p = BigInteger.probablePrime(32, myRandom);
              q = BigInteger.probablePrime(32, myRandom);
              System.out.println("Value of p:" + p);
              System.out.println("Value of q:" + q);
              // N = pq
              N = p.multiply(q);
              System.out.println("Value of N:" + N);
              // v = (p-1)*(q-1)
              v =
                   (p.subtract(BigInteger.valueOf(1))).multiply(
                        q.subtract(BigInteger.valueOf(1)));
              System.out.println("Value of v:" + v);
              // Compute k such that gcd(k, v) = 1
              k = new BigInteger("3");
              while(v.gcd(k).intValue() > 1) k = k.add(new BigInteger("2"));
              System.out.println("Value of k:" + k);
              // Compute d such that (d * k)%v = 1
              d = k.modInverse(v);
              System.out.println("Value of d:" + d);
              System.out.println("Public Key (k,N): (" + k + "," + N + ")");
              System.out.println("Private Key (d,N): (" + d + "," + N + ")");
              // Encryption
              String text = "Welcome to Java";
              System.out.println("Sample text:" + text);
              byte[] cipherData = text.getBytes();
              BigInteger a = new BigInteger(cipherData);
              System.out.println("BigInteger a:" + a);          
              BigInteger b = a.modPow(k, N);
              System.out.println("Encrypted data:" + b);
              // Decryption
              BigInteger c = b.modPow(d, N);
              byte[] decryptedData = c.toByteArray();          
              String plainText = new String(decryptedData);
              System.out.println("Decrypted data:" + plainText);     
    The answer I am getting is like this
    Value of p:3139482721
    Value of q:3180579707
    Value of N:9985375032889742747
    Value of v:9985375026569680320
    Value of k:7
    Value of d:4279446439958434423
    Public Key (k,N): (7,9985375032889742747)
    Private Key (d,N): (4279446439958434423,9985375032889742747)
    Sample text:Welcome to Java
    BigInteger a:1446156601937412646258
    Encrypted data:9678387382297663676
    Decrypted data:r��`�>B[/i]
    Please help me in this regard.
    Regards
    Kathirvel

    "m" (the integer rep of the message) must be strictly less than "N" (p*q). Look at the output - your p and q are too small for your data. Tryp = BigInteger.probablePrime(512, myRandom);
    q = BigInteger.probablePrime(512, myRandom);and try again.
    Then, go back and re-read the description of the RSA algorithm:
    http://en.wikipedia.org/wiki/RSA
    ("Applied Cryptography" would be bettr - but Wikipedia is at least a good start...)
    Grant

  • How to remove padding after RSA decryption??

    Hello,
    I am testing my host apps ability to read public key that was saved in file after being exported from smart card where it was generated.
    I have successfully used the private key on card to encrypt a small piece of data and the cryptogram is returned to the host.
    On host side I retrieve public key from file and decrypt ciphertext
    The on-card alg for Cipher is declared as follows-
    RSAcipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, true);and in the host app
    Cipher rsaCipher = Cipher.getInstance("RSA","BC");I can see from what is returned from
    byte[] decrypted = rsaCipher.doFinal(this.encryptedData);that the correct data is being returned, but is is padded by
    01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFFFFFFFFFFFFFF00How do I know where the padding ends and the plaintext begins?
    Can anyone help me with this?
    Thanks in advance,
    Ann

    Hi!
    I have the same problem like you.
    But my problem is that i don,t know how to move the key across. I manege to create a pair of keys public and private using RSA Algorithm.
    privateKey = KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PRIVATE,KeyBuilder.LENGTH_RSA_512,false);
            publicKey = KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PUBLIC,KeyBuilder.LENGTH_RSA_512,true);
                        // KeyPair creation
                        if(keyPair == null){
                            keyPair = new KeyPair(KeyPair.ALG_RSA, (short)publicKey.getSize());
                        // starts key generation process
                        keyPair.genKeyPair();
                      publicKey = keyPair.getPublic();
                        privateKey = keyPair.getPrivate();
                         cipher = Cipher.getInstance(ALG_RSA_NO_PAD, false );then i send the modulus and exponent part of the public key to host
                 byte    keyElement = (byte)(apduBuffer[ISO7816.OFFSET_P2] & 0xFF);
                     // check correct type (modulus or exponent)
                     if((keyElement != 0x00) && (keyElement != 0x01))
                         ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
                     // check elements request
                     if(keyElement == 0) {
                         // retrieve modulus
                         apduBuffer[0] = (byte)((RSAPublicKey)publicKey).getModulus(apduBuffer, (short)1);
                     } else
                         // retrieve exponent
                        apduBuffer[0] = (byte)((RSAPublicKey)publicKey).getExponent(apduBuffer, (short)1);
                     // send the key element
                     apdu.setOutgoingAndSend((short)0, (short)((apduBuffer[0] & 0xFF) + 1));I decrypt the data as follow in the card
          byte[] apduBuffer = apdu.getBuffer();
          if(!privateKey.isInitialized())
                            ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
          cipher.init(privateKey,Cipher.MODE_DECRYPT);
          apdu.setIncomingAndReceive();
         cipher.doFinal(apduBuffer, (short)ISO7816.OFFSET_CDATA, (short)(apduBuffer[ISO7816.OFFSET_LC] & 0xFF), apduBuffer, (short)0);
        apdu.setOutgoingAndSend((short)0, (short)(KeyBuilder.LENGTH_RSA_512/8));
       in host i encrypt data as follow
    // Note modulus and exponent are arrays of bytes from the card
        BigInteger modulus = new BigInteger(1,modulus);
        BigInteger exponent =new BigInteger(1,exponent);
        cipher = Cipher.getInstance("RSA");
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus,exponent);
    keyFactory = KeyFactory.getInstance("RSA");
    pubKey = keyFactory.generatePublic(pubKeySpec);
    cipher.init(Cipher.ENCRYPT_MODE,pubKey);
    byte[] p = cipher.doFinal(data);

  • How to use RSA keygenerator API

    I've little experience about Java programming. And I can't find the implementaiton APIs for RSA algorithms such as key pair generation. Does sun provider have no implementation about this? If so, how can I use other provider's product?
    Thanks a lot!

    Hi,
    here is the way to generate key pairs. and sign the applet/jar file with RSA algorightm, dont forget about duke dollers.
    http://java.sun.com/products/plugin/1.3/docs/rsa_signing.html
    have fun
    -riyaz

  • RSA Implementation for SunJCE Provider

    Hello there!
    I just would like to inquire if there are plans/news for the sun developers to include the RSA Algorithm as part of the cryptographic services available in the pre-installed SunJCE Provider? If so, when?
    Thanks.
    Regards,
    Ronron

    Which RSA algorithm are you looking for? BTW Sun has 4
    JCE providers: SUN, SunJCE, SunRsaSign, SunJSSE.I am referring to the SunJCE Provider, which is
    already included in the latest Java 2 SDK, v 1.4
    release. Those 4 providers are from JDK 1.4
    I am looking for the RSA Algorithm for
    encryption/decryption of data. Because I believe that
    it would be very helpful when the SunJCE would include
    the implementation of that algorithm since the
    provider had been pre-installed in the latest Java 2
    SDK.
    Do you have any idea?I believe they still don't want to have any issues with US export restrictions, especially with that little case when someone need to use RSA encryption. So, they let you to use any 3rd part JCE provider. And there is such a good one for free. Look at the BouncyCastle.

  • Invalid Key Exception: Unsupported key type: Sun RSA public key, 1024 bits

    I am trying to retrieve certificates from Microsoft Keystore and extract its keys using SunMSCAPI in jdk 1.6. It gives me an invalid key exception, when I am trying to wrap the Symmetric key (which was previously used to perform AES encryption on data), using RSA algorithm.
    Code snippet:
               // RSA 1024 bits Asymmetric encryption of Symmetric AES key             
                // List the certificates from Microsoft KeyStore using SunMSCAPI.
                      System.out.println("List of certificates found in Microsoft Personal Keystore:");
                       KeyStore ks = KeyStore.getInstance("Windows-MY", "SunMSCAPI");
                       ks.load(null, null) ;
                       Enumeration en = ks.aliases() ;
                       PublicKey RSAPubKey = null;
                       Key RSAPrivKey = null;
                       int i = 0;
                       while (en.hasMoreElements()) {
                            String aliasKey = (String)en.nextElement() ;              
                            X509Certificate c = (X509Certificate) ks.getCertificate(aliasKey) ;     
                            String sss = ks.getCertificateAlias(c);
                            if(sss.equals("C5151997"))
                            System.out.println("---> alias : " + sss) ;
                            i= i + 1;
                            String str = c.toString();
                            System.out.println(" Certificate details : " + str ) ;
                          RSAPubKey = c.getPublicKey();
                            RSAPrivKey = ks.getKey(aliasKey, null);  //"mypassword".toCharArray()
                            Certificate[] chain = ks.getCertificateChain(aliasKey);     
                       System.out.println("No of certificates found from Personal MS Keystore: " + i);
                // Encrypt the generated Symmetric AES Key using RSA cipher      
                        Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", ks.getProvider().getName());            
                       rsaCipher.init(Cipher.WRAP_MODE, RSAPubKey);
                       byte[] encryptedSymmKey = rsaCipher.wrap(aeskey);   
                       System.out.println("Encrypted Symmetric Key :" + new String(encryptedSymmKey));
                       System.out.println("Encrypted Symmetric Key Length in Bytes: " + encryptedSymmKey.length);
                       // RSA Decryption of Encrypted Symmetric AES key
                       rsaCipher.init(Cipher.UNWRAP_MODE, RSAPrivKey);
                       Key decryptedKey = rsaCipher.unwrap(encryptedSymmKey, "AES", Cipher.SECRET_KEY);Output:
    List of certificates found in Microsoft Personal Keystore:
    ---> alias : C5151997
    Certificate details : [
    Version: V3
    Subject: CN=C5151997, O=SAP-AG, C=DE
    Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5
    Key: Sun RSA public key, 1024 bits
    modulus: 171871587533146191561538456391418351861663300588728159334223437391061141885590024223283480319626015611710315581642512941578588886825766256507714725820048129123720143461110410353346492039350478625370269565346566901446816729164309038944197418238814947654954590754593726047828813400082450341775203029183105860831
    public exponent: 65537
    Validity: [From: Mon Jan 24 18:17:49 IST 2011,
                   To: Wed Jan 23 18:17:49 IST 2013]
    Issuer: CN=SSO_CA, O=SAP-AG, C=DE
    SerialNumber: [    4d12c509 00000005 eb85]
    Certificate Extensions: 6
    [1]: ObjectId: 2.5.29.14 Criticality=false
    SubjectKeyIdentifier [
    KeyIdentifier [
    0000: 07 E5 83 A1 B2 B7 DF 6B 4B 67 9C 1D 42 C9 0D F4 .......kKg..B...
    0010: 35 76 D3 F7 5v..
    [2]: ObjectId: 2.5.29.35 Criticality=false
    AuthorityKeyIdentifier [
    KeyIdentifier [
    0000: E4 C4 2C 93 20 AF DA 4C F2 53 68 4A C0 E7 EC 30 ..,. ..L.ShJ...0
    0010: 8C 0C 3B 9A ..;.
    [3]: ObjectId: 1.3.6.1.4.1.311.21.7 Criticality=false
    Extension unknown: DER encoded OCTET string =
    0000: 04 30 30 2E 06 26 2B 06 01 04 01 82 37 15 08 82 .00..&+.....7...
    0010: D1 E1 73 84 E4 FE 0B 84 FD 8B 15 83 E5 90 1B 83 ..s.............
    0020: E6 A1 43 81 62 84 B1 DA 50 9E D3 14 02 01 64 02 ..C.b...P.....d.
    0030: 01 1B ..
    [4]: ObjectId: 2.5.29.17 Criticality=false
    SubjectAlternativeName [
    RFC822Name: [email protected]
    [5]: ObjectId: 2.5.29.15 Criticality=true
    KeyUsage [
    DigitalSignature
    Non_repudiation
    Key_Encipherment
    Data_Encipherment
    [6]: ObjectId: 2.5.29.19 Criticality=true
    BasicConstraints:[
    CA:false
    PathLen: undefined
    Algorithm: [SHA1withRSA]
    Signature:
    0000: B3 C5 92 66 8D D7 ED 6D 51 12 63 CC F4 52 18 B9 ...f...mQ.c..R..
    0010: B8 A6 78 F7 ED 7D 78 18 DA 71 09 C9 AE C8 49 23 ..x...x..q....I#
    0020: F5 32 2F 0F D1 C0 4C 08 2B 6D 3C 11 B9 5F 5B B5 .2/...L.+m<.._[.
    0030: 05 D9 CA E6 F9 0A 94 14 E7 C6 7A DB 63 FE E5 EC ..........z.c...
    0040: 48 94 8C 0D 77 92 59 DE 34 6E 77 1A 24 FE E3 C1 H...w.Y.4nw.$...
    0050: D8 0B 52 6A 7E 22 13 71 D7 F8 AF D1 17 C8 64 4F ..Rj.".q......dO
    0060: 83 EA 2D 6A CA 7F C3 84 37 15 FE 99 73 1D 7C D1 ..-j....7...s...
    0070: 6D B4 99 09 62 B9 0F 18 33 4C C6 66 7A 9F C0 DB m...b...3L.fz...
    No of certificates found from Personal MS Keystore: 1
    Exception in thread "main" java.security.InvalidKeyException: Unsupported key type: Sun RSA public key, 1024 bits
    modulus: 171871587533146191561538456391418351861663300588728159334223437391061141885590024223283480319626015611710315581642512941578588886825766256507714725820048129123720143461110410353346492039350478625370269565346566901446816729164309038944197418238814947654954590754593726047828813400082450341775203029183105860831
    public exponent: 65537
         at sun.security.mscapi.RSACipher.init(RSACipher.java:176)
         at sun.security.mscapi.RSACipher.engineInit(RSACipher.java:129)
         at javax.crypto.Cipher.init(DashoA13*..)
         at javax.crypto.Cipher.init(DashoA13*..)
         at com.sap.srm.crpto.client.applet.CryptoClass.main(CryptoClass.java:102)
    Edited by: sabre150 on 18-Jul-2011 03:47
    Added [ code] tags to make code readable.

    A bit of research indicates that the classes of the keys obtained by
                          RSAPubKey = c.getPublicKey();
                               RSAPrivKey = ks.getKey(aliasKey, null);  //"mypassword".toCharArray()are sun.security.rsa.RSAPublicKeyImpl and sun.security.*mscapi*.RSAPrivateKey . It seems that for Cipher objects from the SunMSCAPI provider cannot accept RSA public keys of class sun.security.rsa.RSAPublicKeyImpl and that the SunMSCAPI will only accept RSA private keys of class sun.security.mscapi.RSAPrivateKey.
    This came up under different guise a couple of years ago. It makes sense since encrypting/wrapping with a public key does not represent a security problem (there is nothing secret in any of the encryption operations) when done outside of MSCAPI so one can use any provider that has the capability BUT the decryption/unwrapping must be done with the SunMSCAPI provider which delegates it to the MSCAPI.
    My working test code based on your code implementing this approach is :
            // RSA 1024 bits Asymmetric encryption of Symmetric AES key             
            // List the certificates from Microsoft KeyStore using SunMSCAPI.
            System.out.println("List of certificates found in Microsoft Personal Keystore:");
            KeyStore ks = KeyStore.getInstance("Windows-MY", "SunMSCAPI");
            ks.load(null, null);
            Enumeration en = ks.aliases();
            PublicKey RSAPubKey = null;
            Key RSAPrivKey = null;
            int i = 0;
            while (en.hasMoreElements())
                String aliasKey = (String) en.nextElement();
                X509Certificate c = (X509Certificate) ks.getCertificate(aliasKey);
                String sss = ks.getCertificateAlias(c);
                if (sss.equals("rsa_key")) // The alias for my key - make sure you change it back to your alias
                    System.out.println("---> alias : " + sss);
                    i = i + 1;
                    String str = c.toString();
                    System.out.println(" Certificate details : " + str);
                    RSAPubKey = c.getPublicKey();
             System.out.println(RSAPubKey.getClass().getName());
                   RSAPrivKey = ks.getKey(aliasKey, null);  //"mypassword".toCharArray()
            System.out.println(RSAPrivKey.getClass().getName());
                    Certificate[] chain = ks.getCertificateChain(aliasKey);
            System.out.println(ks.getProvider().getName());
            System.out.println("No of certificates found from Personal MS Keystore: " + i);
            Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");//, ks.getProvider().getName());       !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                rsaCipher.init(Cipher.WRAP_MODE, RSAPubKey);
            byte[] keyBytes =
                1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 4, 5, 6, 7, 8, 9
            SecretKey aeskey = new SecretKeySpec(keyBytes, "AES");
            byte[] encryptedSymmKey = rsaCipher.wrap(aeskey);
            System.out.println("Encrypted Symmetric Key :" + Arrays.toString(encryptedSymmKey));
            System.out.println("Encrypted Symmetric Key Length in Bytes: " + encryptedSymmKey.length);
            // RSA Decryption of Encrypted Symmetric AES key
            Cipher unwrapRsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", ks.getProvider().getName());       //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            unwrapRsaCipher.init(Cipher.UNWRAP_MODE, RSAPrivKey);
            Key decryptedKey = unwrapRsaCipher.unwrap(encryptedSymmKey, "AES", Cipher.SECRET_KEY);
            System.out.println("Decrypted Symmetric Key :" + Arrays.toString(decryptedKey.getEncoded())); // Matches the 'keyBytes' above

  • Help in RSA cipher

    I need to encrypt a byte[] of size 426 using RSA algorithm but when i call cipher.doFinal(byte[]);
    I get
    javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes
         at com.sun.crypto.provider.RSACipher.a(DashoA6275)
         at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA6275)
         at javax.crypto.Cipher.doFinal(DashoA12275)
         at com.security.cert.KeyStre.encryptDecrypt(KeyStre.java:132)
         at com.security.cert.KeyStre.main(KeyStre.java:79)I know there is an update() in cipher but i am not sure how to use it.
    Could anyone help me out...
    thnx alot

    ok i think i got it...
    It should have been done earlier but i had a party to attend to.
    What i did was take 112 bytes of the 226 byte DH public key and encrypt it with the RSA public Key. I did the same for the next 112 bytes and so on till i encrypted the entire 226 bytes and appended each encrypted block into an byte array.
    For decryption i did the same but I used 128 bytes instead of 112 bytes block and decrypted with the RSA private key.
    but i have a problem the resulting decrypted key is appended with zeros because of the encryption algoritm. The only way to get the completely correct key is to use the length of the original DH public key. Is there any way to solve this small problem...
    Here is the code hope it helps someone....
    plz test it too...
    thnks
    public byte[] encryptDecrypt(String type,byte[] data,Key secretKey) throws EncryptDecryptException
              byte cryptedCipherText[] = null ;
              BufferedReader read;
              try {
              Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
              System.out.println("Provider is-->" + cipher.getProvider().getInfo());
              int j = 0;
              int k=0;
              boolean flag = false;
              byte[] bufferedEncryption = null;
                   if(type.equals("ENCRYPT"))
                        cipher.init(Cipher.ENCRYPT_MODE,secretKey);
                        j = 112;
                        k=112;
                        bufferedEncryption = new byte[k];
                   else
                        cipher.init(Cipher.DECRYPT_MODE,secretKey);
                        j = 128;
                        k=128;
                        bufferedEncryption = new byte[k];
                   int cipherlength = cipher.getOutputSize(data.length);
                   System.out.println("data size-->" + data.length);
                   System.out.println("cipher size-->" + cipherlength);
                   cryptedCipherText= new byte[cipherlength];
                   ByteArrayOutputStream cryptedTextBuffer = new ByteArrayOutputStream();
                   int count =0;
                   int i = 0;
                   while( i< data.length)
                        System.arraycopy(data,i,bufferedEncryption,0,j);
                        System.out.println("sizeof bufferedencryption-->"+bufferedEncryption.length);
                        cryptedCipherText = cipher.doFinal(bufferedEncryption);
                        count+=cryptedCipherText.length;
                        System.out.println("Length-->"+count);
                        cryptedTextBuffer.write(cryptedCipherText);
                        System.out.println("i-->"+i);
                             i+=k;
                             bufferedEncryption = new byte[k];
                             if(flag == true)
                                  break;
                             if(i+k > data.length)
                                  j = data.length - i;
                                  flag = true;
                   cryptedCipherText = cryptedTextBuffer.toByteArray();
                   //cryptedCipherText = cipher.doFinal(data);
              } catch (InvalidKeyException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   //throw new EncryptDecryptException("Invalid Key in encrypt/decrypt");
              } catch (NoSuchAlgorithmException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   //throw new EncryptDecryptException("No such algorithm in encrypt/decrypt");
              } catch (NoSuchPaddingException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   //throw new EncryptDecryptException("No such padding in encrypt/decrypt");
              } catch (IllegalBlockSizeException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (BadPaddingException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              return cryptedCipherText;
    just give the inputs as "ENCRYPT"/"DECRYPT", your data and the public key for encryption and privatekey for decryption.

  • Generating Random Alpha numeric Salt String using MD5 or other algorithm

    Hello,
    I have a requirement where i need to generate a random alpha numeric salt for MD5 algorithm. Is there a best way to generate this salt ?
    The alpha numerics should confine to 5 digits with possible values for each digit being (a-z), (0-9), (A-Z).
    Any good random generator for salt would be appreciated.
    Thanks.

    Hi there,
    I think the book you read is the book "Java Security", I have that one too.
    Please read all those pages before this code.........
    In this code, it used the RSA algorithm to do the encryption and JDK DOES NOT support
    RSA algorithm....
    Beside, this line
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");It implies the BouncyCastle security provider is in use.... so
    www.bouncycastle.org might be a good place to start with....
    Good luck!

  • Is RSA supported by SunJCE?

    Please, this may sound too basic, but I need to know from you whether SunJCE provider includes the RSA algorithm!

    Anyway, it is surprising that Java has so little
    support for public encryption that lies at the heart
    of cryptology, and security in general. Thanks for
    your help!It's not at all surprising if you know anything about US Export regulations. Those have been recently relaxed - which is why RSA is available as a Cipher now in 1.5.
    The standard Java library has some of the best encryption support I've seen, built in. There are Providers available, for free, that give you access to nearly every algorithm I can think of. JAAS provides access to a wide variety of authentication and authorization protocols. HTTPS is brain-dead easy. I can write my own TrustManager class, to control how (and from whom!) my program accepts certificates. There is built-in support for configurable SecurityManagers, that allow you fine-grained control over the allowed operations of the executing program.
    In what context does Java provide "little support for...security in general"?
    Grant

Maybe you are looking for

  • Error while deploying import project

    I am getting the following error while deploying the import project. I dont get any error while importing assets from the xls sheet. it successfully imports all the assets. It only gives error when i try to deploy this project. I have checked all the

  • Migrating from Linux 9.2.0.3 to Solaris 10.2.

    Hello, Which method is best when moving from Linux platform, db 9.2.0.3 to Solaris, db 10.2. I have tried in exp and imp but it will require shutting down production db for more than 8 hours. I am now thinking of replication. Is this a better method?

  • How do i add a table?

    how do i insert a blank table into indesign/

  • JDeveloper  soap library.

    I have installed Oracle Jdeveloper 9.0.695. In lib directory there is soap.jar. Also I use newest version of Oracle IAS . But it comes with old soap library. Which version of iAS will use this library from Jdeveloper ? Or how to "upgrade" soap in iAS

  • Multiple Tabs - only first three/four of seven open - others "failed..."

    I have a few folders of pages that open in tabs. In previous versions of the OS/Safari It would quickly and painlessly open 7 or more tabs at the same time. Now - My whole Safari 3.0 experience seems slooowww and now when I try and open 6+ tabs at th