Invalid Key Exception for DES Encryption during cipher initialization.

All,
We are trying to implement DES Encryption in IBM Mainframe Z series. The code looks like...
<code>
public String encrypt(String input){
String outputStr = null;
SecretKeySpec keySpec = null;
SecretKeyFactory keyFactory = null;
SecretKey key = null;
keySpec = new SecretKeySpec(keyPassword.getBytes("ISO-8859-1"), "DES");
Cipher cipher = Cipher.getInstance("DES","IBMJCE");
cipher.init(Cipher.ENCRYPT_MODE, key);
BASE64Encoder encode = new BASE64Encoder();
output = cipher.doFinal(input.getBytes("ISO-8859-1"));
outputStr = encode.encode(output);
</code> with relevant try catch etc.
However we are getting an exception -
java.security.InvalidKeyException
at com.ibm.crypto.provider.DESCipher.engineGetKeySize(Unknown Source)
at javax.crypto.Cipher.init(Unknown Source)
The same code is working in Windows.
Please let us know if there s anything wrong - or there is a work-around.
JDK Version in Mainframe is 1.4
Thanks
Srini

DES keys are 8 bytes with the Least Significant Bit (LSB) of each byte being used as a parity bit but taking no part in the encryption process. DES keys are binary data and are normally provided as bytes and not as a String object. If 'keyPassword' does not reference a String containing exactly 8 ISO-8859-1 characters then you will get the Invalid Key Exception since the key has to be exactly 8 bytes.
I have to ask why you don't have exactly 8 characters in your password? The fact that your code talks of passwords and not key-bytes hints that you should maybe be using Password Based Encryption (PBE).

Similar Messages

  • 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

  • Invalid key number for CRforVS_13_0

    why diplay invalid key number when I add a new crystal report in VS 2010?

    You can use a FTP client (or your browser if it supports FTP) and download from the Adobe FTP server (ftp.adobe.com). The files are in /pub/adobe/cs6/downloads :
    Windows (launch the .exe which will open the 7z file):
    ftp://ftp.adobe.com/pub/adobe/cs6/downloads/Photoshop_13_LS6.7z
    ftp://ftp.adobe.com/pub/adobe/cs6/downloads/Photoshop_13_LS6.exe
    Mac :
    ftp://ftp.adobe.com/pub/adobe/cs6/downloads/Photoshop_13_LS6.dmg
    Previous versions are also available in /pub/adobe/photoshop/win and /pub/adobe/photoshop/mac
    These folders are public so you don't need any identifier to connect.

  • Sql Server connection - missing / invalid key information for tables

    Not sure if this is a known issue (couldn't see one) or simply poor JDBC behaviour ... I'm connected to a Sql Server 2000something instance and I see the Users, and I see the Tables and Columns for the user of interest. BUT for Keys for each table, I only see the Primary Key. No other keys (especially Foreign Keys). There is nothing under Constraints. And also, for the Primary Keys I do see, the list of columns is "messed up" (some columns appear twice, in a different order, etc).
    - Yes I'm using the jtds jdbc driver off of sourceforge.net
    - Yes I used the "add 3rd party driver" wizard to add the entry
    - Yes I am connecting using the "sa" account, and it has a password (which I supplied to the Connection definition)
    - Yes the Connection then asks me for a database, I see users in that database, I see element types for each user
    --- so most of it is working.
    I'd really like to get this working, to migrate data from the Sql Server database into an Oracle database (and yes I pulled down the Migration Tool plugin). But I need to understand the Foreign Keys in order to set up the target database and perform the migration.
    Any ideas as to why it doesn't pull info on Keys correctly ??

    Cos its not there. Right now, the SQL constrained the keys tab to just Primary keys. I'm removed that restriction so FK's should appear here now, the same as it does in SQL Server EM
    Barry

  • How to use the same keypair for both encrypt/decryprt-SunPKCS#11

    Dear All,
    Subject: To access iKey 2032 token, to retrieve public/private key from iKey 2032 token using pkcs#11 in sdk1.5, to encrypt/decrypt files.
    When I separate the encrypt and decrypt part of java program, encryption program works well, whereas decryption program does not decrypt anything in the decrypt file (But there is no error). I printed out the public and private key in both encrypt and decrypt part of java program, its displayed differently::
    Encrypt program:
    SunPKCS11-rainbow_token RSA public key, 1024 bits (id 10, session object)
    modulus: 114338469922835728259534620463489934081917342509275191892563243582065
    74380495029336519036972702864998634664269499641616889325482699399559620370181624
    72068116957594402738459932902481604823224406859575930392708524033619120886256353
    58738237376491107769961041015109436347533548940674900728805627968145581222172729
    public exponent: 65537
    SunPKCS11-rainbow_token RSA private key, 1024 bits (id 11, session object, sensi
    tive, unextractable)
    Decrypt Program::
    SunPKCS11-rainbow_token RSA public key, 1024 bits (id 12, session object)
    modulus: 138556361758970660122782926386849783732271581948935425587968692317930
    09262429353977097956605140384961825974398004270547046620971835394362397699233738
    54481804748731546655197744692886754946373745924825650876065903334173666990347814
    83727290962956934521650035029131176614982652900659797194703065074407857754883163
    public exponent: 65537
    SunPKCS11-rainbow_token RSA private key, 1024 bits (id 13, session object, sensi
    tive, unextractable)
    I suspect that every time program generates different set of key, therefore we need to store the generated key during encryption part (i believe it is to be in the keystore) and to use the same for decryption part. Could you please give me a tips how to do this?
    Encrypt Program ::
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.sql.*;
    import java.text.*;
    import java.math.*;
    import java.security.*;
    import java.security.cert.*;
    import java.security.interfaces.*;
    import javax.crypto.interfaces.*;
    import javax.net.ssl.*;
    import javax.crypto.*;
    import javax.crypto.spec.DESKeySpec;
    import java.security.KeyStore.*;
    * A class of Encrypt.
    public class Encrypt
    public Encrypt(){}
    public void loginToken() {
         Provider p = new sun.security.pkcs11.SunPKCS11(MQConfig.getvalue("SecurityPropertyPath"));
         Security.addProvider(p);
         KeyStore ks = null;
         try{
              String password = General.ReadFiles(MQConfig.getvalue("logFilePath"),"Simple");
              password = password.trim();
              char pin[] = password.toCharArray();
              ks = KeyStore.getInstance("pkcs11");
              ks.load(null,pin);
         KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA",p);
              KeyPair kp = kpg.genKeyPair();
              kpg.initialize(1024, new java.security.SecureRandom());
              FileInputStream in = new FileInputStream("C:\\ReportDBBE.properties");
              FileOutputStream out = new FileOutputStream("C:\\ReportDBAE.properties");
              Cipher cp=Cipher.getInstance("RSA/ECB/PKCS1Padding", p);
              cp.init(cp.ENCRYPT_MODE,kp.getPublic());
              CipherOutputStream cout=new CipherOutputStream(out,cp);
              byte[] input=new byte[8];
              int byteread=in.read(input);
              while(byteread!=-1){
                   cout.write(input,0,byteread);
                   byteread=in.read(input);
              cout.flush();
              in.close();
              cout.close();
         catch(NoSuchAlgorithmException nsae)
         System.out.println("No Such Algorithm Exception " + nsae.getMessage());
         catch(NoSuchPaddingException nspe)
         System.out.println("No Such Padding Exception " + nspe.getMessage());
         catch(InvalidKeyException ike)
         System.out.println("Invalid Key Exception " + ike.getMessage());
         catch(IllegalStateException ise)
         System.out.println("Illegal State Exception " + ise.getMessage());
         catch(KeyStoreException kse)
         System.out.println("Key Store Exception " + kse.getMessage());
         catch(CertificateException ce)
         System.out.println("Certificate Exception " + ce.getMessage());
         catch(IOException ioe)
         System.out.println("IO Exception " + ioe.getMessage());
    public static void main (String args[]) throws Exception {
         try{
         Encrypt tl = new Encrypt();
         tl.loginToken();
         }catch(Exception e){
         e.printStackTrace();
    Decrypt Program ::
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.sql.*;
    import java.text.*;
    import java.math.*;
    import java.security.*;
    import java.security.cert.*;
    import java.security.interfaces.*;
    import javax.crypto.interfaces.*;
    import javax.net.ssl.*;
    import javax.crypto.*;
    import javax.crypto.spec.DESKeySpec;
    import java.security.KeyStore.*;
    * A class of Decrypt.
    public class Decrypt
    public Decrypt(){}
    public void loginToken() {
         Provider p = new sun.security.pkcs11.SunPKCS11(MQConfig.getvalue("SecurityPropertyPath"));
         Security.addProvider(p);
         KeyStore ks = null;
         try{
              String password = General.ReadFiles(MQConfig.getvalue("logFilePath"),"Simple");
              password = password.trim();
              char pin[] = password.toCharArray();
              ks = KeyStore.getInstance("pkcs11");
              ks.load(null,pin);
         KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA",p);
              KeyPair kp = kpg.genKeyPair();
              kpg.initialize(1024, new java.security.SecureRandom());
              FileInputStream in1 = new FileInputStream("C:\\ReportDBAE.properties");
              FileOutputStream out1 = new FileOutputStream("C:\\ReportDBAD.properties");
              Cipher cipher=Cipher.getInstance("RSA/ECB/PKCS1Padding", p);
              AlgorithmParameters algParams = cipher.getParameters();
              cipher.init(Cipher.DECRYPT_MODE,kp.getPrivate(),algParams);
              CipherInputStream cin1=new CipherInputStream(in1,cipher);
              byte[] input1=new byte[8];
              int byteread1=cin1.read(input1);
              while(byteread1!=-1){
                   out1.write(input1,0,byteread1);
                   byteread1=cin1.read(input1);
              out1.flush();
              in1.close();
              out1.close();
              cin1.close();
         catch(NoSuchAlgorithmException nsae)
         System.out.println("No Such Algorithm Exception " + nsae.getMessage());
         catch(NoSuchPaddingException nspe)
         System.out.println("No Such Padding Exception " + nspe.getMessage());
         catch(InvalidKeyException ike)
         System.out.println("Invalid Key Exception " + ike.getMessage());
         catch(IllegalStateException ise)
         System.out.println("Illegal State Exception " + ise.getMessage());
         catch(InvalidAlgorithmParameterException iape)
         System.out.println("Invalid Algorithm ParameterException " + iape.getMessage());
         catch(KeyStoreException kse)
         System.out.println("Key Store Exception " + kse.getMessage());
         catch(CertificateException ce)
         System.out.println("Certificate Exception " + ce.getMessage());
         catch(IOException ioe)
         System.out.println("IO Exception " + ioe.getMessage());
    public static void main (String args[]) throws Exception {
         try{
         Decrypt tl = new Decrypt();
         tl.loginToken();
         }catch(Exception e){
         e.printStackTrace();
    Configuration file::
    name = rainbow_token
    library = c:\winnt\system32\dkck201.dll
    attributes(*,CKO_PRIVATE_KEY,*) = {
    CKA_SIGN = true
    attributes(*,CKO_PRIVATE_KEY,CKK_DH) = {
    CKA_SIGN = null
    attributes(*,CKO_PRIVATE_KEY,CKK_RSA) = {
    CKA_DECRYPT = true
    }

    Hi all,
    Now i manage to use the same keypair for both encrypt/decryprt-SunPKCS#11. Below is my code woks well. In my code i hard coded alias name of certificate, did anyone knows how to read alias name of certificate from iKey token 2032??
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.sql.*;
    import java.text.*;
    import java.math.*;
    import java.security.*;
    import java.security.cert.*;
    import java.security.interfaces.*;
    import javax.crypto.interfaces.*;
    import javax.net.ssl.*;
    import javax.crypto.*;
    import javax.crypto.spec.DESKeySpec;
    import java.security.KeyStore.*;
    * A class of Encrypt.
    public class Encrypt
    public Encrypt(){}
    public void loginToken() {
         Provider p = new sun.security.pkcs11.SunPKCS11(MQConfig.getvalue("SecurityPropertyPath"));
         String myAlias = "349eefd1-845b-4ba4-9f88-06e9f5cb82f6";
         /** to view alias name
         keytool -list -v -keystore NONE -storetype PKCS11 -storepass PASSWORD
         Security.addProvider(p);
         KeyStore ks = null;
         PrivateKey privKey = null;
         PublicKey pubKey = null;
         try{
              String password = General.ReadFiles(MQConfig.getvalue("logFilePath"),"Simple");
              password = password.trim();
              char pin[] = password.toCharArray();
              ks = KeyStore.getInstance("pkcs11");
              ks.load(null,pin);
              java.security.cert.Certificate cert = ks.getCertificate(myAlias);
              Key key = ks.getKey(myAlias, pin);
              if(key != null) {
                   System.out.println("key class: " + key.getClass().getName()); // -> sun.security.pkcs11.P11Key$P11PrivateKey
                   System.out.println("key bytes: " + key.getEncoded()); // -> null!!!!!!!
         if(PrivateKey.class.isInstance(key)) {
         privKey = (PrivateKey)key;
         System.out.println("algo: " + privKey.getAlgorithm()); // -> RSA
         //Signature rsasig = Signature.getInstance("SHA1withRSA");
         //rsasig.initSign(privKey);
         //rsasig.update(data.getBytes());
         //byte[] sigBytes = rsasig.sign();
         pubKey = cert.getPublicKey();
         //System.out.println("signed bytes: " +sigBytes);
         //return sigBytes;
         //KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA",p);
              //KeyPair kp = kpg.genKeyPair();
              //KeyPair kp = kpg.generateKeyPair();
              //kpg.initialize(1024, new java.security.SecureRandom());
              FileInputStream in = new FileInputStream("C:\\ReportDBBE.properties");
              FileOutputStream out = new FileOutputStream("C:\\ReportDBAE.properties");
              Cipher cp=Cipher.getInstance("RSA/ECB/PKCS1Padding", p);
    //cp.init(cp.ENCRYPT_MODE,kp.getPublic());
              cp.init(cp.ENCRYPT_MODE,pubKey);
              CipherOutputStream cout=new CipherOutputStream(out,cp);
              byte[] input=new byte[8];
              int byteread=in.read(input);
              while(byteread!=-1){
                   cout.write(input,0,byteread);
                   byteread=in.read(input);
              cout.flush();
              in.close();
              cout.close();
         catch(NoSuchAlgorithmException nsae)
         System.out.println("No Such Algorithm Exception " + nsae.getMessage());
         catch(NoSuchPaddingException nspe)
         System.out.println("No Such Padding Exception " + nspe.getMessage());
         catch(InvalidKeyException ike)
         System.out.println("Invalid Key Exception " + ike.getMessage());
         ike.printStackTrace();
         catch(IllegalStateException ise)
         System.out.println("Illegal State Exception " + ise.getMessage());
         catch(KeyStoreException kse)
         System.out.println("Key Store Exception " + kse.getMessage());
         catch(CertificateException ce)
         System.out.println("Certificate Exception " + ce.getMessage());
         catch(IOException ioe)
         System.out.println("IO Exception " + ioe.getMessage());
         catch(UnrecoverableKeyException unrke)
         System.out.println("Unrecoverable Key Exception " + unrke.getMessage());
    public static void main (String args[]) throws Exception {
         try{
         Encrypt tl = new Encrypt();
         tl.loginToken();
         }catch(Exception e){
         e.printStackTrace();
    Your help is very much appreciated!!!!

  • Java.sql exception for rs.nesxt() ( nested statements)

    I have a problem with java.sql.I am getting an Invalid handle exception for nested result sets ...
    example:-
    //Conn is the common connection
    Statement s1 = conn.createStatement();
    rs1 = s1.executeQuery(query1);
    while (rs.next){
    Statement s2 = conn.createStatement();
    rs2= s2.executeQuery(query2)
    while (rs2.next){
    The rs2 resultset works fine,but when it gets back into the outer while loop the exception is thrown.
    I know that the problem is becuase the nested statements are usign the same connection.
    I know of two ways to work around this
    (1) use different connections
    (2) remove nesting (save the result rs1,and then retrieve rs2)
    But I wnated to know if anyone knows of any other way to work around this problem.
    let me know.
    Thanks.

    Each connection has a single storage area for iteration, metadata, etc. Obviously you are aware that outer loop is unable to proceed because iteration data is of a different format from the inner sql query. It is not a good idea to do more than a single, or small set of queries on a single connection object. Would you consider a connection pool? They are not for the timid programmer, but they do take advantage of using connection objects much like pointers, with the ability to pop them into and out of a collection, ready to roll once the connection object is setup and ready for action much like a pointer that is properly assigned can be passed and always ready for action. The entire connection object (and metadata) is stored in the collection data structure. My advice is to keep it simple! It is easy to get too carried away with connection pools.

  • Runtime exceptions while trying to DES encryption

    Hi,
    I am quite new to Java and I am trying the following Encryption/decryption logic using DES Encryption. It works fine on my machine which has JDK 1.4 version and JCE 1.2.2
    CODE SAMPLE:-
    import java.io.UnsupportedEncodingException;
    import java.security.spec.AlgorithmParameterSpec;
    import java.security.spec.KeySpec;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.PBEKeySpec;
    import javax.crypto.spec.PBEParameterSpec;
    public class DesEncrypter {
    Cipher ecipher;
    Cipher dcipher;
    // 8-byte Salt
    byte[] salt = {
    (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
    (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
    // Iteration count
    int iterationCount = 19;
    DesEncrypter(String passPhrase) {
    try {
    // Create the key
    KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
    SecretKey key = SecretKeyFactory.getInstance(
    "PBEWithMD5AndDES").generateSecret(keySpec);
    ecipher = Cipher.getInstance(key.getAlgorithm());
    dcipher = Cipher.getInstance(key.getAlgorithm());
    // Prepare the parameter to the ciphers
    AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
    // Create the ciphers
    ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
    dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
    } catch (java.security.InvalidAlgorithmParameterException e) {
    } catch (java.security.spec.InvalidKeySpecException e) {
    } catch (javax.crypto.NoSuchPaddingException e) {
    } catch (java.security.NoSuchAlgorithmException e) {
    } catch (java.security.InvalidKeyException e) {
    public String encrypt(String str) {
    try {
    // Encode the string into bytes using utf-8
    byte[] utf8 = str.getBytes("UTF8");
    // Encrypt
    byte[] enc = ecipher.doFinal(utf8);
    // Encode bytes to base64 to get a string
    return new sun.misc.BASE64Encoder().encode(enc);
    } catch (javax.crypto.BadPaddingException e) {
    } catch (IllegalBlockSizeException e) {
    } catch (UnsupportedEncodingException e) {
    } catch (java.io.IOException e) {
    return null;
    public String decrypt(String str) {
    try {
    // Decode base64 to get bytes
    byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
    // Decrypt
    byte[] utf8 = dcipher.doFinal(dec);
    // Decode using utf-8
    return new String(utf8, "UTF8");
    } catch (javax.crypto.BadPaddingException e) {
    } catch (IllegalBlockSizeException e) {
    } catch (UnsupportedEncodingException e) {
    } catch (java.io.IOException e) {
    return null;
    public static void main(String args[])
         try {
    // Create encrypter/decrypter class
    DesEncrypter encrypter = new DesEncrypter("My Pass Phrase!");
    String origText="My text";
    System.out.println("Original Text="+origText);
    // Encrypt
    String encrypted = encrypter.encrypt(origText);
    System.out.println("Encrypted Text="+encrypted);
    // Decrypt
    String decrypted = encrypter.decrypt(encrypted);
    System.out.println("Decrypted Text="+decrypted);
    } catch (Exception e) {
    However, when i try it on another machine with JDK 1.3 and JCE 1.2.2 I get the error message
    Exception in thread "main" java.lang.NoSuchMethodError
    at javax.crypto.SunJCE_b.<clinit>(DashoA6275)
    at javax.crypto.SecretKeyFactory.getInstance(DashoA6275)
    at DesEncrypter.<init>(DesEncrypter.java:31)
    at DesEncrypter.main(DesEncrypter.java:93)
    Just for the sake of inference, we have already tried the steps mentioned in
    http://archives.java.sun.com/cgi-bin/wa?A2=ind0110&L=java-security&F=&S=&P=6353
    and
    http://archives.java.sun.com/cgi-bin/wa?A2=ind0103&L=java-security&F=&S=&P=14826
    But the problem is ever persistent. Any help in this regards would be greatly appreciated.
    Regards,
    Diws

    Hello Praveen,
       This is just a Vanilla installation of the Portal and KMC. we are on EP 6 SP14. I try opening the KMContent and I get this big page of exceptions.
    I am not able to figure out what and when was the final deployment..
    Please suggest me if you have any solution in mind.
    <b>~~As always, points galore for the right and helpful
    answer.</b>
    Thanks,
    ~LB

  • "Invalid key" error --- License Key for system NSP

    Hello SDN Team,
    I have successfully installed the NW04 ABAP Sneak Preview. Now I'm trying to get a license for it at http://www.sap.com/solutions/netweaver/minisap.epx. I enter all the data, check the License Agreement, hardware key from Transaction SLICENSE, choose the System NSP and send the form.
    I got an email with the following information:
    Your Hardware key      : X17xxxxxxxx
    Your License Key       : BCBHPS8UVTRYQT8TWURZxxxx
    License Expiration date: 20060101
    SID                    : NSP
    Installation-Nr.       : DEMOSYSTEM
    I entered the License Key in the Transaction SLICENSE but I got an error "Invalid key".
    How can i get the correct key?
    Regards,
    James

    Hi SAP,
    I have the same or a similar problem.
    Trying to install the license, I enter the mailed data exactly and properly, however, receive the following error message:
    saplicense: License not installed
    Wrong license data specified
    Check the specified license data for:
    - typing errors
    - upper / lower characters
    - same values as noted on license fax
    The same result when I enter the given data via a file...
    It looks as an error in the generated LKEY field. Really, something has been changed in the procedure and software during the last 3 months (for example, the new entry field is required now in the request form - SND User id).
    Who is responsible and who could help?
    Thanks in advance & best regards,
    Vladimir

  • Invalid key length: exception

    Hi,
    I will really appreciate if someone can help me on this.
    I created a keystore using below tool
    keytool -genkey -v -alias myAlias -keyalg DSA -keystore myKey.keystore -storetype JCEKS -provider com.sun.crypto.provider.SunJCEI am using following code to encrypt the data.
    Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding",provider.getName());
    Key key = store.getKey(myAlias, myPassword);
    cipher.init(Cipher.ENCRYPT_MODE, key);
    encrypted = cipher.doFinal(data);But I get following error everytime,
    java.security.InvalidKeyException: Invalid key length: 335 bytes
    at com.sun.crypto.provider.DESedeCipher.engineGetKeySize(DashoA12275)
    at javax.crypto.Cipher.init(DashoA12275)I will appreciate if who can advice me on this issue.
    Thanks,
    Rouble

    Please look at http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=65&t=001211

  • Unable to validate message; key used for decrypting message is invalid;

    When trying to decrypt an RNIF message in our SAP XI system we are running into an issue with below error message:
    "Unable to validate message; key used for decrypting message is invalid; expected keystore entry: SSL-<SID>; keystore entry used: null"
    The keystore administrator role is mapped to XIAFUSER. We validated the decryption using the J2EE Private Key thru a third-party (non-SAP) tool and it works fine. The keystore SSL-<SID> contains the Private Key and Cert from our CA. The message was encrypted using the Public Key of J2ee engine.
    We were unable to generate more details even after increasing the log level. The security.log is the only place showing the above error message.

    The folder C:\j2sdk1.4.2_13\jre\lib\security contains the Java Cryptography Extension (JCE)  files -  'local_policy.jar' and 'US_export_policy.jar' .The default files will have a size of 3 kb.These need to be replaced by JCE Unlimited Strength Jurisdiction Policy Files -  'local_policy.jar' and 'US_export_policy.jar'  which are of size 5kb. In brief, C:\j2sdk1.4.2_13\jre\lib\security should contain the files -  'local_policy.jar' and 'US_export_policy.jar'  and their size should be 5kb (and not 3kb). After we did this change the decrypt worked fine.

  • Message processing failed. Cause: com.sap.engine.interfaces.messaging.api.exception.MessagingException: java.io.IOException: invalid content type for SOAP: TEXT/HTML; HTTP 404 Not Found

    In my 2006 biztalk application I have exposed web service to receive SAP input. It was working fine. After I have modified something in orchestration in that application . I am getting following error while SAP try to consume my web service. Can anyone please
    help me.
    Message processing failed. Cause: com.sap.engine.interfaces.messaging.api.exception.MessagingException: java.io.IOException: invalid content type for SOAP: TEXT/HTML; HTTP 404 Not Found

    In my 2006 biztalk application I have exposed web service to receive SAP input. It was working fine. After I have modified something in orchestration in that application . I am getting following error while SAP try to consume my web service.
    HI Arivazhagan K,
    Could you give some explanation about what you modified? according the to error message, this is "resource is not found issue".
    Best regards,
    Angie
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to use exception for a Date Key Figure

    Hello All,
                    I have the following requirement.
    1. I have a Key Figure which is Date Type.
    2. I need to color the cell to green if the it is filled with date otherwise leave it as it is.
    Please suggest how to overcome it.
    Thanks & Regards,
    Rajib

    hi,
    Your requirement is not clear, you have the below setup
    I have the following requirement.
    1. I have a Key Figure which is Date Type.
    How can a KF be of date type, or is it the value of a date characteristic that you have extracted in KF using formula variable. If yes you just need to define exception for the value greater than 0.
    regards,
    Arvind.

  • Looking for "PDF Public-Key Digital Signature and Encryption Specification"

    Hi,
    i am looking for the following ("old") document:
    PDF Public-Key Digital Signature and Encryption Specification
    Originally i could be found here:
    http://partners.adobe.com/asn/developer/acrosdk/DOCS/ppk_pdfspec.pdf
    But not anymore. Does somebody of you still have it? Adobe today just offers the latest documents but i specifically need that older version.
    Or is there an archive i don't know of?
    Thanks for your help,
    ToM

    You can read the PDF 1.5 specification OR even ISO 32000-1 itself for that information. Each feature is "tagged" with the specific version in which it was introduced.
    Digital Signatures were first introduced in Acrobat 4 (PDF 1.3) and have seen various improvements which each version since.

  • How to generate all possible keys for DES algorithm

    Hello every one,
    I want to generate all the possible key combinations for the DES algorithm 56-bit "actuallly 64 but the last 8 bits are just padding", so can anyone plz help how can i do that? or give me article or something that might help me?
    Thanks in advance,
    Amr M. Kamel.

    I know that but who said that it will be one
    processor it will be on distributed and clustered
    environment :). I just want to know how to generate
    the keys "or write binary".
    Thans again for your helpA cluster of 2285 machines will still take a year! The simplest algorithm is to just count from 0 to 2^56 .
    If you are thinking of cracking DES then there is a Book I have on my shelf 'Cracking DES' published by the 'Electronic Frontier Foundation' ISBN 1-56592-520-3 . It contains the C code and describes the hardware used. The hardware cost was about $100,000 and it cracks DES in about 3.5 days.
    Assuming Moore's law ( http://en.wikipedia.org/wiki/Moore's_law ) applies then it should now take about much less than a day and cost much less than $100,000. BUT - it will take a long time using basic computers.

  • Invalid key for Quicktime Pro

    Okay, I'm feeling pretty irate right now after paying out £20 for a product key which was emailed to me for 'instant access' but doesn't bleeding work... Having followed the simple steps, I pasted in my key and got the message 'invalid key' instead of 'Quicktime Pro 7' or whatever...
    Will someone here, or someone at Apple please explain to me how in God's name that can happen!
    There was something I needed to do with it before the night is over - yet now obviously I can't and what's more I am 20quid out of pocket!
    If someone at Apple is reading, I suggest you call or, at the very least, email me with some form of apology for this situation.
    Answers please...

    Well, having waited til daybreak to call the support line, I found out that the key alone will not validate the product - you have to enter the name of the person who ordered and paid for it (in this case me) but exactly as they wrote in in the email... I had neglected to put a '.' after 'Mr' and hence the whole thing didn't work. Add the dot, and hey presto...
    The guy on the line was very cordial about it but did mention that they get this 'all the time'...
    Apple take note... You should make that clearer - especially since my account is in my name - the Mr was selected from a scroll-down menu - and since many people don't even use the dot any more - well it can be confusing...

Maybe you are looking for

  • Every time since I download IOS6 my app store, whatsapp, safari crashes everytime I open it. What should I do?

    Every time since I download IOS6 my app store, whatsapp, safari crashes everytime I open it. What should I do?

  • HT1349 playing music through usb port

    hiw do i play ipod touch through a normal hifi with either usb or phono plugs   when i connect to usb connection im told it is not compatable yet my origonal i pod works fin 

  • Migration from SQL 7.0 to Oracle

    Hey guys ! I am required to migrate from MS SQL7.0 to oracle which has around 150 stored procedures and a database schema of 50 tables. its oracle 8/8i version. can u suggest how to go about ? ie. should I used Migration workbench or go doing it conv

  • ArcGis dosen't run on Satellite C660

    Load ArcGis AOK on win7 64bit Satellite Laptop. Authorise Licence for single user AOK When I run ArcMap get ArcGis has encountered a serious application error and is unable to run. Note this is happening on another laptop same configuration

  • Safari Doesn't See Webplugin

    I've downloaded and insalled the SurveilClient HiDvrPlugin.webplugin for my Swann security system so that I can monitor my cameras from my laptop. Everytime I go to my cameras IP address, I've given the following message: When I check Help > Installe