Encrypt/Decrypt data, multiple public keys using Bouncy castle api?

Hi all.
I need to implement encrypt/decrypt functionality of some data with many public keys using bouncy castle api and EnvelopedData class in java 1.4 SE.
Could someone give me examples how to do it. I searched whole the internet and i could not find simple example.

Hi thanks very much.
I had a quick look at the examples. I will see if they could help me.
Here is more specific what i want:
Encrypt data with multiple public keys that are kept in .pkcs12 file.
And decrypt the data using coresponding private key after that.
I must use bouncy castle api for java 1.4 se.
Best regards
Edited by: menchev on Nov 13, 2008 8:26 AM

Similar Messages

  • How can I encrypt/decrypt data in Forms using a specified Package?

    Hi All,
    I have searched in the Internet for ecnrypting/decrypting data in Forms.
    That is when I want to query the data outside the Form Application it will be encypted, otherwise if I want to query it in the form application it will be dycrypted
    I found this package:
    CREATE OR REPLACE PACKAGE Encrypt_pkg AS
    FUNCTION encrypt (p_text IN VARCHAR2) RETURN RAW;
    FUNCTION decrypt (p_raw IN RAW) RETURN VARCHAR2;
    END Encrypt_pkg;
    CREATE OR REPLACE PACKAGE BODY Encrypt_pkg AS
    -- All VARCHAR2 inputs are padded to multiples of 8 charaters,
    -- with the encryption key also being a multiple of 8 charaters.
    -- The encryption key and padding characters can be altered to suit.
    g_key RAW(32767) := UTL_RAW.cast_to_raw('12345678');
    g_pad_chr VARCHAR2(1) := '';
    PROCEDURE padstring (p_text IN OUT VARCHAR2);
    FUNCTION encrypt (p_text IN VARCHAR2) RETURN RAW IS
    l_text VARCHAR2(32767) := p_text;
    l_encrypted RAW(32767);
    BEGIN
    padstring(l_text);
    DBMS_OBFUSCATION_TOOLKIT.desencrypt(input => UTL_RAW.cast_to_raw(l_text),
    key => g_key,
    encrypted_data => l_encrypted);
    RETURN l_encrypted;
    END;
    FUNCTION decrypt (p_raw IN RAW) RETURN VARCHAR2 IS
    l_decrypted VARCHAR2(32767);
    BEGIN
    DBMS_OBFUSCATION_TOOLKIT.desdecrypt(input => p_raw,
    key => g_key,
    decrypted_data => l_decrypted);
    RETURN RTrim(UTL_RAW.cast_to_varchar2(l_decrypted), g_pad_chr);
    END;
    PROCEDURE padstring (p_text IN OUT VARCHAR2) IS
    l_units NUMBER;
    BEGIN
    IF LENGTH(p_text) MOD 8 > 0 THEN
    l_units := TRUNC(LENGTH(p_text)/8) + 1;
    p_text := RPAD(p_text, l_units * 8, g_pad_chr);
    END IF;
    END;
    END Encrypt_pkg;
    ** Now How can I use this package to encrypt/decrypt data in the form as I said Plz???

    <p>Read this article and go to chapter 2.3.2.</p>Inserts, Update and Delete orders are managed by a stored procedure. In the sample dialog, the Select is handled by the emp_pkg.emp_query() stored function:
      PROCEDURE emp_query(emp_data IN OUT emptab) IS
        ii NUMBER;
        CURSOR empselect IS
          SELECT empno, ename, job, sal, comm FROM emp
           ORDER BY ename ;
      BEGIN
        OPEN empselect;
        ii := 1;
        LOOP
          FETCH empselect INTO
            emp_data( ii ).empno,
            emp_data( ii ).ename,
            emp_data( ii ).job,
            emp_data( ii ).sal,
            emp_data( ii ).comm;
          EXIT WHEN empselect%NOTFOUND;
          ii := ii + 1;
        END LOOP;
      END emp_query;In your case, all you have to do is th use your decrypt() function in the cursor definition:
        CURSOR empselect IS
          SELECT decrypt(empno), decrypt(ename), decrypt(job), decrypt(sal), comm FROM emp
           ORDER BY ename ;
    ...For Insert and Update events, use the crypt() function in the related stored procedures.
      PROCEDURE emp_insert2(t IN emptab) IS
      BEGIN
        FOR i IN t.first..t.last LOOP
         INSERT INTO emp (empno, ename, job, sal, comm)
         VALUES(crypt(t(i).empno), crypt(t(i).ename), crypt(t(i).job), crypt(t(i).sal, t(i).comm));
         END LOOP ;
      END emp_insert2;Idem for the Update procedure.
    Francois

  • Encrypt data with public key?

    I am trying to find a class that support encryption with PublicKey.
    In the class Signature there is a method "initSign" that takes a PrivateKey as argument, but that is used for signing certificates.
    What I am looking for is to make A encrypt some data with B' public key that B can decrypt with its private key...is there any class for this scenario?

    You might want to check out these, if you haven't already:
    http://java.sun.com/j2se/1.5.0/docs/guide/security/CryptoSpec.html
    http://java.sun.com/j2se/1.5.0/docs/guide/security/jce/JCERefGuide.html
    http://java.sun.com/j2se/1.5.0/docs/api/javax/crypto/package-summary.html
    http://java.sun.com/j2se/1.5.0/docs/api/javax/crypto/interfaces/package-summary.html
    http://java.sun.com/j2se/1.5.0/docs/api/javax/crypto/spec/package-summary.html

  • How could I Encrypt the data of SDO_GEOMETRY type using DBMS_CRYPTO package

    Hi:
    I want to Encrypt the data of SDO_GEOMETRY object type using DBMS_CRYPTO package.
    What could I do? hope anyone can help me,give me a suggestions!
    thanks in advance.
    lgs

    well, the spatial api would not be able to handle this data anymore, so what you are trying to do is converting an SDO_GEOMETRY to some cryptable user type (see http://download-uk.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_crypto.htm#sthref1506) and encrypting this.
    Before using the SDO_GEOMETRY type will have to decrypt and reconvert it again and pass it to the spatial query or function.

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

  • Is it Possible to Decrypt Data if WPA Key is Known

    One of our clients has a WRT54G in his office.
    Several of his employees (including himself) are accessing it wirelessly.
    Is it possible that an employee can decrypt his data if they are running a sniffer program and know the WPA key?
    Thank you in advance.

    I will try to qualify the question somewhat....
    I mean with tools that are available that don't cost a small fortune in terms of money and computer resources to decrypt.

  • Get Modulus and exp from public key

    Hi friends,
    I'm extracting the public key from the X.509 certificate .Is there
    any way i can extract modulus and exponent from the public
    key. i'm using bouncy castle api . Any suggestions are greatly appreciated.
    //Generate Certificate
    //Extract public key
    PublicKey merchKey = cert.getPublicKey();
    //Pls suggest the way to extract mod and exp from public key
    Regards
    Jag

    PublicKey merchKey = cert.getPublicKey();
    RSAPublicKey rsaPub = (RSAPublicKey) merchKey;
    BigInteger modulus = rsaPub.getModulus();
    BigInteger exponent = rsaPub.getPublicExponent();

  • Bouncy castle???

    can v use bouncy castle api's in java????
    i have used it in j2me....can it also b used with standard edition???

    There must be some tutorial information on their website. I know they have an examples on http://www.bouncycastle.org/documentation.html. Basically, you can use it in two ways. One way is exclusively through the JCE. You use the same Java classes like Cipher, MessageDigest, Signature, etc, but you explicitly specify the provider in the getInstance method. Here is small code fragment example
    import java.io.*;
    import java.security.*;
    import javax.crypto.*;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    public class BCastle1
        public static void main(String[] args) throws Exception
            Security.addProvider(new BouncyCastleProvider());
            // "BC" is the name of the BouncyCastle provider
            KeyGenerator keyGen = KeyGenerator.getInstance("DES", "BC");
            keyGen.init(new SecureRandom());
            Key key = keyGen.generateKey();
            Cipher encrypt = Cipher.getInstance("DES/CBC/PKCS5Padding", "BC");
            encrypt.init(Cipher.ENCRYPT_MODE, key);
            ByteArrayOutputStream bOut = new ByteArrayOutputStream();
            CipherOutputStream cOut = new CipherOutputStream(bOut, encrypt);
            // ... other stuff omitted ....
    }Another way is to use the lightweight API directly. You use the classes whose Javadocs are at http://www.bouncycastle.org/docs/docs1.5/index.html just like any other Java classes.

  • How to decrypt data when you can't get the private key in Windows?

    I'm very confuse. My english is poor, but I try to say my question clearly.
    When browser connects to a https website which needs client certificate to authenticate the identity, the browser will send client certificate to web server.
    Then the web server will use the certificate to encrypt some data and send it to browser.
    Then broswer should have private key to decrypt that.
    But as I know, if I install a pfx format personal certificate, I can set can't export private key, which means you can't get the private key to use it. So how can
    the browser decrypt the data without private key?
    By the way, what is CSP, use CSP's interface can we use CryptoAPI
    to decrypt data without private key?

    Answer for question is  "you cant".. 
    "How to decrypt data when you can't get the private key in Windows?"
    Read more 
    http://msdn.microsoft.com/en-us/library/windows/desktop/aa387460(v=vs.85).aspx
    http://msdn.microsoft.com/en-us/library/windows/desktop/bb427432(v=vs.85).aspx
    http://technet.microsoft.com/en-us/library/dd277320.aspx
    http://en.wikipedia.org/wiki/Public-key_cryptography

  • Renewing public key certificate used for Seeburger AS2

    My general question is when a public key certificate, used for Seeburger AS2 payload decryption and digital signatures, needs to be renewed, how carefully do the certificate renewal steps need to be coordinated for a seamless transition?  More specifically...
    1. Once we import the CSR response from the CA, will the public key currently used by our partner become invalid, or will it continue to work until its expiration date? 
    2. Will our partner be able to validate our signature after the new CSR has been imported, but prior to them applying the new public key certificate in their system? 
    3. Or can we renew the certificate, import the CSR request, provide our partner with the renewed certificate, and let them apply the certificate at their own volition, provided they do it prior to the original certificate expiration?

    Hi Kurt
    In my experience, the renewal/replacement of AS2 certificates for encryption/decryption & signing/authentication requires coordinated effort on both sides.
    This is because AS2 uses asymmetrical encryption, so both parties need to use the same pair of certificates at the same time, i.e. you encrypt on your private key, and partner decrypt on the public key matching your private key. If the keys used do not belong to the same pair, then decryption will not work.
    I'm not sure what AS2 software your partner uses and if it has the feature of automatic rollover of certificate, but PI/Seeburger does not. The approach in PI/Seeburger can either be one of the following:-
    i) import new cert replacing original cert of the same name
    ii) import new cert into new name, manually update sender/receiver agreements
    Due to the manual nature of the tasks, normally it requires coordinated effort during a cutover window.
    Rgds
    Eng Swee

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

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

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

  • Signing code with Public Key

    Hi guys,
    I'm working on my thesis,and my prof. told me that I have to sign a
    java object with a public key.
    Looks to be impossible, but I asked him again and he confirmed what he
    said.
    How do I create a digital signature of a java object using a Publik
    Key??
    Thanks a Lot guys!!!
    Bye!

    How do I create a digital signature of a java object using a Public Key??Well as my fellow poster said it makes no sense siging (Encrypting) an Object using a Public Key as it would be available for access.
    If it is about Siging an Object with a Single Key where there is concept having a public / private key i think most of the Symmentric Encryption Algorithms come into picture. where there would be a single key used for both encrypting & decrypting data.
    However, you can very well have a look of the specified links below to recheck on things.
    http://www.unix.org.ua/orelly/java-ent/security/ch12_01.htm
    http://www.developer.com/java/other/article.php/630851
    http://mindprod.com/jgloss/digitalsignatures.html
    Hope these might be of some help...
    REGARDS,
    RaHuL

  • 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

  • In SSL programming what is mean by Public key-pls explain

    In SSL programming what is mean by Public key-pls explain

    Hello Nivas,
    Public Key + Private Key "must pair together to be able to encrypt/decrypt
    Private Key used to decrypt the message.
    Public Key : used to encrypt the message, distributed freely to everyone
    Private Key : kept secret on the machine so that only the owner can decrypt
    the message, used to decrypt his public friends encrypted message.
    You will find more details at :
    http://e-docs.bea.com/wls/docs60////security/concepts.html
    Ludovic.
    "nivas" <[email protected]> a écrit dans le message news:
    3c270b27$[email protected]..
    >
    In SSL programming what is mean by Public key-pls explain

  • Please help I am stuck at "not a DSA public key"

    Hi
    I am just starting with the certificate/security API so this may be a naive question. I have a certificate,private key signature & data from a third-party. I am using following program to verify the signature.
    import java.io.*;
    import java.security.*;
    import java.security.cert.CertificateFactory;
    import java.security.cert.X509Certificate;
    import java.security.spec.*;
    import java.util.Collection;
    import java.util.Iterator;
    class VerSig {
        public static void main(String[] args) {
            /* Verify a DSA signature */
            if (args.length != 3) {
                System.out.println("Usage: VerSig publickeyfile signaturefile datafile");
            else try{
                InputStream inStream = new FileInputStream(args[0]);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                Collection c = cf.generateCertificates(inStream);
                Iterator i = c.iterator();
                X509Certificate cert = null;
                while (i.hasNext()) {
                    cert = (X509Certificate)i.next();
                inStream.close();
                PublicKey pubKey = null;
                if (cert != null)
                    pubKey = cert.getPublicKey();
                // create a Signature object and initialize it with the public key
                Signature sig = Signature.getInstance("SHA1withDSA","SUN");
                sig.initVerify(pubKey);
                // Update and verify the data
                FileInputStream datafis = new FileInputStream(args[2]);
                BufferedInputStream bufin = new BufferedInputStream(datafis);
                byte[] buffer = new byte[1024];
                int len;
                while (bufin.available() != 0) {
                    len = bufin.read(buffer);
                    sig.update(buffer, 0, len);
                bufin.close();
                //input the signature bytes
                FileInputStream sigfis = new FileInputStream(args[1]);
                byte[] sigToVerify = new byte[sigfis.available()];
                sigfis.read(sigToVerify );
                sigfis.close();
                boolean verifies = sig.verify(sigToVerify);
                System.out.println("signature verifies: " + verifies);
            } catch (Exception e) {
                System.err.println("Caught exception " + e.toString());
    } First of all :
    1) I wrote "Signature sig = Signature.getInstance("SHA1withDSA","SUN");" because somewhere in the certificate, I saw Signature Algorithm: SHA1withDSA. Is this correct?
    2)I am getting following exception after
    Signature sig = Signature.getInstance("SHA1withDSA","SUN");"
    sig.initVerify(pubKey);
    Caught exception java.security.InvalidKeyException: not a DSA public key: algorithm = SHA1withDSA, params unparsed, unparsed keybits =
    0000: 02 41 00 91 89 17 2D 83 2D 19 51 96 8F D3 A7 CE .A....-.-.Q.....
    0010: 33 E7 B0 1F 6C 79 F4 91 3E B5 5E 81 92 42 65 BA 3...ly..>.^..Be.
    0020: 56 F8 8B F4 FF 54 4F D6 ED 38 A4 71 BD BE D4 69 V....TO..8.q...i
    0030: 21 02 E3 CD 48 96 BC B3 14 F4 42 90 4D 38 5C 78 !...H.....B.M8\x
    0040: D3 26 58 .&X
    what am I doing wrong?

    Hi,
    I am getting the same issue using JDK 1.4.2 regarding the "not a DSA public key" error.
    I also tried using Bouncy Castle instead, but also fail at the verify step (although with a slightly different error):
    "java.security.NoSuchAlgorithmException: no such algorithm: SHA
    1with1.3.14.3.2.27 for provider BC"
    My initial attempt using the Sun classes looks very much like the original example above. My Bouncy Castle implementation looks like:
    Provider bc = new BouncyCastleProvider();
    Security.insertProviderAt( bc, 1 );
    try
    // read PKCS#7 data from input stream
    CMSSignedData sig = new CMSSignedData( request.getInputStream() );
    CertStore certs = sig.getCertificatesAndCRLs( "Collection", "BC" );
    SignerInformationStore signers = sig.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();
    while (it.hasNext())
    SignerInformation signer = (SignerInformation)it.next();
    Collection certCollection = certs.getCertificates( signer.getSID() );
    Iterator certIt = certCollection.iterator();
    X509Certificate cert = (X509Certificate)certIt.next();
    logger.debug( "Cert = " + cert );
    logger.debug( "Cert Sig Alg = " + cert.getSigAlgName() );
    logger.debug( "Pub Key Alg = " + cert.getPublicKey().getAlgorithm() );
    if ( signer.verify( cert, "BC" ) )
    logger.debug( "Verified!" );
    else
    logger.debug( "Not verified." );
    catch( Exception e )
    e.printStackTrace();
    return e.getMessage();
    and provides the following output:
    2006-04-26 14:06:46,882 - Cert =
    [0] Version: 1
    SerialNumber: 0
    IssuerDN: CN=ID3
    Start Date: Tue Sep 30 20:00:00 EDT 1997
    Final Date: Thu Dec 31 19:00:00 EST 2037
    SubjectDN: CN=ID3
    Public Key: DSA Public Key
    y: 9189172d832d1951968fd3a7ce33e7b01f6c79f4913eb55e81924265ba56f88bf4ff544fd6ed38a471bdbed4692102e3cd4896bcb314f442904d385c78d32658
    Signature Algorithm: SHA1withDSA
    Signature: 302c0214163774149d7a9ac672aa6beb0af7c5b1
    bee965be02144c9bf7da70a24dc644f788a8096e
    9ed1f1777741
    2006-04-26 14:06:46,882 - Cert Sig Alg = SHA1withDSA
    2006-04-26 14:06:46,882 - Pub Key Alg = DSA
    06/04/26 14:06:46 java.security.NoSuchAlgorithmException: no such algorithm: SHA
    1with1.3.14.3.2.27 for provider BC
    06/04/26 14:06:46 at java.security.Security.getEngineClassName(Security.java:723)
    06/04/26 14:06:46 at java.security.Security.getEngineClassName(Security.java:693)
    06/04/26 14:06:46 at java.security.Security.getImpl(Security.java:1132)
    06/04/26 14:06:46 at java.security.Signature.getInstance(Signature.java:218)
    06/04/26 14:06:46 at org.bouncycastle.cms.CMSSignedHelper.getSignatureInst
    ance(CMSSignedHelper.java:171)
    06/04/26 14:06:46 at org.bouncycastle.cms.SignerInformation.doVerify(Signe
    rInformation.java:261)
    06/04/26 14:06:46 at org.bouncycastle.cms.SignerInformation.verify(SignerInformation.java:494)
    ...truncated...
    I see that the original post is quite old. Was anyone able to figure out the issue? What am I missing?
    Thanks,
    Brian

Maybe you are looking for

  • Exchange 2013 SP1 users not receiving quota warning email message

    Hi, We are on Exchange 2013 SP1 and Exchange 2010 SP3 co-existence mode and currently migrating users from Exchange 2010 to 2013.  We have noticed that users are not receiving email message when their mailbox quota warning when its near to maximum li

  • CSS not showing up in Browser

    I am having trouble with my CSS code. I had to break it down to the most simples form. I have created my page using internal CSS which was working when I tested my page in my browser(s). When I exported my CSS code to an external page. This is were i

  • Can I use Lumia 920 charger to charge Lumia 925 ?

    I used tonight my friend Lumia 920 charger (EU ver) to charge my Lumia 925 for a little bit, is this safe for my 925 ? Thx.

  • Entry in Table

    Hi , I have one requirement for table Entry. Requirement is like i hve 3 fields in table dealer no , dealer name and city.While entering the the fields from SM30, user wants like if he/she enters dealer no then dealer name and city should automatical

  • How can a text background color be saved?

    How can a text background color be saved in TextEdit?