BouncyCastle in Java

Hi,
I developing a project which involve cryptography provided by BouncyCastle. May anyone provides me an example of doing AES symmetric cipher by using the APIs in BouncyCastle?
Thanks in advance

In "Practical Cryptography", Ferguson & Schneier simply state:
"Do not ever use ECB for anything. It has serious weaknesses, and
is only included here so that we can warn you away from it."
Basically, identical plaintext is encrypted to identical ciphertext.
This site shows you what this looks like with some image files.
http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation
So you should not use it unless you absolutely have to. Use CBC
instead.
With that said, I can imagine you may be forced to interface with
some poorly designed legacy application that used ECB, so you
may have no choice.
In that case, I'll tell you how to use ECB with BouncyCastle.
Its the default mode for their AESEngine. That means, if you
don't pass in the AESEngine wrapped in a moded block cipher,
you'll end up with ECB. For your code above, simply remove
the "new CBCBlockCipher(engine)" and just pass "engine" directly
into the PaddedBufferedBlockCipher.
And fireflying, Im guessing your desire to use ECB might be an
attempt to alleviate the unwanted padding bytes... I understand
situations where using the JCE is not an option. Ive had to write
code for clients who've actually removed the JCE from their
1.4 JDK(believe it or not!). So, to answer your question about
the padding bytes, here's a little method Ive used:
public static byte[] stripPadding(byte[] b) {
        int len = 0;
        for (int i = 0; i < b.length; i++) {
            if (b[i] == 0x00) {
                len = i;
                break;
        byte[] out = new byte[len];
        System.arraycopy(b, 0, out, 0, len);
        return out;
    }

Similar Messages

  • Strange when using BouncyCastle in Java WebStart

    I write a Java Application which can save a PKCS#12 Keystore to a file.
    The application run well in native mode. But when I use it in
    Java WebStart, a strange error jumped out, and I don't know why?
    Here is the Error message:
    java.io.IOException: exception encrypting data - java.security.NoSuchProviderException: JCE cannot authenticate the provider BC
         at org.bouncycastle.jce.provider.JDKPKCS12KeyStore.wrapKey(JDKPKCS12KeyStore.java:564)
         at org.bouncycastle.jce.provider.JDKPKCS12KeyStore.engineStore(JDKPKCS12KeyStore.java:1026)
         at java.security.KeyStore.store(Unknown Source)
         at com.wellsoon.security.frameMain.SaveKeystoreAs(frameMain.java:270)
         at com.wellsoon.security.frameMain.btnSaveKeystore_actionPerformed(frameMain.java:508)
         at com.wellsoon.security.frameMain_btnSaveKeystore_actionAdapter.actionPerformed(frameMain.java:628)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Here is my JNLP file:
    <?xml version="1.0" encoding="UTF-8"?>
    <jnlp spec="1.0+" codebase="http://192.168.1.76:8080/genKeyCSR" href="genKeystore.jnlp">
    <information>
    <title>genKeystore</title>
    <vendor>genKeystore</vendor>
    <homepage href="genKeystore.html" />
    </information>
    <security>
    <all-permissions/>
    </security>
    <resources>
    <j2se version="1.3+" />
    <jar href="genKeystore.jar" />
    <jar href="bcprov-jdk14-120.jar" />
    </resources>
    <application-desc main-class="com.wellsoon.security.genKeystoreApp" />
    </jnlp>
    All the jar packages are signed by my key.
    The JKS Keystore can be saved without any errors.
    Anybody know the true reason?
    Thanks.

    I have done that and the result is unchanged.
    I have registed Security Provider in my code, so I needn't to
    write security.provider.6=org.bouncycastle.***.** in java.security.
    You know, the application can execute well in native mode, the
    error only happened when the app is running from Java Webstart.

  • CryptoAPI & Java RC4 problem

    Hello,
    I have a problem with some cryto code I'm doing in Java and I'm stuck. I need some help.
    Here is my problem, I have an app made in VC++ that uses cryptoapi to cipher some data. Now I have to redo that app in Java, and I have to mantain backwards compatibility. So the code in Java has to produce the same results that the one in C++, and I cannot alter the C++ code.
    Basically this is the code I have in VC++ (6.0)
    //********************VC++ CODE*************************************
      void simpleTest(void) {
          HCRYPTPROV hCryptProv   = 0;
          HCRYPTHASH hHash        = 0;
          HCRYPTKEY  hKey         = 0;
          BYTE*      pBuf         = NULL;
          DWORD      BufLen       = 0;
          DWORD      DataLen      = 0;
          LPCSTR     PasswordToGenKey = "SEED";
          CString    PlainText = "Data to cipher";
          CryptAcquireContext(&hCryptProv, NULL, MS_DEF_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
          //calc hash
          CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, &hHash);
          CryptHashData(hHash, (BYTE*)PasswordToGenKey, strlen(PasswordToGenKey), 0);
          //get the key from that hash
          CryptDeriveKey(hCryptProv, CALG_RC4, hHash, CRYPT_EXPORTABLE, &hKey);
          BufLen  = PlainText.GetLength();
          DataLen = BufLen;
          pBuf = new BYTE[BufLen];
          memcpy(pBuf, PlainText,BufLen);
          //cipher
          CryptEncrypt(hKey, 0, TRUE, 0, pBuf, &DataLen, BufLen);
    //******************************************************************Here are some hex dumps that I get with this code:
    Plain Text -> [44 61 74 61 20 74 6f 20 63 69 70 68 65 72]
    PasswordToGenKey -> [53 45 45 44]
    Hash of PasswordToGenKey -> [ac e0 1e e4 3f da 36 bd 62 ef c1 20 35 e6 93 f6]
    Key Blob -> [08 02 00 00 01 68 00 00 05 00 00 00 ac e0 1e e4 3f]
    Type -> [08] (PLAINTEXTKEYBLOB)
    Version -> [02]
    KeyAlg -> [6801] (CALG_RC4)
    KeyTam -> [05]
    Key -> [ac e0 1e e4 3f]
    Result of cipher -> [2e 6a 87 61 b0 a5 ae b4 86 79 91 fa 86 25]
    And this is the Java code, I'm using the 1.4.2_04 JDK with the BouncyCastle provider:
    //**********************JAVA CODE**********************************
      try {
          String PassToGenKey = "SEED";
          String dataPlain = "Data to cipher";
          byte buf[] = PassToGenKey.getBytes();
          byte bufPlain[] = dataPlain.getBytes();
          //calc hash
          MessageDigest md = MessageDigest.getInstance("MD5", "BC");
          md.update(buf);
          byte hash[] = md.digest();
          //get the key from that hash, just the first 5 bytes (40 bits)
          KeyParameter keyParambc = new KeyParameter(hash, 0, 5);
          RC4Engine rc4Engine = new RC4Engine();
          rc4Engine.init(true, keyParambc);
          //cipher
          byte bufCipher[] = new byte[bufPlain.length];
          rc4Engine.processBytes(bufPlain, 0, bufPlain.length, bufCipher, 0);
          rc4Engine.reset();
      } catch(Exception e) {}
    //******************************************************************Here are the hex dumps from this code:
    Plain Hex -> [44 61 74 61 20 74 6f 20 63 69 70 68 65 72]
    PasswordToGenKey -> [53 45 45 44]
    Hash of PasswordToGenKey -> [ac e0 1e e4 3f da 36 bd 62 ef c1 20 35 e6 93 f6]
    Key -> [ac e0 1e e4 3f]
    Result of the cipher -> [b6 31 a2 26 a8 30 62 76 0a 89 b2 71 97 3f]
    As you can see only the results are different, but I cannot find why... :-?
    Thanks in advance for any help!!

    I've found it. Thanks to a good fellow in the BouncyCastle mailing list..
    Although CriptoApi is reporting that it uses a 5 byte key, it is using
    a 128 bit key, with the first 5 bytes the ones from the hash and the
    rest zeros.
    Javi

  • Unable to locate unrestricted policy files for the Sun JCE for download

    My platform:
    java version "1.6.0_26"
    Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
    Oracle JRockit(R) (build R28.1.4-7-144370-1.6.0_26-20110617-2130-windows-x86_64, compiled mode)
    I am unable to locate the Unlimited Strength Jurisdiction JCE files.
    According to BouncyCastle for Java 1.6:
    ..."you must download the unrestricted policy files for the Sun JCE if you want the provider to work properly. The policy files can be found at the same place as the JDK download. Further information on this can be found in the Sun documentation on the JCE."

    The version at the very bottom of http://www.oracle.com/technetwork/java/javase/downloads/index.html should work.

  • Providers load order conflict (ExceptionInInitializerError)

    Hello, I have a problem when using several java.security.Provider (BouncyCastleProvider and SunJCE), by the sight, the order in which they are loaded is the problem.
    If load BouncyCastleProvider at position 1, and SunJCE in the 2, (following code) is throwed java.lang.ExceptionInInitializerError
    java.security.Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 1);
    java.security.Security.insertProviderAt(new com.sun.crypto.provider.SunJCE(), 2);
    SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMDAndDES"); // throws ExceptionInInitializerErrorIf the position are another (SunJCE at 1, and BouncyCastle 2)
    java.security.Security.insertProviderAt(new com.sun.crypto.provider.SunJCE(), 1);
    java.security.Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 2);
    SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMDAndDES"); // it works well!yes works well (need that BouncyCastle exist at position 1), but I have problems soon, with my jar library that uses BouncyCastleProvider (which I cannot modify).
    I have tried to do the following:
    java.security.Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 1);
    java.security.Security.insertProviderAt(new com.sun.crypto.provider.SunJCE(), 2);
    Provider sunJCEProv = java.security.Security.getProvider("SunJCE");
    SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMDAndDES", sunJCEProv); // does not work either (ExceptionInInitializerError)here I am indicating him the Provider (SunJCE), but seems to take in any case bouncycastle (the Provider in the position 1).
    The full stackTrace of the exception is:
    java.lang.ExceptionInInitializerError
         AT javax.crypto.SecretKeyFactory.getInstance(DashoA12275)
    Caused by: java.lang.SecurityException:
         Cannot for Seth up certs trusted CAs AT javax.crypto.SunJCE_b. (DashoA12275)
    ... 25 and more
    Caused: java.security.PrivilegedActionException: java.security.InvalidKeyException: Public for key           presented not                certificate signature AT java.security.AccessController.doPrivileged(Native Method)
         ... 26 and more
    Caused by: java.security.InvalidKeyException: Public for key presented not certificate signature
         AT org.bouncycastle.jce.provider.X509CertificateObject.checkSignature(Unknown Source)
         AT org.bouncycastle.jce.provider.X509CertificateObject.verify(Unknown Source)
         AT javax.crypto.SunJCE_b.c(DashoA12275)
         AT javax.crypto.SunJCE_b.b(DashoA12275)
         AT javax.crypto.SunJCE_q.run(DashoA12275)Some idea?
    Thanks to all!

    First off, Im assuming the algorithm you're dealing with is actually
    PBEWithMD5AndDES (not MD without the 5).
    With that, Ive done some experiments and it seems to be dependent on
    where in the java.security file you have the BC provider.
    $JAVA_HOME/jre/lib/security/java.security
    If my java.security settings look like this (other providers omitted from post)
    all 3 of your tests work:
    security.provider.1=sun.security.provider.Sun
    security.provider.2=org.bouncycastle.jce.provider.BouncyCastleProvider
    However, if its reversed like this none work.
    security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider
    security.provider.2=sun.security.provider.Sun
    I thought the insertProviderAt() call worked independently of the java.security
    settings and would override them. In this case it seems like something
    else is going on...
    So try making BouncyCastleProvider #2 behind Sun in your java.security file and see what happens.

  • Javax.crypto.BadPaddingException in DES encrypt/decrypt algorithm

    I am using DES algorithm, the default provided by J2ME to encrypt and decrypt some text. My problem is that I can encrypt the text but when I decrypt I get javax.crypto.BadPaddingException. I used a sample code from this forum I suppose and modified it to some extend.
    Here's the output -
    Plain Text :debayandas
    Cipher Text :Ɩ2&#65533;Ü°*Yð´4}&#65533;f¥
    Recovered Plain Text :javax.crypto.BadPaddingExceptionAnd here's the J2ME code -
    Declaration part:
    private boolean midletPaused = false;
            private static String algorithm = "DES";
         private static byte[] secretKey = {(byte) 0x2b, (byte) 0x7e, (byte) 0x15, (byte) 0x16,
                                                      (byte) 0x28, (byte) 0xae, (byte) 0xd2, (byte) 0xa6 };
         private static String secretKeyAlgorithm = "DES";
         private static byte[] iv = "DES".getBytes();
         private static byte[] plainText = null;
         private Key key = null;
         private static Cipher cipher = null;
         private static int ciphertextLength = 512;
            private static byte[] cipherText = new byte[ciphertextLength];
            private static int decryptedtextLength = 1024;
            private static byte[] decryptedText = new byte[decryptedtextLength];commandAction:
    public void commandAction(Command command, Displayable displayable) {                                              
            if (displayable == form) {                                          
                if (command == exitCommand) {                                        
                    exitMIDlet();                                          
                } else if (command == okCommand) {
                    plainText=textField.getString().getBytes();
                    encrypt();
                    decrypt();                                                        
        } Encrypt:
    public void encrypt()
                try
                    key = new SecretKeySpec(secretKey,0,secretKey.length,secretKeyAlgorithm);
              cipher = Cipher.getInstance(algorithm);
                    cipher.init(Cipher.ENCRYPT_MODE, key);
                    cipher.doFinal(plainText, 0, plainText.length, cipherText, 0);
              System.out.println("Plain Text :"+new String(plainText));
              System.out.println("Cipher Text :"+new String(cipherText));
                catch(Exception e)
                    System.out.println(""+e);
        }Decrypt:
    public void decrypt()
            try
    //            cipher = Cipher.getInstance(algorithm);
                cipher.init(Cipher.DECRYPT_MODE,key);
                cipher.doFinal(cipherText,0,cipherText.length,decryptedText,0);
                System.out.println("Recovered Plain Text :"+new String(decryptedText));
            catch(Exception e)
                System.out.println(""+e);
        }Where am I going wrong?

    debayandas wrote:
    I am using DES algorithm, the default provided by J2ME to encrypt and decrypt some text. My problem is that I can encrypt the text but when I decrypt I get javax.crypto.BadPaddingException. I used a sample code from this forum I suppose and modified it to some extend.How did you get DES in J2ME?
    I am asking as there isn't one default implementation in J2ME and as far as I am aware it is not included in any Configurations or Profiles of J2ME.
    You might be using [Bouncycastle library|http://www.bouncycastle.org/java.html] or any other third party implementation of DES, in which case please refer to the documentation of it to see in which methods throw BadPaddingException and in what circumstances, in order to pinpoint the problem.
    Daniel

  • Interpreting SubjectAlternativeNames

    Hi,
    I have the following code and i am trying to obtain the name field stored in the Subject Alternative Name with oid "1.3.6.1.4.1.5734.1.1" in a X509Certificate object.
    // <X509Certificate object> obtained from a CMS message created with the BouncyCastle API.
    java.security.cert.X509Certificate cert =<X509Certificate object>
    Collection altNames = cert.getSubjectAlternativeNames();
    for (Iterator ani = altNames.iterator(); ani.hasNext();)
    logger.info(ani.next().toString());
    This is the output: (only one element of directoryName type)
    [4, 1.3.6.1.4.1.5734.1.1=#13087573756172696f31,1.3.6.1.4.1.5734.1.2=#13086170653175737531,1.3.6.1.4.1.5734.1.3=#13086170653275737561,1.3.6.1.4.1.5734.1.4=#1309303030303030303161]
    I am not able to obtain a GeneralName or X509Name object that let me read this content. Does anybody know how to interpret this collection getting each oid value separately?.
    Thanks all.

    BouncyCastle appears not to implement the getSubjectAlternativeNames function, so it is implemented by the Sun package (the function is not abstract, as mentioned in the Javadoc below).
    So the directoryname is returned as a RFC2253 string, but in a way that is difficult to use. For instance, the value you need is printed in hexadecimal, instead of translated into a String (I don't know why, because the value is a PrintableString, not an OCTET STRING.)
    1.3.6.1.4.1.5734.1.1=#13 08 75 73 75 61 72 69 6f 31
    Ordinary directoryNames are printed correctly, but not yours. It is a pity.
    Could you try to use the ASN.1 functions from BouncyCastle directly, instead of struggling with the default implementation of Sun? It is a process that requires a lot of work (read the RFC of X.509 and understand some ASN.1 for understanding how to extract the correct values from the directoryName part of the Subject Alternative Names returned by getExtension, for instance), but you will not find undesired surprises.
    By the way, your ASN.1 value was printed by DUMPASN1 as "usuario1". I always guess that the words in Spanish are completely different of Portuguese, but in this case the word for "user" in Portuguese is "usu&aacute;rio" that is not so different of "usuario".
    C>hd test.bin
    0000 13 08 75 73 75 61 72 69 6F 31 ..usuario1
    C>dumpasn1 -a test.bin
    0 13 8: PrintableString 'usuario1'
    The Javadoc.
    public Collection<List<?>> getSubjectAlternativeNames()
    throws CertificateParsingExceptionGets an immutable collection of subject alternative names from the SubjectAltName extension, (OID = 2.5.29.17).
    The ASN.1 definition of the SubjectAltName extension is:
    SubjectAltName ::= GeneralNames
    GeneralNames :: = SEQUENCE SIZE (1..MAX) OF GeneralName
    GeneralName ::= CHOICE {
    otherName [0] OtherName,
    rfc822Name [1] IA5String,
    dNSName [2] IA5String,
    x400Address [3] ORAddress,
    directoryName [4] Name,
    ediPartyName [5] EDIPartyName,
    uniformResourceIdentifier [6] IA5String,
    iPAddress [7] OCTET STRING,
    registeredID [8] OBJECT IDENTIFIER}
    If this certificate does not contain a SubjectAltName extension, null is returned. Otherwise, a Collection is returned with an entry representing each GeneralName included in the extension. Each entry is a List whose first entry is an Integer (the name type, 0-8) and whose second entry is a String or a byte array (the name, in string or ASN.1 DER encoded form, respectively).
    RFC 822, DNS, and URI names are returned as Strings, using the well-established string formats for those types (subject to the restrictions included in RFC 2459). IPv4 address names are returned using dotted quad notation. IPv6 address names are returned in the form "a1:a2:...:a8", where a1-a8 are hexadecimal values representing the eight 16-bit pieces of the address. OID names are returned as Strings represented as a series of nonnegative integers separated by periods. And directory names (distinguished names) are returned in RFC 2253 string format. No standard string format is defined for otherNames, X.400 names, EDI party names, or any other type of names. They are returned as byte arrays containing the ASN.1 DER encoded form of the name.
    Note that the Collection returned may contain more than one name of the same type. Also, note that the returned Collection is immutable and any entries containing byte arrays are cloned to protect against subsequent modifications.
    This method was added to version 1.4 of the Java 2 Platform Standard Edition. In order to maintain backwards compatibility with existing service providers, this method is not abstract and it provides a default implementation. Subclasses should override this method with a correct implementation.
    Returns:
    an immutable Collection of subject alternative names (or null)
    Throws:
    CertificateParsingException - if the extension cannot be decoded
    Since:
    1.4

  • JAVA invocation interface (jar files) BouncyCastle

    Hi!
    I am developing a C++ application which needs the use of BouncyCastle security provider. So I attach to the compilation classpath the jar bouncycastle jar file. Compilation is OK. When i try to trigger mi application jvm crashes. I think that is a problem of JVM path. How should i configure the vm-args.path? The application runs under Linux Ubuntu...
    Thanks in advance...
    Kind Regards

    Hello Mike,
    It customization jar file.
    And customer wants to load this jar file to EBS apache server, so that they can use it to do some development work?
    Now, they wants to know how to load it?
    Thanks,
    Jackie

  • Java Web Start 1.6 fails to start application without Java Consol on Vista

    Hi All,
    I've faced with problem related to starting my application in IE 7 on Vista SP1 using Java Web Start (JRE 1.6.0_12 and 1.6.0_13). I suppose that issue appears after 11th update of JRE 1.6 since it works fine before.
    There were set settings to indicate initial and maximal size of the Java heap in the JNLP file.
    Application consist of 2 JAR files and they are signed with the same certificate.
    When user tried to start application there is no any activity after accepting certificate. After starting application javaw.exe just disappeared from processes list without any message or error.
    When I changed default setting in Java Control Panel to show Java Console, I noticed that the application began to start. But it's not a solution of the issue, since all customers cannot be required to turn on Java console.
    I believe this is a bug in JRE as the application starts with Java console and doesn't without it.
    When I browsed the web looking for the solution or an advice I found Release notes for 1.6.0_014 where it was said that 6u14 Java Web Start failed to launch and notifies that JARs were not signed, if an insecure Java system property was specified in a sandbox JNLP file. In spite of that 14th updated wasn't used and there was no notification I tried to start application without settings for the Java heap and it worked.
    Could someone help me with advice, since the application cannot be started with default heap size settings.
    Thanks in advance.
    Edited by: vovanst on Jul 28, 2009 8:06 AM

    Hi,
    as the 6u15 just arrived and the above mentioned bug should've been fixed (though I was unable to verify through the release notes), the error is still in there.
    We have no timestamped jars, neither ours nor the bouncy castle ones, all certs are valid, ours is self signed.
    6u13 runs, 6u14/6u15 won't.
    I followed the instructions here: http://bouncycastle.org/devmailarchive/msg10415.html to no avail.
    The bcprov.jar is wrapped in its own jnlp and referred as extension from the "main" jnlp.
    The interesting parts of the stack trace are these:
    Caused by (via getCause): java.lang.SecurityException: JCE cannot authenticate the provider BC
         at javax.crypto.Cipher.getInstance(DashoA13*..)
         at javax.crypto.Cipher.getInstance(DashoA13*..)
    Caused by (via getCause): java.util.jar.JarException: Cannot parse https://localhost:8443/deploy/bcprov.jar
         at javax.crypto.SunJCE_c.a(DashoA13*..)
         at javax.crypto.SunJCE_b.b(DashoA13*..)
         at javax.crypto.SunJCE_b.a(DashoA13*..)
         at javax.crypto.Cipher.getInstance(DashoA13*..)
         at javax.crypto.Cipher.getInstance(DashoA13*..)
    For me it seems there's a problem with resolving the url of the bcprov.jar, which would explain the lack of a delay which normally occurs when JCE verifies the signature of the bcprov provider classes. The error pops up almost instantly.
    I'm clueless what to do now. Did Sun really achieve to completely destroy JCE provider functionality in Javaws, forcing us to use an alternative implementation?
    Patric

  • Java C# Encryption compatibility

    Would anyone happen to know or could point me to a place where I can find out the compatibility in the crypto libraries between C#/.NET and the various Java providers including JCE, BouncyCastle and Cryptix. I would need to exchange things like session keys and PBE encrypted messages. Maybe also some MD5 hashes. Now I assume that if I use the same exact algorigthm in theory the byte arrays should be identical, however in practice I'm afraid I'm going to run into issues like different algorithm implementations as well as other things such as byte order differences, String locale differences and maybe even things like Base64 encoding. So I guess what I would really love to read or see would be somekind of a review of compatibility in encrytion and a rough guide for the major issues in sharing encrypted information between Java and C#.
    Thnx for any info.
    -Igor

    I know what you're looking for, and I haven't found it either.
    The closest thing might be this article comparing the crypto
    support in .Net to Java:
    http://www.onjava.com/lpt/a/4415
    If you end up running into compatibility issues, you might want
    to consider using Bouncy Castle's C# crypto port on your .Net
    side: http://www.bouncycastle.org/csharp/index.html
    Using BC on both the Java and C# side could eliminate any weird
    implementation problems with the .Net libraries.
    Be aware that if you go down the pure .Net route, you may end up having
    to use the MS CAPICOM library from C# since it hasnt all been ported over
    yet. Here's an article about how to do it: http://msdn.microsoft.com/security/securecode/dotnet/default.aspx?pull=/library/en-us/dncapi/html/netcryptoapi.asp

  • URGENT: Java stored procedure on oracle 92 database is not working

    Hi,
    I am having an issue regarding java stored procedures. I have created a java class that uses the bouncycastleprovider ( bcprov-jdk13-141.jar ) to encrypt strings. I tested against the version of the java virtual machine that comes bundled with oracle and it works perfectly. I then used JDeveloper to load the class on the database with the resolve, noverify and order flags checked and it shows no errors but when I try to execute the stored procedure it throws the following exception:
    java.lang.ExceptionInInitializerError:
    java.lang.SecurityException: Cannot set up certs for trusted CAs: java.net.MalformedURLException: no protocol: US_export_policy.jar
    at javax.crypto.SunJCE_b.<clinit>(DashoA6275)
    at javax.crypto.Cipher.a(DashoA6275)
    at javax.crypto.Cipher.getInstance(DashoA6275)
    at RijndaelEnhanced.encrypt(RijndaelEnhanced.java:57)
    at RijndaelEnhanced.encrypt(RijndaelEnhanced.java:73)
    I loaded jce1_2_2.jar, sunjce_provider.jar, bcprov-jdk13-141.jar. Also replaced the US_export_policy.jar, local_policy.jar with the unrestrictive version. I add the security provider dinamically with a call to Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 2);
    I also did a select on the user_objects table and all the classes are in VALID status.
    When I run my application using the java virtual machine that is located under C:\Oracle\oracli9i\jdk\jre\bin directory it works fine but when I try to execute on the database it won't work. I found a bug that was if the jce1_2_1.jar file existed in the C:\Oracle\oracli9i\jdk\jre\lib\ext directory ( even if it's extension is renamed ) it won't work because the certification file had expired but I don't know if this has anything to do with this error.
    Am I missing something?
    Please I need an urgent solution to this problem.
    Thanks in advance.
    Bruno Oliveira

    SomeoneElse wrote:
    Waaaaahhhhhhh!I was just thinking the same thing.... ya beat me to it...
    To the OP:
    As an up and coming DB Developer who now works for a small tech firm straight outta college, I can tell you for sure that you will definitely not get anywhere in your impatient life... look behind your back you miserable dude, your job might be in danger since ya got a bad attitude AND you can't figure out an error you are getting from a Java SP. So instead of helping you, I am going to simply tell you how you SHOULD act in a community of practice.
    1. Be nice when looking for help
    2. BE NICE WHEN LOOKING FOR HELP!!!
    Pretty simple right?
    Know what else is really simple? Looking at the topics of each board to make sure ya post in the right board! You people disgust me; somehow getting by in your professional career acting the way you do. I sure hope your "online" persona isn't a reflection of your real attitude towards people, almost pathetic and extremely immature.
    Sorry bout the rant, it is Friday, I know :) Didn't get my coffee this morning. Have a good one all!
    -Tim

  • Java Plug-in 1.4.0 throws an IllegalStateException: zip file closed

    Cross-posting to reach a wider audience:
    Java Plug-in 1.4.0 throws an IllegalStateException: zip file closed
    Author: remyb Jul 23, 2002 6:36 AM
    A IllegalStateException is thrown when the class loader
    try to load a class from my applet JAR file.
    The applet is embedded in a JSP page which use the Plug-In 1.4.0.
    That JSP is hosted by Tomcat 4.0.1.
    The applet JAR file is signed with a self-signed certificate.
    The applet has been compiled with JDK 1.4.0.
    The jar has been put in the Plug-in cache successfully.
    Here is the stack trace I got in the Java Console ...
    java.lang.IllegalStateException: zip file closed
    at java.util.zip.ZipFile.getEntry(Unknown Source)
    at java.util.jar.JarFile.getEntry(Unknown Source)
    at sun.plugin.cache.CachedJarFile.getEntry(Unknown Source)
    at java.util.jar.JarFile.getJarEntry(Unknown Source)
    at sun.misc.URLClassPath$JarLoader.getResource(Unknown Source)
    at sun.misc.URLClassPath.getResource(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at sun.applet.AppletClassLoader.findClass(Unknown Source)
    at sun.plugin.security.PluginClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.applet.AppletClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    Please somebody help me !!
    Thanks !
    Re: Java Plug-in 1.4.0 throws an IllegalStateException: zip file closed
    Author: mutmansky
    In Reply To: Java Plug-in 1.4.0 throws an IllegalStateException: zip file closed Jul 26, 2002 6:36 AM
    Reply 1 of 1
    I've got a very similar error, but unfortuneatly I don't have an answer yet. The only difference is that my Applet is embedded in a standard HTML page, and loaded via Apache. Once the Applet runs, it then communicates with the servlet via Tomcat. I also exchange data with another server task via CORBA.
    But everything else is the same, self-signed applet, applet compiles successfully, and jar is being put in the Plug-in Caceh successfully.
    I have narrowed the problem down a bit, and maybe you can tell me if you're in a similar situation:
    In my case, I need to encrypt the data that I'm sending through CORBA, so I create a Cipher object using Cipher.getInstance(). This method call seems to be the catalyst of my troubles. No matter where I move that call in my code, the next time the code tries to instantiate a class defined in my applet jar file after that "getInstance" call, I get the "zip file closed error." It's like the classloader is confused, because the Cipher.getInstance method would be accessing a different jar file or something. Are you trying to do something similar? Maybe not creating a Cipher, but creating some other object defined outside your own jar-file?
    To top it off, if I disable caching in the Plugin control panel, everything works fine. But that's not really an option for me, since it slows things down a lot, and I can't make all my users go into their control panels and disable caching. But at leasts it makes me confident that there's not a problem with my code.
    In my latest attempt to circumvent this problem, I even put the Cipher.getInstance() call in a static initializer. Here's the stack trace from that attempt:
    java.lang.IllegalStateException: zip file closed
    at java.util.zip.ZipFile.getEntry(Unknown Source)
    at java.util.jar.JarFile.getEntry(Unknown Source)
    at sun.plugin.cache.CachedJarFile.getEntry(Unknown Source)
    at java.util.jar.JarFile.getJarEntry(Unknown Source)
    at sun.misc.URLClassPath$JarLoader.getResource(Unknown Source)
    at sun.misc.URLClassPath.getResource(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at sun.applet.AppletClassLoader.findClass(Unknown Source)
    at sun.plugin.security.PluginClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.applet.AppletClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    at com.uss.wbi.client.WBIClient.<init>(WBIClient.java:404)
    at com.uss.wbi.client.WBIApplet.init(WBIApplet.java:122)
    at sun.applet.AppletPanel.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    In other words, since the getInstance method is in a static initializer, the next thing to run is the applet.init(), which is what is failing now. If I move the Cipher.getInstance method into the client constructor, the next time I instantiate a new object, I'll get the error there.
    Has anybody else seen anything like this? Or does anybody know how I can flush the Cache from the applet code? Or can I reset the ClassLoader in some way in the code?
    Thanks,
    Steve

    Well, I finally came to a solution that is acceptable at least to me, if not ideal. I've started using the BouncyCastle lightweight API. This makes my code somewhat more complicated, and I had to bundle up all the BouncyCastle classes that I'm using into a jar file, and download that to my applet along with my client jar file (after signing the jar files). Using this Lightweight API bypasses the Cipher.getInstance() method all together, and is a little harder to use, but at least everything is working consistently now.
    I still believe this to be a bug either in the ClassLoader or the Cipher.getInstance() method. I intend to try to write a test applet that reproduces the error in a more simple way and if I can pull that off, I'll submit a bug report to Sun.
    Thanks to all who responded!!
    Steve

  • What error is this? for BouncyCastle

    I tried to run this bouncycastle example but encounter this error? what happen to this?? can someone enlighten me? thanks.
    D:\testing>java PKCS12Example
    Exception in thread "main" java.io.IOException: exception encrypting data - java
    .security.NoSuchProviderException: JCE cannot authenticate the provider BC: java
    .lang.SecurityException: Cannot verify jar:file:/D:/testing/!/: java.security.Pr
    ivilegedActionException <<java.util.zip.ZipException: Access is denied>>
    at org.bouncycastle.jce.provider.JDKPKCS12KeyStore.wrapKey(JDKPKCS12KeyS
    tore.java:562)
    at org.bouncycastle.jce.provider.JDKPKCS12KeyStore.engineStore(JDKPKCS12
    KeyStore.java:1003)
    at java.security.KeyStore.store(KeyStore.java:576)
    at PKCS12Example.main(PKCS12Example.java:478)

    If you installed the Sun JCE in your jre/lib/ext directory (which I suggest unless you have some reason not to), you probably neglected to add both the policy files to the same directory. Unfortunately, I'm pretty sure that this is the same Exception you will see no matter what goes wrong when trying to load the classes, so frankly, it's difficult to diagnose the problem.
    Also make sure your system's date and time are set correctly.
    If you still have problems, may I suggest the BouncyCastle provider (http://www.bouncycastle.org) that most people in this forum seem to be using.

  • PGP error in PI 7.4 - BouncyCastle Provider not found

    Hi ,
    I am working on PGP encryption in SAP PI7.4 .
    I have followed below link :
    PGPEncryption Module: A Simple How to Guide
    Using PGP in Process Integration
    But while doing end to end scenario it is givingg error :
    Exception caught by adapter framework: Could not process message, BouncyCastle Provider not found (java.security.NoSuchProviderException: unable to find provider.)
    In my sandbox it was woking fine but when trying to do the same thing in Dev box it staretd giving error .
    Can somebody help me .
    Thanks ,
    Anurag

    Hi Anurag
    You should check if the Secure Connectivity add on was deployed correctly in your Dev system. Maybe there are some missing JAR or SCA files.
    Refer to the Secure connectivity add-on installation guide on how to download and deploy the SCA files. You can find this guide on the Service Marketplace (search for PI SFTP PGP ADDON.)
    You can also refer to the following How-to guide on checking the installation via NWA. The guide is for SFTP but you can follow the same steps in page 2 to check.
    How To Configure SFTP Adapter in SAP PI
    Rgds
    Eng Swee

  • Help : java.security.UnrecoverableKeyException: excess private key

    Hi,
    I require help for the exception "java.security.UnrecoverableKeyException: excess private key"
    When i am trying to generate digital signature using PKCS7 format using bouncyCastle API, it gives the "java.security.UnrecoverableKeyException: excess private key" exception.
    The full stack trace is as follows
    ------------------------------------------------------------------------java.security.UnrecoverableKeyException: excess private key
         at sun.security.provider.KeyProtector.recover(KeyProtector.java:311)
         at sun.security.provider.JavaKeyStore.engineGetKey(JavaKeyStore.java:120)
         at java.security.KeyStore.getKey(KeyStore.java:289)
         at com.security.Security.generatePKCS7Signature(Security.java:122)
         at com.ibm._jsp._SendSecureDetail._jspService(_SendSecureDetail.java:2282)
         at com.ibm.ws.jsp.runtime.HttpJspBase.service(HttpJspBase.java:93)
    I had tested the program under following scenarios...
    The Java Program for generating the digital signature independently worked successfully(without any change in policy files or java.security file) I have tested this independently on Sun's JDK 1.4, 1.6
    For IBM JDK 1.4 on Windows machine for WAS(Webshere Application Server) 6.0, The Program for generating the digital signature using PKCS7 works fine, but it required IBM Policy files(local_policy.jar, US_export_policy.jar) and updation in java.security file
    But the problem occurs in Solaris 5.10, WAS 6.0 where Sun JDK 1.4.2_6 is used.
    I copied the unlimited strength policy files for JDK 1.4.2 from Sun's site(because the WAS 6.0 is running on Sun's JDK intead of IBM JDK)...
    I changed the java.security file as follows(only changed content)
    security.provider.1=sun.security.provider.Sun
    security.provider.2=com.ibm.security.jgss.IBMJGSSProvider
    security.provider.3=com.ibm.crypto.fips.provider.IBMJCEFIPS
    security.provider.4=com.ibm.crypto.provider.IBMJCE
    security.provider.5=com.ibm.jsse2.IBMJSSEProvider2
    security.provider.6=com.ibm.jsse.IBMJSSEProvider
    security.provider.7=com.ibm.security.cert.IBMCertPath
    security.provider.8=com.ibm.security.cmskeystore.CMSProvider
    I have used PKCS12(PFX) file for digital signature
    which is same for all environment(i have described as above)
    I copied the PFX file from windows to solaris using WinSCP in binary format so the content of certificate won't get currupted.
    I can not change the certificate because it's given by the company and which is working in other enviroments absolutely fine(just i have described above)
    I have gone though the "http://forums.sun.com/thread.jspa?threadID=408066" and other URLs too. but none of them helped...
    So what could be the problem for such exception?????
    I am on this issue since last one month...
    I know very little about security.
    Thanks in advance
    PLEASE HELP ME(URGENT)
    Edited by: user10935179 on Sep 27, 2010 2:47 AM
    Edited by: user10935179 on Sep 27, 2010 2:54 AM

    user10935179 wrote:
    The Java Program for generating the digital signature independently worked successfully(without any change in policy files or java.security file) If the program was working fine without changing the java.security policy file, why have you changed it to put the IBM Providers ahead of the SunRsaSign provider?
    While I cannot be sure (because I don't have an IBM provider to test this), the error is more than likely related to the fact that the IBM Provider implementations for handling RSA keys internally are different from the SunRsaSign provider. Since you've now forced the IBM provider ahead of the original Sun provider, you're probably running into interpretation issues of the encoded objects inside the keystore.
    Change your java.security policy back to the default order, and put your IBM Providers at the end of the original list and run your application to see what happens.
    Arshad Noor
    StrongAuth, Inc.

Maybe you are looking for

  • HT4972 How do you save your photos, Are they saved in the back up?

    So you know how when you plug in your apple device the tab for saving your pictures in a certain folder comes up, Well that thing doesnt show up and I dont know how else to save my photos. When you back up your device on itunes does all my photos in

  • Glitches in my new iMac

    Unexpected glitches have occured. (1) characters suddenly appear in uppercase though caps not in use. (2) Opening and closing files slows down - the file slips back to its folder in slow motion. (3) folders/files refuse to open with the double click.

  • Order and purchase order

    hi gurus,   I want to cancel order and purchase order.i am doing Third party returns process.So where can i can cancle these both any transaction code exits .. suresh

  • How to download a site in DW?

    I'm very new to Dreamweaver. I need to take over a site and the adobe software. There is no copy of the site on the local network. I could use an FTP program to download the site to my hard drive and then proceed from there within DW. However, if DW

  • Problem Installing AERS

    Hi guys, I'm new in OPA Technology and I need help because I can't find anything about my problem on Metalink. I describe my situation: Node 1 (Windows 2003 Server) Oracle Database 9.2.0.6 Software (Installed) Oracle Database 9.2.0.6 (Created) Node 2