RSA cipher creation

hi, i encounter a problem when i try to generate RSA cipher, here is the code:
// generate RSA cipher
try {
cp = Cipher.getInstance("RSA");
} catch (NoSuchAlgorithmException ex) {
System.out.println("RSA cipher not found in provider.");
return;
And the error is "RSA cipher not found in provider". My current compiler version used is j2sdk1.4.2_02.
can anyone help me to solve this, thx a lot.

hi ggainey,
thx for ur help, i've downloaded the bouncycastle .jar file.
Everything seem alright, but i encountered an error when i execute my program.
Error :
Exception in thread "main" java.lang.SecurityException: The provider BC may not be signed by a trusted party
at javax.crypto.SunJCE_b.a(DashoA6275)
at javax.crypto.Cipher.a(DashoA6275)
at javax.crypto.Cipher.getInstance(DashoA6275)
at SampleRSACrypto.main(SampleRSACrypto.java:64)
here is my program code :
import java.io.*;
import java.util.Arrays;
import java.security.Security;
import java.security.Provider;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class SampleRSACrypto {
static final byte[] plainText = "Secret Message".getBytes();
public static void main(String argv[]) {
KeyPairGenerator rsaKeyPairGen;
KeyPair rsaKeyPair;
PublicKey rsaPub;
PrivateKey rsaPriv;
Cipher cp = null;
byte[] cipherText = null, newPlainText = null;
// Add a RSA security provider
try {
          Security.addProvider(new BouncyCastleProvider());
     catch(Exception e) {
          System.err.println("Error loading security provider (" + e.getMessage() + ")");
// Generate an RSA key pair
try {
rsaKeyPairGen = KeyPairGenerator.getInstance("RSA", "BC");
} catch (NoSuchAlgorithmException ex) {
System.out.println("RSA KeyPair Generator not found in bouncycastle provider.");
return;
} catch (NoSuchProviderException ex) {
// Should not happen.
System.out.println("Provider bouncycastle not found.");
return;
// Use modulus length = 1024
rsaKeyPairGen.initialize(1024);
rsaKeyPair = rsaKeyPairGen.generateKeyPair();
if (rsaKeyPair == null) {
System.out.println("Key generation failure. KeyPair was not generated.");
return;
// get RSA public key.
rsaPub = rsaKeyPair.getPublic();
// get RSA private key.
rsaPriv = rsaKeyPair.getPrivate();
// generate RSA cipher
try {
cp = Cipher.getInstance("RSA", "BC");
} catch (NoSuchAlgorithmException ex) {
System.out.println("RSA cipher not found in bouncycastle provider.");
return;
} catch (NoSuchProviderException ex) {
// Should not happen.
System.out.println("Provider bouncycastle not found.");
return;
} catch (NoSuchPaddingException ex) {
// Should not happen.
System.out.println("Invalid padding.");
return;
// Encrypt the plain text
try {
cp.init(Cipher.ENCRYPT_MODE, rsaPub);
cipherText = cp.doFinal(plainText);
} catch (Exception ex) {
System.out.println("Error encrypting: " + ex.getMessage());
return;
// Decrypt the cipher text
try {
cp.init(Cipher.DECRYPT_MODE, rsaPriv);
newPlainText = cp.doFinal(cipherText);
} catch (Exception ex) {
System.out.println("Error decrypting: " + ex.getMessage());
return;
// Verify the result.
if (Arrays.equals(plainText, newPlainText)) {
System.out.println("Encryption and decryption successful.");
} else {
System.out.println("Encryption and decryption not successful.");
i downloaded the .jar file from http://www.bouncycastle.org/latest_releases.html, do u have any idea of why i got such an error in my program?
thx a lot.

Similar Messages

  • Cannot decrypt RSA encrypted text : due to : input too large for RSA cipher

    Hi,
    I am in a fix trying to decrypt this RSA encrypted String ... plzz help
    I have the encrypted text as a String.
    This is what I do to decrypt it using the Private key
    - Determine the block size of the Cipher object
    - Get the array of bytes from the String
    - Find out how many block sized partitions I have in the array
    - Encrypt the exact block sized partitions using update() method
    - Ok, now its easy to find out how many bytes remain (using % operator)
    - If the remaining bytes is 0 then simply call the 'doFinal()'
    i.e. the one which returns an array of bytes and takes no args
    - If the remaining bytes is not zero then call the
    'doFinal(byte [] input, int offset, in inputLen)' method for the
    bytes which actually remained
    However, this doesnt work. This is making me go really crazy.
    Can anyone point out whats wrong ? Plzz
    Here is the (childish) code
    Cipher rsaDecipher = null;
    //The initialization stuff for rsaDecipher
    //The rsaDecipher Cipher is using 256 bit keys
    //I havent specified anything regarding padding
    //And, I am using BouncyCastle
    String encryptedString;
    // read in the string from the network
    // this string is encrypted using an RSA public key generated earlier
    // I have to decrypt this string using the corresponding Private key
    byte [] input = encryptedString.getBytes();
    int blockSize = rsaDecipher.getBlockSize();
    int outputSize = rsaDecipher.getOutputSize(blockSize);
    byte [] output = new byte[outputSize];
    int numBlockSizedPartitions = input.length / blockSize;
    int numRemainingBytes = input.length % blockSize;
    boolean hasRemainingBytes = false;
    if (numRemainingBytes > 0)
      hasRemainingBytes = true;
    int offset = 0;
    int inputLen = blockSize;
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < numBlockSizedPartitions; i++) {
      output = rsaDecipher.update(input, offset, blockSize);
      offset += blockSize;
      buf.append(new String(output));
    if (hasRemainingBytes) {
      //This is excatly where I get the "input too large for RSA cipher"
      //Which is suffixed with ArrayIndexOutofBounds
      output = rsaDecipher.doFinal(input,offset,numRemainingBytes);
    } else {
      output = rsaDecipher.doFinal();
    buf.append(new String(output));
    //After having reached till here, will it be wrong if I assumed that I
    //have the properly decrypted string ???

    Hi,
    I am in a fix trying to decrypt this RSA encrypted
    String ... plzz helpYou're already broken at this point.
    Repeat after me: ciphertext CANNOT be safely represented as a String. Strings have internal structure - if you hand ciphertext to the new String(byte[]) constructor, it will eat your ciphertext and leave you with garbage. Said garbage will fail to decrypt in a variety of puzzling fashions.
    If you want to transmit ciphertext as a String, you need to use something like Base64 to encode the raw bytes. Then, on the receiving side, you must Base64-DEcode back into bytes, and then decrypt the resulting byte[].
    Second - using RSA as a general-purpose cipher is a bad idea. Don't do that. It's slow (on the order of 100x slower than the slowest symmetric cipher). It has a HUGE block size (governed by the keysize). And it's subject to attack if used as a stream-cipher (IIRC - I can no longer find the reference for that, so take it with a grain of salt...) Standard practice is to use RSA only to encrypt a generated key for some symmetric algorithm (like, say, AES), and use that key as a session-key.
    At any rate - the code you posted is broken before you get to this line:byte [] input = encryptedString.getBytes();Go back to the encrypting and and make it stop treating your ciphertext as a String.
    Grant

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

  • RSA with Cryptix: can encrypt but not decrypt? Please help.. :)

    Hi all,
    I've been trying to do RSA encryption/decryption using a pair of keys created with keytool. I've been able to encrypt some bytes, but when I attempt to decrypt the results immediately using the private key, I received the following exception:
    IllegalBlockSizeException: RSA: Cipher in DECRYPT state with an incomplete final block
    Please can anyone save me out of my misery and shed some light on this problem? Thanks a great deal in advance.
    Best Regards,
    Kenshin
    Here are the code snippets:
    // 1. imported APIs:
    import javax.net.ssl.*;
    import java.io.*;
    import java.security.*;
    import java.security.interfaces.*;
    import java.security.spec.*;
    import java.security.cert.*;
    import java.security.cert.Certificate;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import cryptix.provider.Cryptix;
    import xjava.security.Cipher;
    import xjava.security.CipherInputStream;
    import xjava.security.CipherOutputStream;
    import xjava.security.interfaces.*;
    import cryptix.provider.rsa.*;
    // 2. Getting the Public Key from the created cert:
    File certFile = new File("c:/keystore/jbossSSL.cer");
    FileInputStream certFileInStream = new FileInputStream(certFile);
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    Certificate cert = (Certificate)cf.generateCertificate(certFileInStream);
    RSAPublicKey serverPublicKey = (RSAPublicKey)cert.getPublicKey();
    // 3. Doing the encryption:
    Security.addProvider( new cryptix.provider.Cryptix());
    Cipher cipherInstance = Cipher.getInstance("RSA/ECB/PKCS7", "Cryptix");
    CryptixRSAPublicKey vCryptixRSAPubKey = (CryptixRSAPublicKey) new RawRSAPublicKey(serverPublicKey.getPublicExponent());
    cipherInstance.initEncrypt(vCryptixRSAPubKey);
    System.out.println("String to be encypted: " + sRandomString);
    // Sample of what is printed: String to be encypted: 2201162506010696613
    ByteArrayInputStream clearTextInStream = new ByteArrayInputStream(sRandomString.getBytes());
    CipherInputStream cInStream = new CipherInputStream(clearTextInStream, cipherInstance);
    ByteArrayOutputStream cipherTextOutStream = new ByteArrayOutputStream();
    CipherOutputStream cOutStream = new CipherOutputStream(cipherTextOutStream, cipherInstance);
    byte[] buffer = new byte[8192];
    int length;
    while((length= cInStream.read(buffer))!=-1)
    cOutStream.write(buffer, 0, length);
    cOutStream.close();
    cInStream.close();
    cipherTextOutStream.close();
    clearTextInStream.close();
    String sEncodedString = new String(cipherTextOutStream.toByteArray());
    System.out.println("String encrpted: " + sEncodedString);
    // Sample of what is printed: String to encrpted: 2 2 01 1 6 25 0 6 01 0 6 96 6 1 3&#9786; &#9787;&#9787;
    // 4. Getting the Private key from the keystore
    FileInputStream in = new FileInputStream("C:/keystore/jbossSSL.keystore");
    KeyStore catalinaKeyStore = KeyStore.getInstance("jks");
    catalinaKeyStore.load(in, "jbossSSL".toCharArray());
    RSAPrivateKey privateK = (RSAPrivateKey)catalinaKeyStore.getKey("jbossSSL", "jbossSSL".toCharArray());
    CryptixRSAPrivateKey vCryptixRSAPriKey = (CryptixRSAPrivateKey) new RawRSAPrivateKey(privateK.getPrivateExponent(), privateK.getModulus());
    cipherInstance.initDecrypt(vCryptixRSAPriKey);
    // 5. Doing the decryption:
    ByteArrayInputStream cipherTextInStream = new ByteArrayInputStream(sEncodedString.getBytes());
    cInStream = new CipherInputStream(cipherTextInStream,cipherInstance);
    ByteArrayOutputStream clearTextOutStream = new ByteArrayOutputStream();
    cOutStream = new CipherOutputStream(clearTextOutStream,cipherInstance);
    while((length= cInStream.read(buffer))!=-1)
    cOutStream.write(buffer, 0, length); >> exception thrown here
    cOutStream.close();
    cInStream.close();
    clearTextOutStream.close();
    cipherTextInStream.close();
    String sDecodedString = new String(clearTextOutStream.toByteArray());
    System.out.println("Stringdecrpted: " + sDecodedString);

    Here is working RSA example Maybe will help you. (may has a few typing errors becosu I rmoved some confidential data ;) )
    import java.util.*;
    import javax.swing.*;
    import java.io.*;
    import java.security.*;
    import javax.crypto.Cipher;
    import xjava.security.*;
    import cryptix.provider.Cryptix;
    import xjava.security.interfaces.CryptixRSAPublicKey;
    import xjava.security.interfaces.CryptixRSAPrivateKey;
    import xjava.security.KeyGenerator;
    import xjava.security.SecretKey;
    public class testcipher extends javax.swing.JFrame{
        /** Creates new test */
        public testcipher() throws Exception {
        * @param args the command line arguments
        public static void main(String [] args) throws Exception  {
            Provider pd = new cryptix.provider.Cryptix();
            Security.addProvider(pd);
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "Cryptix");
            kpg.initialize(1024, new java.security.SecureRandom());
            System.out.println("Generating key pair...");
            KeyPair kp = kpg.genKeyPair();
            System.out.println("Key pair generated...");
            xjava.security.Cipher cp = xjava.security.Cipher.getInstance("RSA/ECB/PKCS7", "Cryptix");
            cp.initEncrypt(kp.getPublic());
            FileInputStream fis = new FileInputStream("c:\\temp\\b2b\\index.htm");
            CipherInputStream cin = new CipherInputStream(fis, cp);
            FileOutputStream fout = new FileOutputStream("C:\\temp\\b2b\\enc.htm");
            CipherOutputStream cout = new CipherOutputStream(fout, cp);
            byte[] buffer = new byte[8192];
            int length;
            while((length=cin.read(buffer))!=-1)
                cout.write(buffer, 0, length);
            cout.close();
            cin.close();
            fout.close();
            fis.close();
            cp.initDecrypt(kp.getPrivate());
            fis = new FileInputStream("c:\\temp\\b2b\\enc.htm");
             cin = new CipherInputStream(fis, cp);
             fout = new FileOutputStream("C:\\temp\\b2b\\dec.htm");
             cout = new CipherOutputStream(fout, cp);
                    while((length=cin.read(buffer))!=-1)
                cout.write(buffer, 0, length);
            cout.close();
            cin.close();
            fout.close();
            fis.close();
    }

  • No luck with RSA and existing cert

    I want to encrypt data in my software, data which will be sent to me by the user, in such a way that only I can decrypt it. This seems to call for asymmetric encryption (only the public key would be embedded in the software), so I am trying to use RSA.
    Specifically I am trying to encrypt and decrypt data using the key pairs found in a cert that we bought from a cert authority. The cert says that key is a "Sun RSA public key, 1024 bits". In the following test, I encrypt using the cert's public key and decrypt using the same, for want of a method to return the private key but the results are the same if I initialize the cipher for decryption with the cert itself (which presumably contains the private key).
            Key key = cert.getPublicKey();
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] enc = cipher.doFinal(test.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] dec = cipher.doFinal(enc);but at the decyrption stage I get the following error:
    Exception in thread "main" javax.crypto.BadPaddingException: Data must start with zero.which I don't know what to make of. It seems to me that I am following the (rather scant) instructions to the letter. If I specify "RSA/ECB/NoPadding" as the transformation I don't get the above error but the roundtrip fails to recreate the original string.
    Furthermore, as I said before, I wanted to use public key encryption because I must include the encryption key in the software and I do not want it to be sufficient to decrypt the cipher. I was hoping that with RSA you'd encrypt using the public key but that you'd need either the secret key or the whole cert to decrypt. However the Javadocs do not say so explicitely and I am left unsure as to how this works exactly. Can anyone shed some light?

    I agree, the documentation is inadequate. Have you also looked at the JCE reference (http://java.sun.com/j2se/1.5.0/docs/guide/security/jce/JCERefGuide.html)? This expands a lot on the javadocs for the classes. It might also help to learn more about cryptography; one book that others recommend is "Practical Cryptography" by Ferguson and Schneier.
    I think the one key misunderstanding you have is what is in a certificate. A certificate contains only the public key, some information about the identity of the owner of the private key, and a digital signature over this public key and identifying information. The private key is not in the certificate! Nor should it be. If it were, it would no longer be private and the security of the system would fall apart.
    The location of the private key depends entirely on the application that created the key pair. java's keytool, for example, stores the private key in a password protected file.
    The error you are seeing makes sense once you understand that , for an RSA cipher, the type of key, public or private, as well as the mode Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE, determine the interpretation of the subsequent update or doFinal method calls.
    Thus in your example, your first call to cipher.doFinal gives the RSA encryption of the data, which is what you wanted. Your second, however, attempts to decrypt this encrypted data with the public key, which makes no sense in this context. It checks to see if the result is has the proper padding, which it does not. If you tell it to assume no padding, you won't get an exception but the result still won't make any sense. You need to init the cipher with the private key for the second part.

  • 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

  • Can a cipher use any type of key?

    I was wondering if it is possible to load a symmetric key from a keystore and use it in a cipher.
    Do ciphers only accept symmetric keys??
    I know that the jks keystore only supports asymmetric keys.
    Is there a Bouncy Castle keystore that stores symmetric keys?
    If so is there a tool that one can use to generate symmetric keys that can be placed in such a keystore (similar to keytool)?
    Any help on this would be greatly appreciated.
    Thank you,
    Blake

    KeyStores can not store symmetric keys otherwise known as Secret Keys. They can only store asymmetric keys. And there are no providers out there that can really change that as the public API for KeyStore provides no means by which to implement one.
    As for ciphers. There are two types of ciphers. The first is symmetric such as DES, Blowfish, AES, DESede, etc... These ciphers use the same key to init for both encrypt and decrypt (aka the secret key). But there are also asymmetric ciphers of which RSA is by far the most common. In asymmetric ciphers you init the cipher with the public key for encryption and the private key for decryption.
    You will have to have a third party provider to use RSA as a cipher as Sun's JCE does not provide an RSA cipher impl. RSA also supports signatures which sun does support.

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

  • Problem while encoding byte[] with RSA

    Hi all,
    I am trying to encode a byte array using RSA encoding. I use the following code (It tries to encode a byte array, "data", with the public key, "publicKey"):
    byte[] encryptData  = new byte[data.length];
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    ByteArrayInputStream inStream = new ByteArrayInputStream(data);
    CipherInputStream cipherStream = new CipherInputStream(inStream, cipher);
    cipherStream.read(encryptData);And all I get is a empty array: encryptData is full of zero!
    Does anyone have an idea about what I did wrong ?
    Thanks in advance

    ok...
    Indeed, my data length is far more than my key length. So you tell me that I should cut my data to have some chunks of smalled size (key length max), and use directly something Cipher ?
    EDIT: Oh, I just got it. I should cut the data into bits of KEY_SIZE minus 11 (for the minimum padding). I'm going to test that.
    EDIT 2: Ok, that's fine, you were right. My error was to use CipherInputStream on data which length was more than key size minus padding. Thank you very much for your answer.
    Edited by: Reeter on Mar 29, 2009 1:10 PM
    Edited by: Reeter on Mar 29, 2009 1:35 PM

  • Encrypting with an RSA Public Key

    Hi everyone. I'm trying to encrypt some characters with an already generated RSA public key. Can anybody help with a SUN provider sample script?
    Thanx

    First of all RSA cipher is not suitable for encription of data more then one block (about 80 bytes for the OAEP mode), so it is paractically only good for the secret key wrapping (like Blowfish or DES) and second thing is that SUN JCE provider doesn't include RSA cipher implementation.

  • Cipher vs signature algorithm?

    Hello,
    What is the difference between a chipher and a signature algorithm? How can SunJSSE provider have an implementation of SHA1withRSA signature algorithm but not have an implementation of RSA cipher? Don't you need to have the cipher to do the signature?
    Thanks for any insights.

    Hi!
    I'd like to get the same result when I use the Cipher class or when I use the Signature class.
    If I use the code below I get different results. Am I doing something wrong? How can I get the same result using these two classes?
    Thank you.
    //Encryption by the Cipher Class
    byte input[]="hello".getBytes();
    MessageDigest md = MessageDigest.getInstance("SHA1");
    md.update(input);
    byte digest[] = md.digest();
    Cipher rsaCipher = Cipher.getInstance("RSA");
    rsaCipher.init(Cipher.ENCRYPT_MODE, privateKey);
    byte[] encryptedData = rsaCipher.doFinal(digest);
    System.out.println("textEncrypted="+Base64Utils.base64Encode(encryptedData));
    //Encryption by the Signature Class
    Signature signatureAlgorithm = Signature.getInstance("SHA1withRSA");
    signatureAlgorithm.initSign(privateKey);
    signatureAlgorithm.update(input);
    encryptedData = signatureAlgorithm.sign();
    System.out.println("textEncrypted2="+Base64Utils.base64Encode(encryptedData));

  • How do I install this self-signed SSL certificate?

    I haven't been able to connect to the jabber server I've been using (phcn.de) for quite some time now, so I filed a bug report with mcabber. The friendly people there told me to install phcn.de's self-signed certificate, but I can't figure out for the life of me how to do that.
    I know I can download something resembling a certificate using
    $ gnutls-cli --print-cert -p 5223 phcn.de
    Which does give me something to work with:
    Resolving 'phcn.de'...
    Connecting to '88.198.14.54:5223'...
    - Ephemeral Diffie-Hellman parameters
    - Using prime: 768 bits
    - Secret key: 767 bits
    - Peer's public key: 767 bits
    - PKCS#3 format:
    -----BEGIN DH PARAMETERS-----
    MIHFAmEA6eZCWZ01XzfJf/01ZxILjiXJzUPpJ7OpZw++xdiQFBki0sOzrSSACTeZ
    hp0ehGqrSfqwrSbSzmoiIZ1HC859d31KIfvpwnC1f2BwAvPO+Dk2lM9F7jaIwRqM
    VqsSej2vAmAwRwrVoAX7FM4tnc2H44vH0bHF+suuy+lfGQqnox0jxNu8vgYXRURA
    GlssAgll2MK9IXHTZoRFdx90ughNICnYPBwVhUfzqfGicVviPVGuTT5aH2pwZPMW
    kzo0bT9SklI=
    -----END DH PARAMETERS-----
    - Certificate type: X.509
    - Got a certificate list of 1 certificates.
    - Certificate[0] info:
    - subject `CN=phcn.de', issuer `CN=phcn.de', RSA key 1024 bits, signed using RSA-SHA, activated `2009-05-04 08:26:21 UTC', expires `2014-04-08 08:26:21 UTC', SHA-1 fingerprint `d01bf1980777823ee7db14f8eac1c353dedb8fb7'
    -----BEGIN CERTIFICATE-----
    MIIBxzCCATCgAwIBAgIINN98WCZuMLswDQYJKoZIhvcNAQEFBQAwEjEQMA4GA1UE
    AwwHcGhjbi5kZTAeFw0wOTA1MDQwODI2MjFaFw0xNDA0MDgwODI2MjFaMBIxEDAO
    BgNVBAMMB3BoY24uZGUwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALqS+tnB
    tNruBGdcjw0o+BWSdfkKH4T3VpS7bkrsS0q7RD5iUIao7jH2lJqTk1TrLbQe28+R
    H0X9Ya+w22iYFea2l3wkrTnBfgdSZbRhpSxgVvC2QEBMoSrEQoRpo5lzXadRlob/
    RQ+rhu/cWCNeiRJzfkmNirPVEciGKQHrwKxxAgMBAAGjJjAkMCIGA1UdEQQbMBmg
    FwYIKwYBBQUHCAWgCwwJKi5waGNuLmRlMA0GCSqGSIb3DQEBBQUAA4GBALFBalfI
    oESZY+UyVwOilQIF8mmYhGSFtreEcUsIQvG1+cgD16glKehx+OcWvJNwf8P6cFvH
    7yiq/fhMVsjnxrfW5Hwagth04/IsuOtIQQZ1B2hnzNezlnntyvaXBMecTIkU7hgl
    zYK97m28p07SrLX5r2A2ODfmYGbp4RD0XkAC
    -----END CERTIFICATE-----
    - The hostname in the certificate matches 'phcn.de'.
    - Peer's certificate issuer is unknown
    - Peer's certificate is NOT trusted
    - Version: TLS1.0
    - Key Exchange: DHE-RSA
    - Cipher: AES-128-CBC
    - MAC: SHA1
    - Compression: NULL
    - Handshake was completed
    - Simple Client Mode:
    Unfortunately, the above command spits out more than a certificate. Do I need the additional information? If so, what do I need it for? Where do I need to put the certificate file?

    Hi,
    I recently found out a way how to install test or self-signed certificates and use it with S1SE.
    See:
    http://www.gtlib.cc.gatech.edu/pub/linux/docs/HOWTO/other-formats/html_single/SSL-Certificates-HOWTO.html
    Follow the instructions there
    1. Create CA
    2. Create root ca certificate
    Now install the root-ca-certificate in S1SE -> Security>Certificate Management and Install a "Trusted Certificate Authority".
    Paste the contents of the file: cacert.pem into the message-text box.
    Then restart the server. Now your CA-Cert should be visible in the Manage Certificates menu.
    The next step is to send a certificate-request from S1SE to your e-mail-address.
    The contents of the e-mail the server sends to you (certificate request) must be pasted into the file: newreq.pem.
    Now just sign the Request:
    CA.pl -sign
    The last step is that you have to paste the contents of the file newcert.pem into the message-box of the Security>Certificate Management - now under the option Certificate for "This Server".
    Then you have to reboot the server/instance again and it should work with your certificate.
    Regards,
    Dominic

  • Install BPEL PM on WebLogic Server 9.2 & AIX 6.1

    We are running into a BPEL PM issue while installing SOA Suite on WLS 9.2 and AIX 6.1. During server startup the BPEL application fails with the following error message:
    ####<May 28, 2009 12:33:47 PM CDT> <Error> <Deployer> <nsiprdsoa2> <SOAServer2> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1243532027915> <BEA-149231> <Unable to set the activation state to true for the application 'BPELPM'.
    weblogic.application.ModuleException: [HTTP:101216]Servlet: "BPEL_Axis_Servlet" failed to preload on startup in Web application: "/orabpel".
    ORABPEL-00006
    Cipher creation error.
    Failed to load the JCE cipher "DESede/ECB/PKCS5Padding". Your environment may not be set correctly.
    You must have the JCE library files installed in your JRE installation as an extension. Copy the jar files from "/opt/apps/oracle/product/bpel/oracle10g/bpel\install\java\jce1.2.2" to the "(jdk_path)\jre\lib\ext" directory (where jdk_path is your jdk installation directory).
    classpath: /usr/java5/lib/tools.jar:/usr/java5/jre/lib/ext/ibmjceprovider.jar:/usr/java5/jre/lib:/usr/java5/jre/ext/lib:/opt/apps/bea/weblogic92/server/lib/weblogic.jar:/opt/apps/bea/weblogic92/server/lib/webservices.jar:/opt/apps/oracle/product/bpel/oracle10g/bpel/domains/default/tmp/.generated:/opt/apps/oracle/product/bpel/oracle10g/bpel/system/classes:/opt/apps/oracle/product/bpel/oracle10g/bpel/system/services/config:/opt/apps/oracle/product/bpel/oracle10g/bpel/system/services/schema:/opt/apps/oracle/product/bpel/oracle10g/integration/esb/config:/opt/apps/oracle/product/bpel/oracle10g/integration/esb/system/classes:/opt/apps/oracle/product/bpel/oracle10g/owsm/lib/custom:/opt/apps/oracle/product/bpel/oracle10g/SOASUITE10134.jar:/opt/apps/bea/CCI/apps/soaApps/ADAPTERS.jar
         at com.collaxa.cube.util.DESService.decrypt(DESService.java:66)
         at com.collaxa.cube.util.CXPasswordUtils.decrypt(CXPasswordUtils.java:50)
         at com.collaxa.cube.ws.soap.axis.BPELAxisServlet.init(BPELAxisServlet.java:50)
         at weblogic.servlet.internal.StubSecurityHelper$ServletInitAction.run(StubSecurityHelper.java:278)
         at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
         at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
         at weblogic.servlet.internal.StubSecurityHelper.createServlet(StubSecurityHelper.java:64)
         at weblogic.servlet.internal.StubLifecycleHelper.createOneInstance(StubLifecycleHelper.java:58)
         at weblogic.servlet.internal.StubLifecycleHelper.<init>(StubLifecycleHelper.java:48)
         at weblogic.servlet.internal.ServletStubImpl.prepareServlet(ServletStubImpl.java:507)
         at weblogic.servlet.internal.WebAppServletContext.preloadServlet(WebAppServletContext.java:1723)
         at weblogic.servlet.internal.WebAppServletContext.loadServletsOnStartup(WebAppServletContext.java:1700)
         at weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1620)
         at weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:2761)
         at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:889)
         at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:333)
         at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:204)
         at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:26)
         at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:60)
         at weblogic.application.internal.flow.ScopedModuleDriver.start(ScopedModuleDriver.java:200)
         at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:117)
         at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:204)
         at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:26)
         at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:60)
         at weblogic.application.internal.flow.StartModulesFlow.activate(StartModulesFlow.java:26)
         at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:635)
         at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:26)
         at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:212)
         at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:154)
         at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:80)
         at weblogic.deploy.internal.targetserver.BasicDeployment.activate(BasicDeployment.java:181)
         at weblogic.deploy.internal.targetserver.BasicDeployment.activateFromServerLifecycle(BasicDeployment.java:358)
         at weblogic.management.deploy.internal.DeploymentAdapter$1.doActivate(DeploymentAdapter.java:52)
         at weblogic.management.deploy.internal.DeploymentAdapter.activate(DeploymentAdapter.java:186)
         at weblogic.management.deploy.internal.AppTransition$2.transitionApp(AppTransition.java:30)
         at weblogic.management.deploy.internal.ConfiguredDeployments.transitionApps(ConfiguredDeployments.java:233)
         at weblogic.management.deploy.internal.ConfiguredDeployments.activate(ConfiguredDeployments.java:169)
         at weblogic.management.deploy.internal.ConfiguredDeployments.deploy(ConfiguredDeployments.java:123)
         at weblogic.management.deploy.internal.DeploymentServerService.resume(DeploymentServerService.java:173)
         at weblogic.management.deploy.internal.DeploymentServerService.start(DeploymentServerService.java:89)
         at weblogic.t3.srvr.SubsystemRequest.run(SubsystemRequest.java:64)
         at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
         at weblogic.work.ExecuteThread.run(ExecuteThread.java:181)
         at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:891)
         at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:333)
         at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:204)
         at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:26)
         at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:60)
         at weblogic.application.internal.flow.ScopedModuleDriver.start(ScopedModuleDriver.java:200)
         at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:117)
         at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:204)
         at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:26)
         at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:60)
         at weblogic.application.internal.flow.StartModulesFlow.activate(StartModulesFlow.java:26)
         at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:635)
         at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:26)
         at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:212)
         at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:154)
         at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:80)
         at weblogic.deploy.internal.targetserver.BasicDeployment.activate(BasicDeployment.java:181)
         at weblogic.deploy.internal.targetserver.BasicDeployment.activateFromServerLifecycle(BasicDeployment.java:358)
         at weblogic.management.deploy.internal.DeploymentAdapter$1.doActivate(DeploymentAdapter.java:52)
         at weblogic.management.deploy.internal.DeploymentAdapter.activate(DeploymentAdapter.java:186)
         at weblogic.management.deploy.internal.AppTransition$2.transitionApp(AppTransition.java:30)
         at weblogic.management.deploy.internal.ConfiguredDeployments.transitionApps(ConfiguredDeployments.java:233)
         at weblogic.management.deploy.internal.ConfiguredDeployments.activate(ConfiguredDeployments.java:169)
         at weblogic.management.deploy.internal.ConfiguredDeployments.deploy(ConfiguredDeployments.java:123)
         at weblogic.management.deploy.internal.DeploymentServerService.resume(DeploymentServerService.java:173)
         at weblogic.management.deploy.internal.DeploymentServerService.start(DeploymentServerService.java:89)
         at weblogic.t3.srvr.SubsystemRequest.run(SubsystemRequest.java:64)
         at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
         at weblogic.work.ExecuteThread.run(ExecuteThread.java:181)
    ORABPEL-00006
    As you can see we have ibmjceprovider.jar in the class path but it appears we are missing some other jar. Any ideas would be appreciated.

    Hi
    You must have the JCE library files installed in your JRE installation as an extension. Copy the jar files from \"{1}\\install\\java\\jce1.2.2\" to the \"(jdk_path) \\jre\\lib\\ext\" directory (where jdk_path is your jdk installation directory).
    Add the following jars to external directory as well as the bpelc classpath :
    sunjce_provider.jar
    local_policy.jar
    US_export_policy.jar
    The jars mentioned above come with jce1_2_2.jar.
    Regards
    Anirudh Pucha

  • Problem in decrypting the code

    I have written the following code for decryption
    String inputString = "5B5E0A35FBD295AB923D872BC1CBCF45307FACDA881978ACBE65C21FDF63658F61B48EE3C99BBDB0E51B9F1498289305526D82EA2D52D681993E3AD499F2887E82D35CC9CD9EF436B8A9E587CC3E2A50CABFAB39824632F7ECDCDFAE7AC0A7BEAD0767D83D3E3E0BFAAA3F053E5678901ABCDE1B8581310F6513D0547290F6C9E";
    String inputKey = "243fbde01df0684ed5b49f1035137225fcca9ba960e5e979e9cb8bee345f2f258678901acbd05c4f084c0373d3300432b186e03c56bd93bacb4ba634ad2b407b18f2985497eaa1e635152d7e9814ee469a94115109841758f67e61885d412dcc47efd670e156700e6df84dcadd41bc0588a8b4babcde54387d742e96308d66a1";
    String labelString = "0000000819";
    byte [] input = hexstringToByteArray(inputString);
    byte[] keyBytes = hexstringToByteArray(inputKey);
    byte[] label = padWithZeros(hexstringToByteArray(labelString));
    Security.addProvider(new BouncyCastleProvider());
    BigInteger privateKeyInt = new BigInteger(keyBytes);
    Cipher bcCipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");
    OAEPParameterSpec defaultOaepSpec = OAEPParameterSpec.DEFAULT;
    OAEPParameterSpec oaepSpec = new OAEPParameterSpec(defaultOaepSpec.getDigestAlgorithm(),
    defaultOaepSpec.getMGFAlgorithm(),
    defaultOaepSpec.getMGFParameters(),
    new PSource.PSpecified(label));
    java.security.KeyFactory keyFactory = java.security.KeyFactory.getInstance("RSA", "BC");
    java.security.Key bcPrivateKey = keyFactory.generatePrivate((new RSAPrivateKeySpec(privateKeyInt,new BigInteger("3"))));
    // SecureRandom = new SecureRandom()
    bcCipher.init(Cipher.DECRYPT_MODE, bcPrivateKey,oaepSpec);
    byte[] em = bcCipher.doFinal(input);
    System.out.println(byteArrayToHexString(em));
    Output :-
    Exception in thread "main" java.lang.IllegalArgumentException: unknown parameter type.
         at org.bouncycastle.jce.provider.JCERSACipher.engineInit(JCERSACipher.java:247)
         at javax.crypto.Cipher.init(DashoA13*..)
         at javax.crypto.Cipher.init(DashoA13*..)
         at PublicMain.main(PublicMain.java:44)
    I have to use OEAP padding
    pls help me solve this problem thanks in advance

    I have written this code for decryption and tried the earlier problem by resolving proper jar file
    String inputString = "5B5E0A35FBD295AB923D872BC1CBCF45307FACDA88598153052DC21FDF6365345678AEBCC99BBDB0E51B9F1498289305526D82EA2D52D681993E3AD499F2887E82D35CC9CD9EF436B8A9E587CC3E2A50CABFAB39824632F7ECDCDFAE7AC0A7BEAD0767D83D3E3E0BFAAA3F";
    /* private key*/String inputKey = "243fbde01df0684ed5b49f1035137225fcca9ba960e5e979e9cb8bee345f2f258344795904605c4f084c037456cabefc4186e03c56bd93bacb4ba634ad2b407b18f2985497eaa1e635152d7e9814ee469a94115109841758f67e61885d412dcc47efd670e156700e6df84dcadd41bc0588a8b4b19bb509409d742e96308d66a1";
    String labelString = "40156ca44f22db70b7f852eec9d57ce10000000913"; //Unencrypted header may change
    String publicKey = "9e4004e8ab15bad1ec47059b86a50f5f46334da008fded08b7fe300d1a14a8f926d8abcde13456786282335c03eee04559861043b8a1f7db4ee79f2a17a8aff278dee0ebc997a48668fb99ec6d901b3e5723318bbdc0586f05196b4603b36b2d8eb62b52395684b26d50bb6df19bc8b72bb7eec359a68651842e739e52cbc05027";
    byte [] input = hexstringToByteArray(inputString);
    byte[] keyBytes = hexstringToByteArray(inputKey);
    byte[] publicKeyBytes = hexstringToByteArray(publicKey);
    byte[] label = hexstringToByteArray(labelString);
    System.out.println(input.length);
    Security.addProvider(new BouncyCastleProvider());
    BigInteger privateKeyInt = new BigInteger(keyBytes);
    BigInteger publicKeyInt = new BigInteger(publicKeyBytes);
    Cipher bcCipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", "BC");
    OAEPParameterSpec defaultOaepSpec = OAEPParameterSpec.DEFAULT;
    OAEPParameterSpec oaepSpec = new OAEPParameterSpec(defaultOaepSpec.getDigestAlgorithm(),
    defaultOaepSpec.getMGFAlgorithm(),
    defaultOaepSpec.getMGFParameters(),
    new PSource.PSpecified(label));
    java.security.KeyFactory keyFactory = java.security.KeyFactory.getInstance("RSA", "BC");
    java.security.Key bcPrivateKey = keyFactory.generatePrivate((new RSAPrivateKeySpec(publicKeyInt,privateKeyInt)));
    // SecureRandom = new SecureRandom()
    /* PrivateKey p = keyFactory.generatePrivate((new RSAPrivateKeySpec(publicKeyInt,privateKeyInt)));
    System.out.println(p.toString());*/
    bcCipher.init(Cipher.DECRYPT_MODE, bcPrivateKey,oaepSpec);
    /*RSAEngine rsa = new RSAEngine();
    OAEPEncoding a = new OAEPEncoding(rsa,new SHA1Digest(),label);
    rsa.init(false, (CipherParameters) p);
    byte[] output = a.decodeBlock(input, 0, input.length); */
    byte[] em = bcCipher.doFinal(input);
    System.out.println(byteArrayToHexString(em));
    But now it is giving the following exception :
    Exception in thread "main" org.bouncycastle.crypto.DataLengthException: input too large for RSA cipher.
         at org.bouncycastle.crypto.engines.RSACoreEngine.convertInput(Unknown Source)
         at org.bouncycastle.crypto.engines.RSABlindedEngine.processBlock(Unknown Source)
         at org.bouncycastle.crypto.encodings.OAEPEncoding.decodeBlock(Unknown Source)
         at org.bouncycastle.crypto.encodings.OAEPEncoding.processBlock(Unknown Source)
         at org.bouncycastle.jce.provider.JCERSACipher.engineDoFinal(Unknown Source)
         at javax.crypto.Cipher.doFinal(DashoA13*..)
         at PublicMain.main(PublicMain.java:55)
    Please help me correcting the input length
    Thanks in advance

  • New bug in IIS/SSL code ?

    Hello Team,
    Windows 2012 R2 Datacenter with all patches. IIS with SSL and SCEP (NDES) service.
    Problem occurs only when client is proposing SSL RSA cipher suite. For DH cipher suite everything is working fine.
    The SCEP communication from my router to IIS/SSL:
    - Client Hello with RSA cipher 
    - Server Hello with RSA cipher + Certificate
    - client sending Client Key Exchange + received ACK from server
    - client sending Change Cipher spec and..
    - server sends RST
    Screenshot from SSL session:
    http://tinypic.com/r/m93976/8
    The problem is not SCEP related. It can be recreated by any web browser accessing IIS via HTTPS. That web browser should have RSA cipher suite disabled (in firefox about:config/ssl). I have tested from locally installed firefox to exclude any interference
    on the network.
    Is this any well known bug ? (i can not find any). Please advise.
    Regards,
    Michal Garcarz

    I agree that it is weird - but I would still be interested in using another crypto provider at the server ... not just another certificate, but one associated with a key using a different CSP.
    If you say you use the 'default' one - which one is it? It depends on the certificate template or settings you made when creating the key.
    I suppose it is either the Software Key Storage provider (CNG) or the classical RSA SChannel CSP (Visible e.g. in the output of
    certutil -v -store run at the server). If all of your server certificates use one of these I'd try to test one more certificate that uses the other one - and if it is just to rule out an impact of the crypto provider.
    Elke

Maybe you are looking for