Rsa keyfactory.getinstance

Hi guys could somebody tell me if iaik support keyfactory for rsa?
Apparently no, infact
try{
            java.security.KeyFactory fact = java.security.KeyFactory.getInstance ( " RSA" , "IAIK");
}throw a java.security.NoSuchAlgorithmException: no such algorithm: RSA for provider IAIK.
Could somebody help me? Suggest?
thanks in advacne.

Interesting, I can get this to work(I'm using java 1.4.2 and iaik_jce.jar). Maybe you have bad version of your jar file.
import iaik.security.provider.IAIK;
import java.security.KeyFactory;
import java.security.Security;
public class temp {
      * @param args
     public static void main(String[] args) {
          Security.addProvider(new IAIK());
          try {
               KeyFactory kf = KeyFactory.getInstance("RSA", "IAIK");
               System.out.println(kf.getAlgorithm());
          } catch (Exception e) {
               e.printStackTrace();
}

Similar Messages

  • I can�t decrypt a text encrypted (using RSA) with keys on smartcard.

    I use a Cyberflex Access e-gate smartcard and I can encrypt and decrypt any text on the card but if I encrypt a text outside using the exported public key, card is not able to decrypt the message.
    On the card side:

    RSAPrivateCrtKey privateKey;
    RSAPublicKey publicKey;
    Cipher cipherRSA;

    private MyIdentity (byte buffer[], short offset, byte length){
            // initialise PIN
            pin = new OwnerPIN(PinTryLimit, MaxPinSize);
            pin.resetAndUnblock();  
            // Key Pair
            KeyPair kp = new KeyPair(KeyPair.ALG_RSA_CRT, (short)1024);
            kp.genKeyPair();
            privateKey = (RSAPrivateCrtKey) kp.getPrivate();
            publicKey = (RSAPublicKey) kp.getPublic();  
            cipherRSA = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);
            if (buffer[offset] == (byte)0) {
                register();
            } else {
                register(buffer, (short)(offset+1) ,(byte)(buffer[offset]));
        private void GetPublicKey (APDU apdu) {
            if (pin.isValidated()){
                byte apduBuffer[] = apdu.getBuffer();
                // short byteRead = (short)(apdu.setIncomingAndReceive());
                   short bytesMod = publicKey.getModulus(apduBuffer, (short) 0);
                   short bytesExp = publicKey.getExponent(apduBuffer,bytesMod);
                   short outbytes = (short) (bytesMod + bytesExp);
                    // Send results
                 apdu.setOutgoing();
                 // indicate the number of bytes in the data field
                 apdu.setOutgoingLength((short)outbytes);
                 // at offset 0 send 128 byte of data in the buffer
                 apdu.sendBytesLong(apduBuffer, (short)APDUDATA, (short)outbytes);
            } else {
                ISOException.throwIt (ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
         private void Decrypt (APDU apdu) {
            byte apduBuffer[] = apdu.getBuffer();
             short byteRead = (short)(apdu.setIncomingAndReceive());
            cipherRSA.init(privateKey, Cipher.MODE_DECRYPT);
              cipherRSA.doFinal(apduBuffer,(short)APDUDATA, byteRead, apduBuffer, (short)APDUDATA);
             // Send results
            apdu.setOutgoing();
            // indicate the number of bytes in the data field
            apdu.setOutgoingLength(byteRead);
            // at offset 0 send x byte of data in the buffer
            apdu.sendBytesLong(apduBuffer, (short)APDUDATA, byteRead);
         }Off the card, I have a java client:
    public void getPublicKey () {
            int CLA, INS, P1, P2;
            int iArray[] = new int[0];
            short sArray[] = new short[0];
            String ss = new String("");
            String s;
            byte [] sBytes = null;
            byte [] myModulus = new byte[128];
            byte [] myExponent = new byte[3];
            try     {
                CLA = 0x68;
                INS = 0x78;
                P1  = 0;
                P2  = 0;
                sArray = iopCard.SendCardAPDU(CLA,INS,P1,P2,iArray,0x83);
                int iErrorCode = iopCard.GetLastErrorCode();
                if (iErrorCode != 0x9000)     {
                    if (iErrorCode == 0x6300) {
                        System.out.println("Wrong PIN");
                    } else {
                        s = iopCard.GetErrorMessage();
                        System.out.println("SendCardAPDU: " + s);
                } else {
                    System.out.println("Getting Public Key...");
                    if (sArray != null)  {
                        sBytes = new byte[sArray.length];
                        for (int i = 0; i < sArray.length; i++)  {
                            sBytes[i] = (byte)sArray;
    ss = new String(sBytes);
    System.out.println ("------ BEGIN PUBLIC KEY -------------------");
    for (int i=0; i < sArray.length; i++){
    System.out.print(Integer.toHexString(ss.charAt(i)).toUpperCase());
    System.out.println ();
    System.out.println ("------ END PUBLIC KEY -------------------");
    } else {
    System.out.println("Nothing.");
    } catch (slbException b) {
    s = b.getMessage();
    System.out.println("Validate error: " + s);
    for (int i=0; i<128; i++){
    myModulus[i] = (byte) sArray[i];
    for (int i=0; i<3; i++){
    myExponent[i] = (byte) sArray[128+i];
    BigInteger modulus = new BigInteger (1,myModulus);
    BigInteger exponent = new BigInteger ("65537"); // there is a well-known bug in getExponent
    RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, exponent);
    KeyFactory keyFactory =null;
    try {
    keyFactory = KeyFactory.getInstance("RSA");
    publicKey = keyFactory.generatePublic(keySpec);
    } catch (NoSuchAlgorithmException e) {
    System.out.println(e.getMessage ());
    } catch (InvalidKeySpecException e) {
    System.out.println(e.getMessage ());
    System.out.println("------------------ BEGIN ------------------");
    ss = new String(publicKey.getEncoded());
    for (int i=0; i < publicKey.getEncoded().length; i++){
    System.out.print(Integer.toHexString(ss.charAt(i)).toUpperCase());
    System.out.println ();
    System.out.println("------------------ END ------------------");
    // to a file
    try {
    //Store in raw format
    FileWriter fw = new FileWriter("public_raw.txt");
    for (int i=0; i < publicKey.getEncoded().length; i++){
    fw.write(Integer.toHexString(ss.charAt(i)).toUpperCase());
    fw.close();
    //could also store it as a Public key
    System.out.println("Public key saved to file");
    } catch(Exception e) {
    System.out.println("Error opening and writing Public key to file : "+e.getMessage());
    public void encrypt () {
    byte cadena[] = {0x01,0x02,0x03,0x04};
    byte resultado[] = new byte[256];
    // Create Cipher
    try {
    cipherRSA.init(Cipher.ENCRYPT_MODE, publicKey);
    resultado = cipherRSA.doFinal (cadena);
    } catch (InvalidKeyException e) {
    System.out.println(e.getMessage());
    } catch (BadPaddingException e) {
    System.out.println(e.getMessage());
    } catch (IllegalBlockSizeException e) {
    System.out.println(e.getMessage());
    String ss = new String (resultado);
    System.out.println("------------------ BEGIN 4 ------------------");
    for (int i=0; i < resultado.length; i++){
    System.out.print(Integer.toHexString(ss.charAt(i)).toUpperCase());
    System.out.println ();
    System.out.println("------------------ END 4 ------------------");
    Another question is that I don�t understand why I get a constant length string when I encrypt a text on the card and variable length string when I encrypt off the card

    I thought that exponent was 3 bytes long...
    On the card I have the following code:
        private void GetExponent (APDU apdu) {
            if (pin.isValidated()){
                byte apduBuffer[] = apdu.getBuffer();
            short bytesExp = publicKey.getExponent(apduBuffer, (short) 0);
               // Send results
                 apdu.setOutgoing();
                 // indicate the number of bytes in the data field
                 apdu.setOutgoingLength((short)bytesExp);
                 // at offset 0 send 128 byte of data in the buffer
                 apdu.sendBytesLong(apduBuffer, (short)APDUDATA, (short)bytesExp);
            } else {
                ISOException.throwIt (ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
        }And if I don't send an APDU with length expected, I get the exception 6C03 (Correct Expected Length (Le) = 0x6C00) so I send APDU with 03 length and I receive the exponent. The problem is that there is a well know bug in getExponent and it returns 00 00 00... so I set it up to 65537 outside the card.

  • Save and load public/private RSA key on file

    hi
    i'm triyng to save and load an RSA key to a file
    i generate the keys:
            KeyPairGenerator generator=null;
            KeyPair coppia=null;
            PrivateKey c_privata=null;
            PublicKey c_pubblica=null;
                generator=KeyPairGenerator.getInstance("RSA");
                //imposto la dimensione
                generator.initialize(1024);
                //genero le 2 chiavi
                coppia=generator.genKeyPair();
                //imposto la privata
                c_privata=coppia.getPrivate();
                //imposo la pubblica
                c_pubblica=coppia.getPublic();
    //i save the key
            FileOutputStream file = new FileOutputStream("key");
            file.write(c_pubblica.getEncoded());
            file.close();and then i use another program that imports the key:
       Key chiave=null;
       FileInputStream file=new FileInputStream("key");
       byte[]byte_chiave=new byte[162];
                 X509EncodedKeySpec chiave_spec = new X509EncodedKeySpec(byte_chiave);
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                chiave = keyFactory.generatePublic(chiave_spec);but when i try to reload he key i get:
    java.security.InvalidKeyException: IOException : DER input, Integer tag error
    where am i wrong?
    thanks

    sorry...
    this is the correct code:
            Key chiave=null;
            FileInputStream file=new FileInputStream(path);
            byte[]byte_chiave=new byte[file.available()];
            System.out.println("leggo: "+file.read(byte_chiave));
            X509EncodedKeySpec chiave_spec = new X509EncodedKeySpec(byte_chiave);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            chiave = keyFactory.generatePublic(chiave_spec);

  • How  to use the RSA  key files generated by Crypto++ in java

    Hi - Good day to all :)
    I have two RSA key files(private key file and public key file) generated by Crypto++ 5.2.1:
    code here:
    void GenerateRSAKey(unsigned int keyLength, const char *privFilename, const char *pubFilename, const char *seed)
         RandomPool randPool;
         randPool.Put((byte *)seed, strlen(seed));
         RSAES_OAEP_SHA_Decryptor priv(randPool, keyLength);
         HexEncoder privFile(new FileSink(privFilename));
         priv.DEREncode(privFile);
         privFile.MessageEnd();
         RSAES_OAEP_SHA_Encryptor pub(priv);
         HexEncoder pubFile(new FileSink(pubFilename));
         pub.DEREncode(pubFile);
         pubFile.MessageEnd();
    }generated private key is:
    30820273020100300D06092A864886F70D01010105000482025D3082025902010002818100E19891D888651221AF315B369873F01910D097F554723EE8748FA230F2B954EBEFC57CB402DD03333BA9514AB5256EF92BE714C710D166A1D86CB7A11EFB4499506826AB873F5036B92F07BBB3ABB8F562646DE6E11031C46542633605FDE4A31E0E0A8651B4BC7743C18266D664E59E713D7595ED3D3B6C2F94C6072E276171020111028180425A0CC7372CC918F74AC07978221970C8B5D25736F46CDAF51B2FB40B27735473B28E16D3AA6A5A5CD7724326382FB2B28F4258AA97F1026CD4AE7AAEC25F77D54DF69BB3979E2893EBB071DA5752871BC8C60F9B5546C466F3103884D6B67FADCD51B17899991989507CB16F45DD76EC0DEDA1BD979ED1A101179F9687E9E5024100FFCAAEF814F12DCBDF20D4CFDD5007738DAAE45AE7EC2FD8E23A9EFCA85FADCAF61B03BFEA6FE6023E78700F804C4C275375A85BC367FE39D5FB2E0F0A4555F7024100E1C797A20FB108ADAFECDB025665FF500FDBB4F0829BAAE95833C046005DCA593F6C2437CD3A9AB7CC04372F422B0EE2C7FED87AA53821366962AE0CBDAD89D702402D23C48621D035421851167F08F00150A08791B5B074F96282469486F0895AE794D7973FFC31DD4BB0ABD78A43D13A9D8732E1799AF43BEC16B3DAF3986696B30240351FE7716D1A98A156921569F6361DF4B86FEE56B551CDDC8D395A6AD2E8E4513C1971EF031CD91C3000FDED00829A173E1DD895540D34FDBE71925D59CE7AC9024014A4347A1E7408FBB0A9AE5064FA58CAF2BCA5C00B8082A46EECABFA5CBF61364FEE81E2C049F399A2F601C802DD54A6D9340FABE62D6D1F913026C8B3764AFEI use this key in java
    BufferedInputStream input=new BufferedInputStream(new FileInputStream("privateKey"));
              int size= input.available();
              byte[]buffer=new byte[size];
              input.read(buffer);
    X509EncodedKeySpec lX509EncodedKeySpec = new X509EncodedKeySpec(buffer);
              PrivateKey lPrivateKey = KeyFactory.getInstance("RSA").generatePrivate(lX509EncodedKeySpec);there is a exception,at generatePrivate() method
    at sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:294)
         at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:171)
         at java.security.KeyFactory.generatePrivate(KeyFactory.java:322)
         at test.Main.main(Main.java:27)any body can help me?

    X509 is for public keys, not private keys. You need PKCS8 using PKCS8EncodedKeySpec on the hex decoded private key string.
    Your method for reading the private key from the file is flawed. The method available() does not guarantee to give you the file length. This is easy to prove since files can be longer than Integer.MAX_VALUE and available() returns an 'int'. To get the file length use File.length() which returns a 'long'. Also, reading from an InputStream using
    input.read(buffer); does not guarantee to read all the bytes. For that you need to use something like DataInputStream.readFully().

  • I can't decrypt a text encrypted(useing RSA) with publickey on mobile

    hi all, I got some problem with my code,
    when I wanna use the JSR177 of J2ME to do something about Decryption
    here is some of my code as following:
    KeyFactory kf = KeyFactory.getInstance("RSA");
    byte[] publickeyEncode
    x509EncodedKeySpec keyspec = new X509EncodedKeySpec(publickeyEncode)
    PublicKey pubkey = kf.generatePublic(Keyspec) as using that, we can renew our publickey which is from the server.
    but there are Exception when I use the publickey to do decryption.
    java.security.InvalidKeyException
    at com.sun.satsa.crypto.RSACipher.init(+31)
    at javax.crypto.Cipher.init(+30)
    at javax.crypto.Cipher.init(+7)
    at KEYback.startApp(+210)
    at javax.microedition.midlet.MIDletProxy.startApp(+7)
    at com.sun.midp.midlet.Scheduler.schedule(+270)
    at com.sun.midp.main.Main.runLocalClass(+28)
    at com.sun.midp.main.Main.main(+116) however, the problem is solved when I change the DECRYPTO_MODE into ENCRYPTO_MODE
    so, is it impossible to do decryption with publickey on the mobile???

    because in the JSR177 apis,there is not "PrivateKey" this class so we only can use the "PublicKey" to do Decryption on the Mobile and do Encryption on Server with the PrivateKey..Sorry, I forgot that you are working in the J2ME context.
    as the result of our test , when the cipher_mode is "Encrypto", the code is run well, but when we turn is to "Decrytpo", the Exception is appear.Did you check that the encryption does return a valid result? Because while reading the JSR177 javadoc I got the feeling that the PublicKey only exists for verifying signatures.
    May be you should consider switching to the J2ME Bouncycastle implementation completly (or only for decryption). AFAIK it works idependent of JSR177.
    Jan

  • RSA Decryption Error - Illegal Use

    Hi there,
    i have a crypthographic problem using a JavaCard application and a Java host application.
    On the card i create a cipher object and a private/public key:
    Cipher cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1_OAEP, false);
    KeyPair kP = new KeyPair(KeyPair.ALG_RSA, KeyBuilder.LENGTH_RSA_1984);
    kP.genKeyPair();
    RSAPublicKey app_public_key = (RSAPublicKey) kP.getPublic();
    RSAPrivateKey app_private_key = (RSAPrivateKey) kP.getPrivate();There are two functions on the card to send the modulus and the exponent from the public key to the host application using two APDUs.
    private void sendModulus(APDU apdu)
         byte[] buffer = apdu.getBuffer();
         short modLength = app_public_key.getModulus(buffer, (short)ISO7816.OFFSET_CDATA);
         apdu.setOutgoing();
         apdu.setOutgoingLength(modLength);
         apdu.sendBytesLong(buffer, (short)ISO7816.OFFSET_CDATA, modLength);
    private void sendExponent(APDU apdu)
         byte[] buffer = apdu.getBuffer();
         short expLength = app_public_key.getExponent(buffer, (short)ISO7816.OFFSET_CDATA);
         apdu.setOutgoing();
         apdu.setOutgoingLength(expLength);
         apdu.sendBytesLong(buffer, (short)ISO7816.OFFSET_CDATA, expLength);
    }On the host i request the modulus and the exponent and build the public key:
    public void getAppMod() throws TerminalException
                      //get modulus
         ResponseApdu response = send(new CommandApdu("0x00 0xAA 0x01 0x00"));
         System.out.println(response.getStatusHexString());
         byte[] modulus = response.getData().toByteArray();
                      //get exponent
         ResponseApdu response = send(new CommandApdu("0x00 0xAA 0x02 0x00"));
         System.out.println(response.getStatusHexString());
         byte[] exponent = response.getData().toByteArray();
                      RSAPublicKeySpec kSpec = new RSAPublicKeySpec(new BigInteger(1, mod), new BigInteger(1, exp));
         KeyFactory kFac = KeyFactory.getInstance("RSA");
         RSAPublicKey app_rsa_publicKey = (RSAPublicKey)kFac.generatePublic(kSpec);
    }Now i create a cipher object on the host application, encrypt a message with this public key and send it to the card:
    Security.addProvider(new BouncyCastleProvider());
    Cipher cipher = Cipher.getInstance("RSA", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, app_rsa_publicKey);
    byte[] cipherData = cipher.doFinal(bData); //bData is the message and cipherData the encrypted 248byte message.On the card now im trying to decrypt it with the private key.
    byte[] buffer = apdu.getBuffer();
    short bytesRead = apdu.setIncomingAndReceive();
    cipher.init(app_private_key, Cipher.MODE_DECRYPT);
    short messageLength = cipher.doFinal(buffer, (short)ISO7816.OFFSET_CDATA, bytesRead, buffer, (short)ISO7816.OFFSET_CDATA);
    }But the "doFinal" method throws an "ILLEGAL_USE" Exception...
    I dont know what to do now....
    Is it possible that the "BouncyCastle" Cipher object on the host side does not fit the cipher object on the card side ? because the key was transfered correctlly :(
    is there any provider i can use whre i dont need a free library like bouncycastle ?
    Thanks for helping...
    Edited by: 963778 on 08.10.2012 01:56

    Hi again,
    i think i solved my problem.
    So far it seems it wasnt the same RSA padding on card an host.
    After create the cipher on the card this way:
    cipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, false);And on the host this way:
    cipher = Cipher.getInstance("RSA/NONE/PKCS1Padding", "BC");it works fine from host to card.
    The other way from card to host i get an "unknown block type" error.

  • 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 encrypt byte array with out padding using RSA in Java?

    I've modulus and public exponent as byte[] array, so I'm trying to convert into BigIntegers and then create public key and then Cipher. Here is the example code:
    With this I'm always getting different encrypted bytes, is it because of padding. I dont want to use any padding so what parameter I need to pass along with RSA? I've modulus byte[] array size 64 bytes. I believe I'll get 64 encrypted bytes. I've content size of 32 bytes to be encrypted.
    --------code begin ---------------------------
    BigInteger bexponent = new BigInteger(pubExpo);
    BigInteger bmodulus = new BigInteger(modulus);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(bmodulus, bexponent);
    RSAPublicKey pubKey = (RSAPublicKey)keyFactory.generatePublic(pubKeySpec);
    Cipher c = Cipher.getInstance("RSA");
    c.init(Cipher.ENCRYPT_MODE, pubKey);
    return c.doFinal(content);
    --------code end---------------------------

    With this I'm always getting different encrypted
    bytes, is it because of padding. Yes, if you're using PKCS1Padding (which is the default in SunJCE if you don't specify it). Have a look at the PKCS1 spec if you haven't seen it already.
    http://www.rsasecurity.com/rsalabs/pkcs
    Section 7.2.1 talks about type 2 padding, which uses random bytes as the PS string.
    I dont want to use
    any padding so what parameter I need to pass along
    with RSA? NOPADDING. You should be able to find this out by look at the "Supported Paddings" parameter in your provider's database. Which of course, means you'll need to supply the right number of bytes to the Cipher.

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

  • Help with RSA Encryption using SATSA

    Hello,
    I am a new to writing code on J2ME . I am trying to encrypt data using
    RSA public key on J2ME using SATSA.
    I generated the public key using openssl in the PEM format and stored the
    key (mypublickey) as a Base64 decoded byte array in my code.
    Next, I did the following:
    X509EncodedKeySpec test - new X509EncodedKeySpec(mypublickey);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey key = kf.generatePublic(test);
    I used this key to encrypt as follows:
    cipher c = Cipher.getInstance("RSA");
    c.init(Cipher.ENCRYPT_MODE, key);
    c.doFinal(data,0,data.length,ciphertext,0);
    where byte[] data = "1234567890".getBytes();
    I get no errors during this process.
    Now, when I try to decrypt the string, I get a padding error as follows:
    javax.crypto.BadPaddingException: Data must start with zero
    The decode is done on a server.
    I tried getting an instance of the cipher with RSA/ECB/NoPadding and this time the decrypt gives junk.
    Question 2: The SATSA example online at http://java.sun.com/j2me/docs/satsa-dg/AppD.html
    has a public key embedded as a byte array. They haven't explained how
    this key is generated. Does someone know?
    Question 3: Suppose, I can get the modulus and exponent of the public key is there any way I can convert it to X509EncodedKeySpec so that I can
    use the APIs in SATSA?
    Thanks in advance for your help. I have been trying to solve this for a lot of time and any help will be greatly appreciated.

    Just wanted to add my code:
    public class test2 {
         public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, ShortBufferException {
              // TODO Auto-generated method stub
              byte [] data = "012345678901234567890123456789ab".getBytes();
              Base64 base64 = new Base64();
    /*public key generated by
              byte [] mypublickey = base64.decode("publickey in PEM format");
              byte [] ciphertext = new byte[128];
              X509EncodedKeySpec test = new X509EncodedKeySpec(mypublickey);
              byte [] myprivatekey = base64.decode("privatekey in pkcs8format");
    KeyFactory rsakeyfac = KeyFactory.getInstance("RSA");
              PublicKey pubkey = rsakeyfac.generatePublic(test);
              Cipher c1 = Cipher.getInstance("RSA");
              c1.init(Cipher.ENCRYPT_MODE, pubkey);
              c1.doFinal(data, 0,data.length, ciphertext);
              PKCS8EncodedKeySpec pks2 = new PKCS8EncodedKeySpec(myprivatekey);
              RSAPrivateCrtKey privkey = (RSAPrivateCrtKey)rsakeyfac.generatePrivate(pks2);
              Cipher c2 = Cipher.getInstance("RSA");
              c2.init(Cipher.DECRYPT_MODE, privkey);
              byte [] decrypteddata = c2.doFinal(ciphertext);
              System.out.println("Decrypted String is:"+new String(decrypteddata).trim());
    Error that I get is:
    Exception in thread "main" javax.crypto.BadPaddingException: Data must start with zero
         at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
         at sun.security.rsa.RSAPadding.unpad(Unknown Source)
         at com.sun.crypto.provider.RSACipher.a(DashoA13*..)
         at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA13*..)
         at javax.crypto.Cipher.doFinal(DashoA13*..)

  • Store RSA keys

    I have Generated the public and private keys for RSA using the following Code
    KeyPairGenerator key=KeyPairGenerator.getInstance("RSA");
    KeyPair k=key.generateKeyPair();
    PrivateKey pri=k.getPrivate();
    PublicKey pub=k.getPublic();
    byte[] prikey_bytes=pri.getEncoded();          
    byte[] pubkey_bytes=pub.getEncoded();I want to know how can i store these keys in a txt file and regenerate_ the same the next time i want to decrypt the message.
    I used the following line to regenerate the keys,but it failed to work.
    SecretKey nkey=new SecretKeySpec(prikey_bytes,"RSA");Does anyone have a solution for the same?

    You need to know the appropriate key specifications for the public and private keys. Then you use a KeyFactory to convert a key specification to the PublicKey and PrivateKey. In your case, something like the following should work: X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubkey_bytes);
    PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(prikey_bytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey pri2 = kf.generatePrivate(priKeySpec);
    PublicKey pub2 = kf.generatePublic(pubKeySpec);

  • Java RSA PKCS1 padding Help!

    I'm doing a client for my vb6 coded server, though in vb6 i use RSA padding PKCS1 with loading public and private key from PEM formated files,
    it works in vb6, but in java. I have trouble recreating the rsa cryptation part for protocols to server.

    I'm using a old c++ lib in vb6 since it doesnt really allow rsa to be simple.
    Java; this stuff works to encryp / decrypt THOUGH trying to decrypt Rsa encrypted byte array from vb6, returns some error with was expecting zero at start, guessing it's just the java example thats not PKCS1 padding.
          * RSA:
         private static Cipher enc;
         private static Cipher dec;
         public static void loadrsa(String pub, String priv) {
              try {
                            //pub and priv, are file paths for the pem keys.
                   byte[] pubKeyBytes  = getBytesFromFile(pub);
                   byte[] privKeyBytes = getBytesFromFile(priv);
                   KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                   X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKeyBytes);
                   RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubSpec);
                   PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes);
                   RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec);          
                   enc = Cipher.getInstance("RSA");
                   enc.init(Cipher.ENCRYPT_MODE, pubKey);
                   dec = Cipher.getInstance("RSA");
                   dec.init(Cipher.DECRYPT_MODE, privKey);
              } catch (Exception e) {
                   System.out.println("loadrsa():::");
                   System.out.println(e);
         public static byte[] RSAE(byte[] data) {
              try {
                   return enc.doFinal(data);
              } catch (Exception e) {
                   System.out.println("RSAE():::");
                   System.out.println(e);
              return null;
         public static byte[] RSAD(byte[] data) {
              try {
                   return dec.doFinal(data);
              } catch (Exception e) {
                   System.out.println("RSAD():::");
                   System.out.println(e);
              return null;
         private static byte[] getBytesFromFile(String filePath) throws IOException {
              File file = new File(filePath);
              InputStream is = new FileInputStream(file);
              long length = file.length();
              byte[] bytes = new byte[(int)length];
              int offset = 0;
              int numRead = 0;
              while (offset < bytes.length &&
                        (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
                  offset += numRead;
              if (offset < bytes.length) {
                  throw new IOException("Could not completely read file " + file.getName());
              is.close();
              return bytes;
         }

  • RSA help

    KeyFactory       keyFactory = KeyFactory.getInstance("RSA", "BC");
            RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger("d46f473a2d746537de2056ae3092c451", 16),
                    new BigInteger("11", 16));
            RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(new BigInteger("d46f473a2d746537de2056ae3092c451", 16),
                    new BigInteger("57791d5430d593164082036ad8b29fb1", 16));
            RSAPublicKey pubKey = (RSAPublicKey)keyFactory.generatePublic(pubKeySpec);
            RSAPrivateKey privKey = (RSAPrivateKey)keyFactory.generatePrivate(privKeySpec);hello..i am doing my RSA encryption using password..can somebody explain the code above..as far as i know RSA need 1024 but the above example is 128 which is one-eight from it.

    KeyFactory       keyFactory = KeyFactory.getInstance("RSA", "BC");
            RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger("d46f473a2d746537de2056ae3092c451", 16),
                    new BigInteger("11", 16));
            RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(new BigInteger("d46f473a2d746537de2056ae3092c451", 16),
                    new BigInteger("57791d5430d593164082036ad8b29fb1", 16));
            RSAPublicKey pubKey = (RSAPublicKey)keyFactory.generatePublic(pubKeySpec);
            RSAPrivateKey privKey = (RSAPrivateKey)keyFactory.generatePrivate(privKeySpec);hello..i am doing my RSA encryption using password..can somebody explain the code above..as far as i know RSA need 1024 but the above example is 128 which is one-eight from it.

  • Reading private key: works in jdk 1.5, but throws exception in 1.4

    Hello,
    I am trying to read an RSA private key from a file. I am using the following code snippet:
    KeySpec spec = new RSAPrivateKeySpec(modulus, pExp);
    KeyFactory factory = KeyFactory.getInstance("RSA");
    PrivateKey key = factory.generatePrivate(spec);
    This runs perfectly fine under jdk 1.5 on keys I generate with OpenSSL. However, if I recompile and run under jdk 1.4, I get the following exception:
    java.security.spec.InvalidKeySpecException: Unknown key spec.
         at com.sun.net.ssl.internal.ssl.JS_KeyFactory.engineGeneratePrivate(DashoA6275)
         at com.sun.net.ssl.internal.ssl.JSA_RSAKeyFactory.engineGeneratePrivate(DashoA6275)
         at java.security.KeyFactory.generatePrivate(KeyFactory.java:237)
    I have also tried using RSAPrivateCrtKeySpec but I get the same error. Can anyone shed some light on what is going on?
    Thank you.

    'Unlimited Strength Jurisdiction Policy Files 1.4' Could be the solution.
    I had a similar problem with java 1.4 and those files do the work.
    ... finally the problem was that the password that protectd the keystore had 7 characters, using one of 5 characters works ok...

  • I need help with Creating Key Pairs

    Hello,
    I need help with Creating Key Pairs, I generate key pais with aba provider, but the keys generated are not base 64.
    the class is :
    import java.io.*;
    import java.math.BigInteger;
    import java.security.*;
    import java.security.spec.*;
    import java.security.interfaces.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import au.net.aba.crypto.provider.ABAProvider;
    class CreateKeyPairs {
    private static KeyPair keyPair;
    private static KeyPairGenerator pairGenerator;
    private static PrivateKey privateKey;
    private static PublicKey publicKey;
    public static void main(String[] args) throws Exception {
    if (args.length != 2) {
    System.out.println("Usage: java CreateKeyParis public_key_file_name privete_key_file_name");
    return;
    createKeys();
    saveKey(args[0],publicKey);
    saveKey(args[1],privateKey);
    private static void createKeys() throws Exception {
    Security.addProvider(new ABAProvider());
    pairGenerator = KeyPairGenerator.getInstance("RSA","ABA");
    pairGenerator.initialize(1024, new SecureRandom());
    keyPair = pairGenerator.generateKeyPair();
    privateKey = keyPair.getPrivate();
    publicKey = keyPair.getPublic();
    private synchronized static void saveKey(String filename,PrivateKey key) throws Exception {
    ObjectOutputStream out= new ObjectOutputStream(new FileOutputStream(filename));
    out.writeObject(key);
    out.close();
    private synchronized static void saveKey(String filename,PublicKey key) throws Exception {
    ObjectOutputStream out= new ObjectOutputStream( new FileOutputStream(filename));
    out.writeObject(key);
    out.close();
    the public key is:
    �� sr com.sun.rsajca.JSA_RSAPublicKeyrC��� xr com.sun.rsajca.JS_PublicKey~5< ~��% L thePublicKeyt Lcom/sun/rsasign/p;xpsr com.sun.rsasign.anm����9�[ [ at [B[ bq ~ xr com.sun.rsasign.p��(!g�� L at Ljava/lang/String;[ bt [Ljava/lang/String;xr com.sun.rsasign.c�"dyU�|  xpt Javaur [Ljava.lang.String;��V��{G  xp   q ~ ur [B���T�  xp   ��ccR}o���[!#I����lo������
    ����^"`8�|���Z>������&
    d ����"B��
    ^5���a����jw9�����D���D�)�*3/h��7�|��I�d�$�4f�8_�|���yuq ~
    How i can generated the key pairs in base 64 or binary????
    Thanxs for help me
    Luis Navarro Nu�ez
    Santiago.
    Chile.
    South America.

    I don't use ABA but BouncyCastle
    this could help you :
    try
    java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    java.security.KeyPairGenerator kg = java.security.KeyPairGenerator.getInstance("RSA","BC");
    java.security.KeyPair kp = kg.generateKeyPair();
    java.security.Key pub = kp.getPublic();
    java.security.Key pri = kp.getPrivate();
    System.out.println("pub: " + pub);
    System.out.println("pri: " + pri);
    byte[] pub_e = pub.getEncoded();
    byte[] pri_e = pri.getEncoded();
    java.io.PrintWriter o;
    java.io.DataInputStream i;
    java.io.File f;
    o = new java.io.PrintWriter(new java.io.FileOutputStream("d:/pub64"));
    o.println(new sun.misc.BASE64Encoder().encode(pub_e));
    o.close();
    o = new java.io.PrintWriter(new java.io.FileOutputStream("d:/pri64"));
    o.println(new sun.misc.BASE64Encoder().encode(pri_e));
    o.close();
    java.io.BufferedReader br = new java.io.BufferedReader(new java.io.FileReader("d:/pub64"));
    StringBuffer keyBase64 = new StringBuffer();
    String line = br.readLine ();
    while(line != null)
    keyBase64.append (line);
    line = br.readLine ();
    byte [] pubBytes = new sun.misc.BASE64Decoder().decodeBuffer(keyBase64.toString ());
    br = new java.io.BufferedReader(new java.io.FileReader("d:/pri64"));
    keyBase64 = new StringBuffer();
    line = br.readLine ();
    while(line != null)
    keyBase64.append (line);
    line = br.readLine ();
    byte [] priBytes = new sun.misc.BASE64Decoder().decodeBuffer(keyBase64.toString ());
    java.security.KeyFactory kf = java.security.KeyFactory.getInstance("RSA","BC");
    java.security.Key pubKey = kf.generatePublic(new java.security.spec.X509EncodedKeySpec(pubBytes));
    System.out.println("pub: " + pubKey);
    java.security.Key priKey = kf.generatePrivate(new java.security.spec.PKCS8EncodedKeySpec(priBytes));
    System.out.println("pri: " + priKey);
    catch(Exception e)
    e.printStackTrace ();
    }

Maybe you are looking for

  • S_alr_87013574 Report

    Hi Experts, Can you tell me the functionality of S_alr_87013574 Report. Since this report is not executing from my side. Is there any required configuration to be done.Or is there any payment report in PS. Thanks & Regards, Gagan

  • How to get rid of "wild" sessions?

    Hello, is there a possibility to kill DB-sessions for a workspace admin? Situation: I'm having a class scenario where students create data structures and (APEX-) applications on their own and teams of five persons each work in seperate workspaces. As

  • Urgent. [Items - Valuation Method] error when creating documents

    I have recently upgraded one of my customers databases to the newest 2005 sp: 01 pl: 45 version Before that, they were running 2005, but with no service pack. However, after the upgrade they cannot any longer create salesorders, invoices etc! They al

  • Is it possible to create views with parameters ?

    Hi, As MS-Access, is it possible to create views with parameters ? Ms-Access syntax : parameters [a] text; select * from table where code = [a] If yes, can you give samples ? Regards Pascal

  • Print preview while getting otf data

    hi experts, can somebody tell me how to get the print preview of sap script while getting the otf data. I have set the ITCPO-TDGETOTF = 'X' option in OPEN FORM but when i give it its not showing the output. How can  I see output ?