Initialising Cipher- No Alg params exception

Hi guys.
I am trying to encrypt some data with the secret key and then.. send the secret key & encrypted data across ..(dont worry the secret key is sent securely using PKI ;-)) . Then i recreate the secret key and use it to decrypt the data. I was successful in recreating the secret key. but while initialising the cipher (to decrypt mode) using the reconstructed secret key, it throws exception like this:
java.lang.IllegalArgumentException: no IV set when one expected
at org.bouncycastle.jce.provider.JCEBlockCipher.engineInit(JCEBlockCipher.java:437)
at javax.crypto.Cipher.init(DashoA6275)
I then got the algorithm params from the earlier cipher and then sent them across too.. and this works properly !!! Can u please tell me whether it is right to do it this way.Can we do it in any other way without sending the alg parameters ?? something like.. can the parameters be generated at the other side..just guessing ;)
//Encrypt
Cipher scipher= Cipher.getInstance("DES/CBC/PKCS5Padding");
scipher.init(Cipher.ENCRYPT_MODE,secretKey);
encrypted= scipher.doFinal("data".getBytes());
System.out.println("after encrypting the data with the secret key : "+new String(encrypted));
AlgorithmParameters ap= scipher.getParameters();
//Decrypt
Cipher dcipher= Cipher.getInstance("DES/CBC/PKCS5Padding");
dcipher.init(Cipher.DECRYPT_MODE,reconstructedSecretKey);//HERE I GET THE EXCEPTION
decrypt= dcipher.doFinal(encrypted);
System.out.println("after decrypting with the secret key the data is: "+new String(decrypt));
Thanks in advance,
Vijay.

Thanks a LOT Grant . I tried it out and it works
well!!:-)). Glad I could help.
I would like to know more about
IVParameters and also about different modes (CFB/ OFB
/CFB8/OFB32/ OAEP and others)and the padding schemes
to be used with them. Can u give me any specific link
where these things are discussed well?My usual advice is to find and browse/read Bruce Schneier's "Applied Cryptography", ISBN 0-471-111709-9, Wiley&Sons pub. It's a very good introduction to the whole crypto field. There's also the "Handbook of Applied Cryptography" (HAC) - it's also a great book, but heavier on the math and not as accessible (IMNSHO) to the beginner as Schneier. However, it is available in PDF format - check here:
http://www.cacr.math.uwaterloo.ca/hac/
It's a fascinating field - good luck!
Grant

Similar Messages

  • BAD PARAM Exception

    Folks, My CORBA App is throwing the following exception:
    WARNING: "IOP00110201: (BAD_PARAM) Null parameter"
    org.omg.CORBA.BAD_PARAM:vmcid: SUN minor code: 201 completed: Maybe
    at com.sun.corba.se.impl.logging.ORBUtilSystemException.nullParam (Unknown Source)
    This is being thrown from an IDL-generated Helper class of an object in the method 'public static void write()' in the line 'out.write_string(s.someString);'. This seems to be happening when the string 'someString' has a value of null. Can't a string have null value? Is this exception expected? Should all string values be necessarily non-null?
    Thanks.

    GSP wrote:
    Folks, My CORBA App is throwing the following exception:
    WARNING: "IOP00110201: (BAD_PARAM) Null parameter"
    org.omg.CORBA.BAD_PARAM:vmcid: SUN minor code: 201 completed: Maybe
    at com.sun.corba.se.impl.logging.ORBUtilSystemException.nullParam (Unknown Source)
    This is being thrown from an IDL-generated Helper class of an object in the method 'public static void write()' in the line 'out.write_string(s.someString);'. This seems to be happening when the string 'someString' has a value of null. Can't a string have null value? Err, apparently not...
    Is this exception expected? Should all string values be necessarily non-null?No, not all. But it can't be null in this case (given the provided details).
    It this application developed by a company called Atomikos?

  • Cipher in multihreaded environments

    Hi,
    I have short question because I didn't find an anwser yet.
    Is the Cipher I use to encrypt/decrypt multithreading-safe?
    I ask this because I want to use it in a web-environment.
    I have something like this:
    public class Whatever {
         // Are these to fields Thread safe?
         private static Cipher cipherEncrypt;
         private static Cipher cipherDecrypt;
         private static Key key = new SecretKeySpec("donttell".getBytes(), "DES");
         private static boolean initialised = false;
         private void initialise() {
              if (!initialised) {
                   synchronized (ImmonetCookie.class) {
                        if (!initialised) {
                             try {
                                  cipherEncrypt = Cipher.getInstance("DES");  // This one is very expensive, so we try to avoid it for every user
                                  cipherEncrypt.init(Cipher.ENCRYPT_MODE, key);
                                  cipherDecrypt = Cipher.getInstance("DES");
                                  cipherDecrypt.init(Cipher.DECRYPT_MODE, key);
                             catch (Exception ex) {
                                  logger.error("..", ex);
                             initialised = true;
         protected String encryptValue(String value) {
              ByteArrayOutputStream output = new ByteArrayOutputStream();
              // Here we use the cipher ..
              CipherOutputStream cos = new CipherOutputStream(output, cipherEncrypt);
              try {
                   cos.write(value.getBytes());
                   cos.close();
              catch (IOException e) {
                   logger.error("..", e);
                   return null;
              return new String(Base64.encodeBase64(output.toByteArray()));
         protected String decryptValue(String value) {
              ByteArrayInputStream input = new ByteArrayInputStream(Base64.decodeBase64(value.getBytes()));
              // .. and here we use the cipher
              CipherInputStream cis = new CipherInputStream(input, cipherDecrypt);
              BufferedReader reader = new BufferedReader(new InputStreamReader(cis));
              try {
                   StringBuffer buffer = new StringBuffer();
                   String next = reader.readLine();
                   while (next != null) {
                        buffer.append(next);
                        next = reader.readLine();
                   reader.close();
                   return buffer.toString();
              catch (IOException e) {
                   logger.error("..", e);
              return null;
    }

    Cipher keeps internal state between init, update, and doFinal time. I suspect that what you're doing here will fail horribly.
    And why do you think that Cipher.getInstance("DES") is so awful? The very first time you do it, ever, I suspect it will be,
    because I think that's when SecureRandom gets initialized. After that, though, Cipher.getInstance() isn't a big deal.Thanks Grant, this are the information I was searching for. You're right, the getInstance was just the first time very slow,
    (Also, if you throw an exception trying to initialize your Ciphers, you -still- set "initialised" to true. This will break the rest of your app, because it will keep trying to use null Ciphers.)
    (Your key, btw, is pretty dismal. There are ways of generating reasonable keys from human-readable passwords - a straight getBytes() isn't one of them.)
    (And why are you using DES? Ew. AES is actually secure - nowadays, DES is considered so broken that you might almost just as well use plaintext.)Also thanks a lot for your additional useful information, I will dig into it and take it to heart.
    Regards
    Daniel

  • Problem with Cipher.init()

    i am using java 1.4.2 on Windows 2000 Professional
    I am using "Assembla" as JCE Provider for Microsoft Keystore. But when i call Cipher.init() i am getting the following error
    MSKeyStoreJNI: Could not acquire context for temporary container used for importing public key.
    SYSMSG: The keyset is not defined.
    The Code is as follow :
    -----------------------------import java.util.*;
    import javax.crypto.*;
    import java.security.*;
    import java.security.cert.*;
    import se.assembla.jce.provider.ms.*;
    // JCE Provider for Microsoft Keystore https://download.assembla.se
    public class cipher
       public cipher(String[] args) throws Exception
          Security.addProvider(new MSProvider());
          KeyStore ks = KeyStore.getInstance("msks", "assembla");
          ks.load(null,null);
          X509Certificate cert = null;
          String alias = null;
          for(Enumeration e = ks.aliases(); e.hasMoreElements();)
             alias = (String) e.nextElement();
             if(ks.isKeyEntry(alias))
                cert = (java.security.cert.X509Certificate) ks.getCertificate(alias);
                break;
          Cipher c = Cipher.getInstance("RSA", "assembla");
          c.init(Cipher.ENCRYPT_MODE, cert); // error on this line
       public static void main(String args[])
          try
             new cipher(args);
          catch(Exception e)
             e.printStackTrace();
    }--- hasstar
    --- [SCJP]
    --- url : http://www.myjavaserver.com/~hasstar

    Yes, I tried KeyStore ks = KeyStore.getInstance("RSA", "assembla"); instead of msks?
    and it is not working. (www.bouncycastle.org)
    I tried www.bouncycastle.org, but i don't know how to get Certificates from Microsoft Keystore.
    If u know how to get keys from Microsoft Keystore please help

  • Cryptograhpy cipher RC4 2048bit in JDK1.5

    I need to use RC4 key size of (256 bytes) 2048 bits. From JCE JavaDoc
    http://java.sun.com/j2se/1.5.0/docs/guide/security/jce/JCERefGuide.html#AppE
    RC4 can only support 128 bytes/1024 bits
    I wonder, does any of the JDK/JCE version support RC4 for 2048 bits key?
    Or can you suggest a shareware provider which supports RC4 2048 bits?
    I had this topic posted orginaly in
    http://forum.java.sun.com/thread.jspa?threadID=757353
    Thanks a lot.

    Thanks for your reply:
    I have downloaded Unlimited Strength Jurisdiction Policy Files and replaced jars in my jre/lib/security. I still have the same problem.
    Here is my code: The parameter keyBytes is the same as we use on the other side of the wire implemented in C version of openssl.
    private Cipher quickTestRC4(byte[] keyBytes){
    SecretKey key = new SecretKeySpec(keyBytes, "RC4");
    Cipher cipher = null;
    try {
    cipher = Cipher.getInstance("RC4");
    System.out.println("Testing RC4: initialize by passing keyBytes size = "+keyBytes.length+" bytes");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    catch (Exception e1){
    e1.printStackTrace();
    return cipher;
    Here is the exception:
    Testing RC4: initialize by passing keyBytes size = 256 bytes
    java.security.InvalidKeyException: Key length must be between 40 and 1024 bit
    at com.sun.crypto.provider.ARCFOURCipher.a(DashoA12275)
    at com.sun.crypto.provider.ARCFOURCipher.a(DashoA12275)
    at com.sun.crypto.provider.ARCFOURCipher.engineInit(DashoA12275)
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.a(DashoA12275)
    at javax.crypto.Cipher.init(DashoA12275)
    at javax.crypto.Cipher.init(DashoA12275)
    at com.MyTest.quickTestRC4(MyTest.java:138)
    If I pass in 128 bytes keyBytes, it works fine.
    I wonder, what could be the problem here and how to solve it?
    Thanks a lot.

  • How to set causing Exception correctly?

    I'm trying to nest exceptions. I've written a JUnit tests which does this, but while it works for simple nesting, it doesn't for my more complex Exception.
    The following works:
            Exception e1 = new Exception("bla");
            Exception e2 = new Exception("whatever");
            e1.initCause(e2);
            Assert.assertEquals(e2, e1.getCause());
            Exception e3 = new Exception("yet another exception");
            e2.initCause(e3);
            Assert.assertEquals(e3, e1.getCause().getCause());
            Exception e4 = new Exception("yawn");
            e3.initCause(e4);
            Assert.assertEquals(e4, e1.getCause().getCause().getCause());The following doesn't:
         * The exception to use when a Hibernate transaction can't be ended.
         * The causes of this are created according to the given exceptions.
         * If <code>exception</code> exists:
         * <pre>
         * this
         * |
         * +--> exception
         *      |
         *      +--> hibernateException1
         *           |
         *           +--> hibernateException2 (if it exists)
         * </pre>
         * If <code>exception</code> is <code>null</code>:
         * <pre>
         * this
         * |
         * +--> hibernateException1
         *      |
         *      +--> hibernateException2 (if it exists)
         * </pre>
         * @param errorMessage The error message to show
         * @param exception The exception coming from the business process, which may be <code>null</code>
         * @param hibernateException1 The first Hibernate exception, which <strong>must exist</strong>
         * @param hibernateException2 The second Hibernate exception, which may be <code>null</code>
        public RecoverableSystemException(String errorMessage, Exception exception, HibernateException hibernateException1, HibernateException hibernateException2) {
            super(errorMessage, getCause(exception, hibernateException1, hibernateException2));
         * Gets the causing exception for {@link #RecoverableSystemException(String, Exception, HibernateException, HibernateException)}.
         * @param exception The exception coming from the business process, which may be <code>null</code>
         * @param hibernateException1 The first Hibernate exception, which <strong>must exist</strong>
         * @param hibernateException2 The second Hibernate exception, which may be <code>null</code>
         * @return The causing exception to use for the constructor
        private static Exception getCause(Exception exception, HibernateException hibernateException1, HibernateException hibernateException2) {
            if (hibernateException2 != null && hibernateException1 != null) {
                hibernateException1.initCause(hibernateException2);
            if (exception == null) {
                return hibernateException1;
            else {
                if (hibernateException1 != null) {
                    exception.initCause(hibernateException1);
                return exception;
        }with the test looking like this:
            this.hibernateException1 = new HibernateException("h1");
            this.hibernateException2 = new HibernateException("h2");
            this.businessProcessException = new Exception("e1");
            RecoverableSystemException recoverableSystemException = new RecoverableSystemException("Test", null, this.hibernateException1, this.hibernateException2);
            Assert.assertEquals("Checking Hibernate exception 1", this.hibernateException1, recoverableSystemException.getCause());
            // THIS FAILS
            Assert.assertEquals("Checking Hibernate exception 2", this.hibernateException2, recoverableSystemException.getCause().getCause());Any help would be greatly appreciated!

    initCause is rarely if ever used. It is possible that the way HibernateException is written does not support the use of this call. Have a look at its source to find out if it does.

  • Session key and MAC generation in SCP '02' i='15'

    Hi,
    I am trying send a PUT KEY command and it resolves to '6982' after a '9000' EXTERNAL AUTHENTICATE.
    I suspect that my encryption is causing the problem.(not really sure!)
    I compare my session keys to some that ppl had derived and posted on the forum and I don't really get what they did.
    I am trying to find out if I'm deriving the correct session keys or not?!?!
    e.g
    //Calculating session keys with
    //static key = '404142434445464748494a4b4c4d4e4f' (keyData)
    //sequence counter = '003b'
    //"0101" + sequenceCounter + "000000000000000000000000" for session CMAC key (data)
    //"0102" + sequenceCounter + "000000000000000000000000" for session RMAC key (data)
    //"0181" + sequenceCounter + "000000000000000000000000" for session DEK key (data)
    //"0182" + sequenceCounter + "000000000000000000000000" for session ENC key (data)
    //sessionCMAC is :3213860da8f8d9796794cbcec43ef7a23213860da8f8d979: with sequence counter:003b (result)
    //sessionRMAC is :042a687f6e0dd3f80eabf1e5d51ccefe042a687f6e0dd3f8: with sequence counter:003b (result)
    //sessionDEK is :1fe31370c22354e3b90d6b8ad5686d371fe31370c22354e3: with sequence counter:003b (result)
    //sessionENC is :94a47ad54ffbf423fe4a9d915befab5294a47ad54ffbf423: with sequence counter:003b (result)
    <code>
    if (keyData.length == 16) {
    byte[] temp = (byte[]) keyData.clone();
    keyData = new byte[24];
    System.arraycopy(temp, 0, keyData, 0, temp.length);
    System.arraycopy(temp, 0, keyData, 16, 8);
    DESedeKeySpec keySpec = new DESedeKeySpec(keyData);
    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DESede");
    SecretKey key = secretKeyFactory.generateSecret(keySpec);
    IvParameterSpec iv = new IvParameterSpec(new byte[]{0, 0, 0, 0, 0, 0, 0, 0});
    Cipher desedeCBCCipher = Cipher.getInstance("DESede/CBC/NoPadding");
    desedeCBCCipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] result = desedeCBCCipher.doFinal(data);
    if (result .length == 16) {
    byte[] temp = (byte[]) result .clone();
    result = new byte[24];
    System.arraycopy(temp, 0, result , 0, temp.length);
    System.arraycopy(temp, 0, result , 16, 8);
    keySpec = new DESedeKeySpec(result);
    secretKeyFactory = SecretKeyFactory.getInstance("DESede");
    key = secretKeyFactory.generateSecret(keySpec);
    </code>
    I use the same encrytion to derive KeyCheckValue with
    newKey ='505152535455565758595a5b5c5d5e5f', data = '0000000000000000'
    and it results to : '6d377e' (of course the last 3 bytes)
    Even though my CMAC session key is different from others (e.g "RLopes" in "http://192.9.162.102/thread.jspa?threadID=5365173&tstart=363" and I have seen it in others too and its really odd to me that its slightly different if you take a close look you will get what i mean) i get the EXTERNAL AUTHENTICATION to work.
    If there is anyone who is 100% sure meaning he/she got other commands to work after EXTERNAL AUTHENTICATE using CMAC please help me verify the keys I got?
    Can he/she test with his code to see if he/she is getting the same session keys or check value?
    Thanks in advance
    Kamran

    Hi,
    Here is the Class and thanks for the tip, I've honestly tried these <code></code> but didn't work and I know it is indeed annoying without the tags :D
    I really hope it helps...
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package terminalpcsc;
    import java.lang.Exception;
    import java.security.GeneralSecurityException;
    import java.security.Key;
    import java.security.SecureRandom;
    import java.util.List;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import javax.security.sasl.AuthenticationException;
    import javax.smartcardio.*;
    * @author Kamran
    * @param args the command line arguments
    public class Main {
        private static CardChannel channel;
        private static Card card;
        private static int CHALLENGE_LENGTH = 8;
        private static byte[] keyDiversification = new byte[10];
        private static byte[] keyInformation = new byte[2];
        private static byte[] sequenceCounter = new byte[2];
        private static byte[] cardChallenge = new byte[6];
        private static byte[] cardCryptogram = new byte[8];
        private static byte[] hostChallenge = new byte[8];
        private static byte[] hostCryptogram = new byte[8];
        private static String keyDiversificationHexString;
        private static String keyInformationHexString;
        private static String sequenceCounterHexString;
        private static String cardChallengeHexString;
        private static String cardCryptogramHexString;
        private static String hostChallengeHexString;
        private static String hostCryptogramHexString;
        private static byte[] sessionCMAC;
        private static byte[] sessionDEK;
        private static byte[] sessionENC;
        private static byte[] sessionRMAC;
        private static byte[] icvNextCommand;
        private static IvParameterSpec ivAllZeros = new IvParameterSpec(new byte[]{0, 0, 0, 0, 0, 0, 0, 0});
        private static byte[] staticKey = hexStringToByteArray("404142434445464748494a4b4c4d4e4f4041424344454647");
        private static byte[] newKey = hexStringToByteArray("505152535455565758595a5b5c5d5e5f");
        private static byte[] CMAC;
         * @param args the command line arguments
        public static void main(String[] args) throws Exception {
            initiateCardChannel();
            String apduString = generateSelectAPDU("a000000003535041");
            byte[] bufferC = hexStringToByteArray(apduString);
            CommandAPDU capdu = new CommandAPDU(bufferC);
            System.out.println("Sending APDU Select AID: " + byteArrayToHexString(bufferC));
            ResponseAPDU rapdu = channel.transmit(capdu);
            System.out.println("Sending Apdu: Done!");
            System.out.println("Waiting For Response...");
            byte[] bufferR = rapdu.getData();
            String responseData = byteArrayToHexString(rapdu.getBytes());
            System.out.println("Response: " + responseData);
            apduString = generateInitializeUpdateAPDU();
            bufferC = hexStringToByteArray(apduString);
            capdu = new CommandAPDU(bufferC);
            System.out.println("Sending APDU Initialize Update: " + byteArrayToHexString(bufferC));
            rapdu = channel.transmit(capdu);
            System.out.println("Sending Apdu: Done!");
            System.out.println("Waiting For Response...");
            bufferR = rapdu.getData();
            responseData = byteArrayToHexString(rapdu.getBytes());
            System.out.println("Response: " + responseData);
            // protocol 01
            //System.arraycopy(bufferR,0,keyDiversification,0,10);
            //System.arraycopy(bufferR,10,keyInformation,0,2);
            //System.arraycopy(bufferR,12,cardChallenge,0,8);
            //System.arraycopy(bufferR,20,cardCryptogram,0,8);
            // protocol 02
            System.arraycopy(bufferR, 0, keyDiversification, 0, 10);
            System.arraycopy(bufferR, 10, keyInformation, 0, 2);
            System.arraycopy(bufferR, 12, sequenceCounter, 0, 2);
            System.arraycopy(bufferR, 14, cardChallenge, 0, 6);
            System.arraycopy(bufferR, 20, cardCryptogram, 0, 8);
            keyDiversificationHexString = byteArrayToHexString(keyDiversification);
            keyInformationHexString = byteArrayToHexString(keyInformation);
            sequenceCounterHexString = byteArrayToHexString(sequenceCounter);
            cardChallengeHexString = byteArrayToHexString(cardChallenge);
            cardCryptogramHexString = byteArrayToHexString(cardCryptogram);
            System.out.println("keyDiversification: " + keyDiversificationHexString);
            System.out.println("keyInformation: " + keyInformationHexString);
            System.out.println("sequenceCounter: " + sequenceCounterHexString);
            System.out.println("cardChallenge: " + cardChallengeHexString);
            System.out.println("cardCryptogram: " + cardCryptogramHexString);
            System.out.println("Calculating Session Keys... encryption with CBC");
            //E.4.1 GP 2.1.1
            sessionCMAC = deriveEncryptionCBC(staticKey, hexStringToByteArray("0101" + sequenceCounterHexString + "000000000000000000000000"));
            System.out.println("sessionCMAC is :" + byteArrayToHexString(sessionCMAC) + ": with sequence counter:" + sequenceCounterHexString);
            sessionRMAC = deriveEncryptionCBC(staticKey, hexStringToByteArray("0102" + sequenceCounterHexString + "000000000000000000000000"));
            System.out.println("sessionRMAC is :" + byteArrayToHexString(sessionRMAC) + ": with sequence counter:" + sequenceCounterHexString);
            sessionDEK = deriveEncryptionCBC(staticKey, hexStringToByteArray("0181" + sequenceCounterHexString + "000000000000000000000000"));
            System.out.println("sessionDEK is :" + byteArrayToHexString(sessionDEK) + ": with sequence counter:" + sequenceCounterHexString);
            sessionENC = deriveEncryptionCBC(staticKey, hexStringToByteArray("0182" + sequenceCounterHexString + "000000000000000000000000"));
            System.out.println("sessionENC is :" + byteArrayToHexString(sessionENC) + ": with sequence counter:" + sequenceCounterHexString);
            System.out.println("Calculating and Verifying Card Cryptogram...");
            byte[] signature = cbcMACSignature(hexStringToByteArray(hostChallengeHexString + sequenceCounterHexString + cardChallengeHexString + "8000000000000000"), sessionENC);
            String signatureHexString = byteArrayToHexString(signature);
            if (signatureHexString.equalsIgnoreCase(cardCryptogramHexString)) {
                System.out.println("signature is :" + signatureHexString + "\ncardCryptogram is :" + cardCryptogramHexString + " \nCard cryptogram authenticated");
                apduString = generateExternalAuthenticateAPDU();
                bufferC = hexStringToByteArray(apduString);
                capdu = new CommandAPDU(bufferC);
                System.out.println("Sending APDU External Authenticate: " + byteArrayToHexString(bufferC));
                rapdu = channel.transmit(capdu);
                System.out.println("Sending Apdu: Done!");
                System.out.println("Waiting For Response...");
                bufferR = rapdu.getData();
                responseData = byteArrayToHexString(rapdu.getBytes());
                System.out.println("Response: " + responseData);
                apduString = generatePutKeyAPDU();
                bufferC = hexStringToByteArray(apduString);
                capdu = new CommandAPDU(bufferC);
                System.out.println("Sending APDU Put Key: " + byteArrayToHexString(bufferC));
                rapdu = channel.transmit(capdu);
                System.out.println("Sending Apdu: Done!");
                System.out.println("Waiting For Response...");
                bufferR = rapdu.getData();
                responseData = byteArrayToHexString(rapdu.getBytes());
                System.out.println("Response: " + responseData);
            } else {
                System.out.println("signature is :" + signatureHexString + "\ncardCryptogram is :" + cardCryptogramHexString + " \nCard cryptogram is not authenticated");
            releaseCardChannel();
        public static byte[] cbcMACSignature(byte[] data, byte[] sessionSENC) throws AuthenticationException {
            IvParameterSpec params =
                    new IvParameterSpec(new byte[]{0, 0, 0, 0, 0, 0, 0, 0});
            if (sessionSENC.length == 16) {
                byte[] temp = (byte[]) sessionSENC.clone();
                sessionSENC = new byte[24];
                System.arraycopy(temp, 0, sessionSENC, 0, temp.length);
                System.arraycopy(temp, 0, sessionSENC, 16, 8);
            byte[] temp = null;
            SecretKey secretKey = new SecretKeySpec(sessionSENC, "DESede");
            try {
                Cipher cbcDES = Cipher.getInstance("DESede/CBC/NoPadding");
                cbcDES.init(Cipher.ENCRYPT_MODE, secretKey, params);
                temp = cbcDES.doFinal(data);
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            byte[] signature = new byte[8];
            System.arraycopy(temp, temp.length - 8, signature, 0, signature.length);
            return signature;
        // generateInitialUpdateAPDU()
        //CLA '80'
        //INS '50' INITIALIZE UPDATE
        //P1 'xx' Key Version Number
        //P2 '00' Reference control parameter P2
        //Lc '08' Length of host challenge
        //Data 'xx xx…' Host challenge
        //Le '00'
        //RESPONSE TEMPLATE
        //Key diversification data 10 bytes
        //Key information 2 bytes
        //Card challenge 8 bytes
        //Card cryptogram 8 bytes
        public static String generateInitializeUpdateAPDU() throws Exception {
            hostChallenge = generateHostChallenge();
            hostChallengeHexString = byteArrayToHexString(hostChallenge);
            return "8050000008" + hostChallengeHexString + "00";
        //CLA '80' or '84'
        //INS 'D8' PUT KEY
        //P1 'xx' Reference control parameter P1 Key Version Number -- '00' is new key  range is '01' to '7F'
        //P2 'xx' Reference control parameter P2 Key Identifier     -- '00' to '7F'
        //Lc 'xx' Length of data field
        //Data 'xxxx..' Key data (and MAC if present)
        //Le '00'
        public static String generatePutKeyAPDU() throws Exception {
            String keyCheckValue = new String();
            //keyCheckValue = keyCheckValue.substring(keyCheckValue.length() - (3 * 2));
            keyCheckValue = byteArrayToHexString(deriveEncryptionECB(newKey, hexStringToByteArray("0000000000000000")));
            keyCheckValue = keyCheckValue.substring(keyCheckValue.length() - (3 * 2));
            System.out.println("keyCheckValue :" + keyCheckValue + " 3DES ECB, key is new key '505152535455565758595a5b5c5d5e5f5051525354555657', data is 8 zeroes");
            String encryptedNewKey = byteArrayToHexString(deriveEncryptionECB(sessionDEK, newKey));
            //System.out.println("sessionDEK.getEncoded() :" + sessionDEK.getEncoded() + " len is:" + sessionDEK.getEncoded().length);
            System.out.println("encryptedNewKey :" + encryptedNewKey);
            //testing newKey
            String dataField = "01" + "8010" + encryptedNewKey + "03" + keyCheckValue + "8010" + encryptedNewKey + "03" + keyCheckValue + "8010" + encryptedNewKey + "03" + keyCheckValue;
            // String dataField2 = "01" + "8010" + byteArrayToHexString(newKey) + "03" + keyCheckValue + "8010" + byteArrayToHexString(newKey) + "03" + keyCheckValue + "8010" + byteArrayToHexString(newKey) + "03" + keyCheckValue;
            System.out.println("datafield to calculate cmac :" + dataField);
            System.out.println("icv to calculate cmac is previous mac first 8 byte sessionCMAC in CBC single des :" + byteArrayToHexString(icvNextCommand));
            CMAC = generateCMac2((byte) 0x84, (byte) 0xD8, (byte) 0x00, (byte) 0x81, hexStringToByteArray(dataField), sessionCMAC, icvNextCommand);
            System.out.println("data field with des padding for encryption (encryption in CBC sessionENC) :" + desPadding(dataField));
            String dataField3 = byteArrayToHexString(deriveEncryptionCBC(sessionENC, hexStringToByteArray(desPadding(dataField))));
            System.out.println("data field after encryption :" + dataField3);
            Integer CMACLen = byteArrayToHexString(CMAC).length() / 2;
            System.out.println("CMACLen :" + CMACLen);
            Integer dataFieldLen = dataField3.length() / 2;
            System.out.println("dataFieldLen :" + dataFieldLen);
            Integer intLc = dataFieldLen + CMACLen;
            System.out.println("intLc :" + intLc);
            String hexLc = Integer.toString(intLc, 16);
            System.out.println("hexLc :" + hexLc);
            return "84D80081" + hexLc + dataField3 + byteArrayToHexString(CMAC) + "00";
        //generateExternalAuthenticateAPDU()
        //CLA '84'
        //INS '82' EXTERNAL AUTHENTICATE
        //P1 'xx' Security level  --'03' C-DECRYPTION and C-MAC.--'01' C-MAC.'00' No secure messaging expected.
        //P2 '00' Reference control parameter P2
        //Lc '10' Length of host cryptogram and MAC
        //Data 'xx xx…' Host cryptogram and MAC
        //Le Not present
        public static String generateExternalAuthenticateAPDU() throws Exception {
            System.out.println("Calculating and Verifying Host Cryptogram...");
            hostCryptogram = cbcMACSignature(hexStringToByteArray(sequenceCounterHexString + cardChallengeHexString + hostChallengeHexString + "8000000000000000"), sessionENC);
            hostCryptogramHexString = byteArrayToHexString(hostCryptogram);
            System.out.println("hostCryptogram is :" + hostCryptogramHexString);
            CMAC = generateCMac2((byte) 0x84, (byte) 0x82, (byte) 0x03, (byte) 0x00, hostCryptogram, sessionCMAC, new byte[]{0, 0, 0, 0, 0, 0, 0, 0});
            return "8482030010" + hostCryptogramHexString + byteArrayToHexString(CMAC);
        // generateSelectAPDU()
        //CLA '00' ISO/IEC 7816-4 command
        //INS 'A4' SELECT
        //P1 'xx' Reference control parameter P1 --'04' select by name
        //P2 'xx' Reference control parameter P2 --'00' First or only occurrence --'02' Next occurrence
        //Lc 'xx' Length of AID
        //Data 'xxxx..' AID of Application to be selected
        //Le '00'
        // RESPONSE TEMPLATE
        //'6F' File Control Information (FCI template) Mandatory
        //'84' Application / file AID Mandatory
        //'A5' Proprietary data Mandatory
        //'73' Security Domain Management Data (see Appendix F for detailed coding) Optional
        //'9F6E' Application production life cycle data Optional
        //'9F65' Maximum length of data field in command message Mandatory
        public static String generateSelectAPDU(String AID) throws Exception {
            String AIDlen = Integer.toString(AID.length() / 2, 16);
            if (AIDlen.length() == 1) {
                AIDlen = "0" + AIDlen;
            System.out.println("00A40400" + AIDlen + AID);
            return "00A40400" + AIDlen + AID;
        public static String byteArrayToHexString(byte[] b) throws Exception {
            String result = "";
            for (int i = 0; i < b.length; i++) {
                result +=
                        Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
            return result;
        public static void initiateCardChannel() throws CardException {
            System.out.println("Connecting to Java Card...");
            TerminalFactory factory = TerminalFactory.getDefault();
            List<CardTerminal> terminals = factory.terminals().list();
            System.out.println("Terminals Detected: " + terminals);
            // get the first terminal
            System.out.println("Connecting to: " + terminals + "...");
            CardTerminal terminal = terminals.get(0);
            System.out.println("Connected to: " + terminals);
            // establish a connection with the card
            System.out.println("Connecting to Java Card...");
            card = terminal.connect("T=0");
            System.out.println("Connected to card: " + card);
            System.out.println("Obtaining Channel...");
            channel = card.getBasicChannel();
            System.out.println("Connecting to Channel: " + channel.getChannelNumber());
        public static void releaseCardChannel() throws CardException {
            System.out.println("Disconnection all...");
            card.disconnect(false);
            System.out.println("Disconnection Done");
            System.out.println("*END*");
        public static byte[] hexStringToByteArray(String s) {
            int len = s.length();
            byte[] data = new byte[len / 2];
            for (int i = 0; i < len; i += 2) {
                data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
            return data;
        //To generate the derivation data:
        public static byte[] deriveEncryptionCBC(byte[] keyData, byte[] data) throws GeneralSecurityException {
            //Key key = getSecretKey(keyData);
            if (keyData.length == 16) {
                byte[] temp = (byte[]) keyData.clone();
                keyData = new byte[24];
                System.arraycopy(temp, 0, keyData, 0, temp.length);
                System.arraycopy(temp, 0, keyData, 16, 8);
            SecretKey secretKey = new SecretKeySpec(keyData, "DESede");
            IvParameterSpec dps =
                    new IvParameterSpec(new byte[]{0, 0, 0, 0, 0, 0, 0, 0});
            String algorithm = "DESede/CBC/NoPadding";
            Cipher desedeCBCCipher = Cipher.getInstance(algorithm);
            desedeCBCCipher.init(Cipher.ENCRYPT_MODE, secretKey, dps);
            byte[] result = desedeCBCCipher.doFinal(data);
            //adjustParity(result);
            return result;
        public static byte[] deriveEncryptionECB(byte[] keyData, byte[] data) throws GeneralSecurityException {
            //Key key = getSecretKey(keyData);
            if (keyData.length == 16) {
                byte[] temp = (byte[]) keyData.clone();
                keyData = new byte[24];
                System.arraycopy(temp, 0, keyData, 0, temp.length);
                System.arraycopy(temp, 0, keyData, 16, 8);
            SecretKey secretKey = new SecretKeySpec(keyData, "DESede");
            String algorithm = "DESede/ECB/NoPadding";
            Cipher desedeCBCCipher = Cipher.getInstance(algorithm);
            desedeCBCCipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] result = desedeCBCCipher.doFinal(data);
            //adjustParity(result);
            return result;
         * Adjust a DES key to odd parity
         * @param key
         *            to be adjusted
        public static byte[] adjustParity(byte[] key) {
            for (int i = 0; i < key.length; i++) {
                int akku = (key[i] & 0xFF) | 1;
                for (int c = 7; c > 0; c--) {
                    akku = (akku & 1) ^ (akku >> 1);
                key[i] = (byte) ((key[i] & 0xFE) | akku);
            return key;
        public static byte[] generateCMac2(byte cla, byte ins, byte p1, byte p2, byte[] dataField, byte[] SMacSessionKey, byte[] icv) throws GeneralSecurityException, Exception {
            if (SMacSessionKey.length == 16) {
                byte[] temp = (byte[]) SMacSessionKey.clone();
                SMacSessionKey = new byte[24];
                System.arraycopy(temp, 0, SMacSessionKey, 0, temp.length);
                System.arraycopy(temp, 0, SMacSessionKey, 16, 8);
            byte[] cMac = new byte[8];
            byte[] padding = {(byte) 0x80, 0, 0, 0, 0, 0, 0, 0};
            int paddingRequired = 8 - (5 + dataField.length) % 8;
            byte[] data = new byte[5 + dataField.length + paddingRequired];
            //Build APDU
            data[0] = cla;
            data[1] = ins;
            data[2] = p1;
            data[3] = p2;
            data[4] = (byte) ((byte) dataField.length + (byte) 0x08);
            System.arraycopy(dataField, 0, data, 5, dataField.length);
            System.arraycopy(padding, 0, data, 5 + dataField.length, paddingRequired);
            System.out.println("data to calculate mac :" + byteArrayToHexString(data));
            System.out.println("icv to calculate mac :" + byteArrayToHexString(icv));
            Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
            Cipher singleDesCipher = Cipher.getInstance("DES/CBC/NoPadding", "SunJCE");
            SecretKeySpec desSingleKey = new SecretKeySpec(SMacSessionKey, 0, 8, "DES");
            SecretKey secretKey = new SecretKeySpec(SMacSessionKey, "DESede");
            //Calculate the first n - 1 block. For this case, n = 1
            IvParameterSpec ivSpec = new IvParameterSpec(icv);
            singleDesCipher.init(Cipher.ENCRYPT_MODE, desSingleKey, ivSpec);
            byte ivForLastBlock[] = singleDesCipher.doFinal(data, 0, 8);
            int blocks = data.length / 8;
            for (int i = 0; i < blocks - 1; i++) {
                singleDesCipher.init(Cipher.ENCRYPT_MODE, desSingleKey, ivSpec);
                byte[] block = singleDesCipher.doFinal(data, i * 8, 8);
                ivSpec = new IvParameterSpec(block);
            int offset = (blocks - 1) * 8;
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
            cMac = cipher.doFinal(data, offset, 8);
            ivSpec = new IvParameterSpec(new byte[8]);
            singleDesCipher.init(Cipher.ENCRYPT_MODE, desSingleKey, ivSpec);
            icvNextCommand = singleDesCipher.doFinal(cMac);
            return cMac;
        public static byte[] generateHostChallenge() {
            byte[] hostChallenge = new byte[CHALLENGE_LENGTH];
            SecureRandom random = new SecureRandom();
            random.nextBytes(hostChallenge);
            return hostChallenge;
        public static String desPadding(String hexString) {
            System.out.println("String to pad before:" + hexString);
            hexString = hexString + "80";
            int hexStringLen = hexString.length() / 2;
            int padding = 8 - (hexStringLen % 8);
            for (int i = 0; i < padding; i++) {
                hexString = hexString + "00";
            System.out.println("String to pad after :" + hexString);
            return hexString;
    }Thanks in advance
    Kamran

  • Problems using NSS library as PKCS#11 provider with JAVA 6

    Hi,
    I�m trying to configure JAVA 6 on Solaris 10 SPARC to use Mozilla NSS library as PKCS#11 provider (to achieve FIPS-140 certification for my application). I�m following the guidelines from http://java.sun.com/javase/6/docs/technotes/guides/security/p11guide.html#NSS but unfortunately something doesn�t work for me as expected...
    Let me describe the exact steps that I followed (because devil may be in the small details :-)
    I downloaded NSS 3.11.4 and NSPR 4.6.4 binaries from mozilla.org (32 bit �debug� versions for Solaris 9, because these were the only �binary� versions for SPARC available on Mozilla site and as far as I understand these are the exact versions that passed FIPS-140 certification), unpacked them under the /opt directory and copied both of them into a single /opt/nss tree as follows:
    mkdir /opt/nss
    cp �r /opt/nss-3.11.4/* /opt/nss
    cp �r /opt/nspr-4.6.4/* /opt/nss
    I created a PKCS#11 configuration file /opt/nss/pkcs11.cfg as per JAVA 6 security guide:
    name = NSScrypto
    nssLibraryDirectory = /opt/nss/lib
    nssDbMode = noDb
    attributes = compatibility
    (I know that this configuration is not for FIPS mode � but I thought that I�d better start with a simple NSS configuration)
    Then I modified /usr/jdk/jdk1.6.0_03/jre/lib/security/java.security file and replaced 1st provider with:
    security.provider.1=sun.security.pkcs11.SunPKCS11 /opt/nss/pkcs11.cfg
    Now everything should be in place � so I created a small JAVA program and ran it:
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESedeKeySpec;
    import javax.crypto.SecretKey;
    import javax.crypto.Cipher;
    import java.security.*;
    public class Test
    public static void main(String[] args)
    try
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
    DESedeKeySpec keySpec = null;
    keySpec = new DESedeKeySpec(new String("laKuf1Tcc6sOhsdPf49=m4es").getBytes());
    System.out.println("keyFactory provider: " + keyFactory.getProvider().getName());
    SecretKey key = keyFactory.generateSecret(keySpec);
    Cipher decryptCipher = Cipher.getInstance("DESede");
    decryptCipher.init(Cipher.DECRYPT_MODE, key);
    System.out.println("decryptCipher provider: " + decryptCipher.getProvider().getName());
    catch (Exception ex)
    ex.printStackTrace();
    Unfortunately it produced the following output:
    EMS-Server42# java test
    keyFactory provider: SunPKCS11-NSScrypto
    decryptCipher provider: SunJCE
    And when I comment out SunJCE provider in java.security file I get the following exception:
    java.security.NoSuchAlgorithmException: Cannot find any provider supporting DESede
    at javax.crypto.Cipher.getInstance(DashoA13*..)
    at test.main(test.java:38)
    So it looks like something is wrong with my NSS configuration. Because AFAIK DESede (3DES) is supported by the NSS library, but for some reason JAVA doesn�t see this algorithm implemented in NSS PKCS#11 provider.
    Any suggestions on what am I doing wrong?
    Best regards,
    Alex

    Works for me:
    import java.security.Provider;
    import java.security.SecureRandom;
    import java.security.Security;
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESedeKeySpec;
    import javax.crypto.spec.IvParameterSpec;
    public class Test
      public static void main(String[] args)
        try
          String configFileName = "/nss/nss.cfg";
          Provider nss = new sun.security.pkcs11.SunPKCS11(configFileName);
          Security.addProvider(nss);
          SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede", nss);
          DESedeKeySpec keySpec = new DESedeKeySpec(new String("laKuf1Tcc6sOhsdPf49=m4es").getBytes("UTF-8"));
          System.out.println("keyFactory provider: " + keyFactory.getProvider().getName());
          SecretKey key = keyFactory.generateSecret(keySpec);
          //iv for CBC mode - note, in practice you don't generate a random iv for decryption :)
          byte[] iv = new byte[8];  //64-bit block size for 3DES
          SecureRandom sr = SecureRandom.getInstance("PKCS11", nss);
          sr.nextBytes(iv);
          IvParameterSpec params = new IvParameterSpec(iv);
          Cipher decryptCipher = Cipher.getInstance("DESede/CBC/NoPadding", nss);
          decryptCipher.init(Cipher.DECRYPT_MODE, key, params);
          System.out.println("decryptCipher provider: " + decryptCipher.getProvider().getName());
        catch (Exception ex)
          ex.printStackTrace();
    }Oh, I wouldn't expect your key loading to work when you switch over to FIPS mode.
    cfg file:
    name = NSScrypto
    nssLibraryDirectory = /nss
    nssSecmodDirectory = /nss
    nssModule = fipsYields the following error:
    java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: Could not create key
    because you can't directly handle keying material in FIPS. You'll have to save the secret key in the NSS certDB or generate a random one each time and send it wrapped to the other side.

  • Heavy use of public key

    I need to encrypt a lot of (maybe mllions) pieces of data (each 32 byte long, random looking) using a PublicKey. Each piece must be encrypted separately (since I need the possibility to decrypt it alone).
    This way it is possible to obtain many plaintext-ciphertext pairs using my program. Is it too risky? Of course, cracking the program would reveal the PublicKey anyway, so maybe my whole problem is just stupid.....
    I found out different ways, e.g., encrypting this way just a couple of random SecretKeys, which will be used to encrypt the pieces of data mentioned above. The storage overhead would be small, the computation could be even faster (using symmetrical cipher instead of RSA), but it's more complicated to maintain.... and loosing somehow the encrypted random SecretKeys would be a disaster.
    null

    I tried to figure out, how it works....
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.security.*;
    import java.security.spec.*;
    import sun.misc.*;
    public class PBEEncryptDataString
        static public class EncryptionException extends Exception
            private EncryptionException(String text, Exception chain)
                super(text, chain);
        private static final String PROVIDER = "BC";
        private static final String ALGORITHM = "PBEWITHSHA-1AND192BITAES-CBC-BC";
        public PBEEncryptDataString(String passphrase, byte[] salt, int iterationCount, String characterEncoding) throws EncryptionException
            assert(passphrase != null);
            assert(passphrase.length() >= 6);
            assert(salt != null);
            assert((iterationCount > 6) && (iterationCount < 20));
            assert(characterEncoding != null);
            try
                PBEParameterSpec params = new PBEParameterSpec(salt, iterationCount);
                KeySpec keySpec = new PBEKeySpec(passphrase.toCharArray());
                SecretKey key = SecretKeyFactory.getInstance(ALGORITHM, PROVIDER).generateSecret(keySpec);
                this.characterEncoding = characterEncoding;
                this.encryptCipher = Cipher.getInstance(ALGORITHM, PROVIDER);
                this.encryptCipher.init(javax.crypto.Cipher.ENCRYPT_MODE, key, params);
                this.decryptCipher = Cipher.getInstance(ALGORITHM, PROVIDER);
                this.decryptCipher.init(javax.crypto.Cipher.DECRYPT_MODE, key, params);
            catch (Exception e)
                throw new EncryptionException("Problem constucting " + this.getClass().getName(), e);
        synchronized public byte[] encrypt(String dataString) throws EncryptionException
            assert dataString != null;
            try
                byte[] dataStringBytes = dataString.getBytes(characterEncoding);
                byte[] encryptedDataStringBytes = this.encryptCipher.doFinal(dataStringBytes);
                return encryptedDataStringBytes;
            catch (Exception e)
                throw new EncryptionException("Problem encrypting string", e);
        synchronized public String decrypt(byte[] encryptedDataStringBytes) throws EncryptionException
            assert encryptedDataStringBytes != null;
            try
                byte[] dataStringBytes = this.decryptCipher.doFinal(encryptedDataStringBytes);
                String recoveredDataString = new String(dataStringBytes, characterEncoding);
                return recoveredDataString;
            catch (Exception e)
                throw new EncryptionException("Problem decrypting string", e);
        public static void main(String[] args)
            try
                Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
                final byte[] salt =
                {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, };
                PBEEncryptDataString dataStringEncryptAgent = new PBEEncryptDataString("The Password - make if fairly long so that there is lots and lots of entropy", salt, 1000, "UTF-8");
                // Get the dataString to encrypt from the command line
                String dataString = (args.length == 0)? "The quick brown fox jumps over the lazy dog." : args[0];
                System.out.println("Data string ....................[" + dataString + "]");
                // Encrypt the data
                byte[] encryptedDataStringBytes = dataStringEncryptAgent.encrypt(dataString);
                BASE64Encoder base64Encoder = new BASE64Encoder();
                System.out.println("Encoded encrypted data string ..[" + base64Encoder.encode(encryptedDataStringBytes) + "]");
                // Decrypt the data
                String recoveredDataString = dataStringEncryptAgent.decrypt(encryptedDataStringBytes);
                System.out.println("Recovered data string ..........[" + recoveredDataString + "]");
            catch (Exception e)
                e.printStackTrace(System.out);
        private String characterEncoding;
        private Cipher encryptCipher;
        private Cipher decryptCipher;
    }Here, to show the basic approch, I have used a fixed IV but one can use a random IV and write it as a prefix to the output so that it can be used in the decryption process. Schneier has shown that this in no way compromises the security of the approach BUT, of course, it does increase the effective length of the encrypted data.

  • Runtime error at installing basis patch

    hi
    experts
    i applied basis patch SAPKB60070012 in ECC 6.0 with databse oracle10.2.0after iam logging to the sap i got run time error below
    Runtime Errors         SYNTAX_ERROR
    Date and Time          22.10.2008 11:03:27
    Short text
         Syntax error in program "SAPLSCP2 ".
    What happened?
         Error in the ABAP Application Program
         The current ABAP program "SAPLOLEA" had to be terminated because it has
         come across a statement that unfortunately cannot be executed.
         The following syntax error occurred in program "SAPLSCP2 " in include
          "CL_SALV_FORM_ELEMENT==========CU " in
         line 13:
         "The type "IF_SALV_FORM_CONFIG" is unknown."
         The include has been created and last changed by:
         Created by: "SAP "
         Last changed by: "SAP "
    Error analysis
         The following syntax error was found in the program SAPLSCP2 :
         "The type "IF_SALV_FORM_CONFIG" is unknown."
    igger Location of Runtime Error
      Program                                 SAPLOLEA
      Include                                 LOLEAU13
      Row                                     71
      Module type                             (FUNCTION)
      Module Name                             AC_CALL_METHOD
    urce Code Extract
    ne  SourceCde
    41   DATA AC_GLOBAL_FLUSH_MODE TYPE C.
    42   DATA MAXLINES          TYPE I.
    43   DATA URL(255)          TYPE C.
    44   DATA LEN               TYPE I.
    45   DATA FLDTYPE           TYPE C.
    46   DATA DOLPARAM          TYPE C.
    47   DATA NCOMPS            TYPE I.
    48   DATA I                 TYPE I.
    49   DATA N(2)              TYPE N.
    50   DATA SIZE              TYPE I.
    51   DATA SVARS_WA          LIKE svars_record.
    52
    53   FIELD-SYMBOLS: <F>, <AC_X1> TYPE X, <AC_X2> TYPE X,
    54                  <EXPORTS_WA> TYPE OLE2_METH_PARMS.
    55
    56 For the call to CL_ABAP_CHAR_UTILITIES=>charsize......................
    57   CLASS CL_ABAP_CHAR_UTILITIES DEFINITION LOAD .
    58
    59
    60 * Initialisation
    61   CLEAR: EXPORTSINDEX, PARAMS, MESSAGE_NR, MESSAGE_TEXT.
    62
    63 * check and set the AC_FRONTEND_RUNS_IN_UTF8 parameter.
    64 * if the AC_FRONTEND_RUNS_IN_UTF8 parameter is set, multiply the string parameter len by 3
    65 * to avoid parameters being truncated in the frontend.
    66   IF AC_FRONTEND_RUNS_IN_UTF8 <> ABAP_TRUE.
    67
    68     DATA : gui_uses_utf8 TYPE rststype-sel_ok.
    69
    70     " ask Matthias whether SAPGUI uses the length critical codepage UTF-8
    >>>     CALL FUNCTION 'SCP_GUI_USES_UTF8'
    72       IMPORTING
    73         gui_uses_utf8 = gui_uses_utf8.
    74
    75     IF gui_uses_utf8 IS NOT INITIAL.
    76       AC_IS_FRONTEND_UTF8 = abap_true.
    77     ENDIF.
    78
    79     AC_FRONTEND_RUNS_IN_UTF8 = abap_true.  "set to true to avoid multiple calls
    80   ENDIF.
    81
    82
    83 * If there are entries in IMPORTS set the RETURN_VALUES_EXIST for
    84 * smart flushing. So if RETURN_VALUES_EXIST = ' ' a flush can be
    85 * postponed in AC_FLUSH_CALL
    86   IF NOT IMPORTS[] IS INITIAL.
    87     RETURN_VALUES_EXIST = 'X'.
    88   ENDIF.
    89
    90 * determine size of exports table
    what is the solution for it.

    hi venkat
    u execute this tp command at /usr/sap/trans/bin with sidadm user.before executing of this command take  backup
    /usr/sap/trans/bin # tp r3i SAPKB70014 SID pf = /usr/sap/trans/bin/TP_DOMAIN_KDV.PFL -Dclientcascade=yes -Drepeatonerror=8 -Dsourcesystems= tag=SPAM
    i got tp error 8 in my server.which error u got u mention above.
    NOTE:After executing this command return must be 0 or 4.other than this u contact sap.wont tell about this command
    after solving this problem u enter spam tcode and import queue.dont open another transactions while installaing patch except spam.
    i tried almost three times i succeed.
    regards
    vasu

  • Hi, can someone help me with:NoSuchAlgorithmException

    Hi firneds, Sorry by my poor English.
    I am trying to use a "cipher", and I get this error:
    java.security.NoSuchAlgorithmException: Algorithm RSA_PKCS1_v2_1 not
    available at javax.crypto.b.a([DashoPro-V1.2-120198]) at
    javax.crypto.Cipher.getInstance ...
    What's going wrong?
    My code...
    import javax.crypto.*;
    public class Cifrado
         Cipher cipher;
    public void Cifra(byte[] input, String Algor, PublicKey publickey,
    PrintStream out)
    try {
    cipher = Cipher.getInstance Algor); ///"RSA_PKCS1_v2_1/CBC/PKCS5Padding"
    catch(Exception e){
         e.printStackTrace(out);
    In another class I did set the provider with:
    import de.flexiprovider.core.*;
    Security.addProvider(new de.flexiprovider.core.FlexiCoreProvider());
    I'm trying to use FlexiPorvider with jdk 1.3.1_01 as development tool
    by your time: thanks a lot.

    Thanks by the reply: Crypto03
    This provider contains the algorithm, when I put the "addProvider", I get with getPorviders() the following:
    Alg.Alias.Cipher.PBEwithSHA1andDES-CBC
    Signature.SHA1withRSA
    Cipher.SERPENT
    Cipher.E2
    SecretKeyFactory.PbeWithSHAAnd3_KeyTripleDES_CBC
    Alg.Alias.AlgorithmParameterGenerator.1.2.840.10040.4.1
    SecretKeyFactory.0.2.262.1.10.1.2.5.2
    Alg.Alias.AlgorithmParameters.1.2.840.113549.1.12.1.6
    AlgorithmParameters.HmacMD5
    Cipher.RSA_PKCS1_v2_1 >>>>>>>>>>> Here is <<<<<<<<<<<<<<
    Alg.Alias.AlgorithmParameters.1.2.840.113549.1.12.1.3
    SecretKeyFactory.Hmac
    AlgorithmParameters.PBEWithMD5AndDES
    Alg.Alias.SecretKeyFactory.1.2.840.113549.1.12.1.6
    AlgorithmParameterGenerator.RC6
    Alg.Alias.Cipher.PBEwithSHA-1andDES-CBC
    AlgorithmParameterGenerator.RC5
    Cipher.ElGamal
    SecureRandom.BBSRandom
    Alg.Alias.Cipher.1.2.840.113549.3.2
    Alg.Alias.AlgorithmParameters.1.2.840.113549.1.5.13
    Alg.Alias.AlgorithmParameters.1.2.840.113549.1.5.12
    Alg.Alias.MessageDigest.SHA-1
    AlgorithmParameterGenerator.TWOFISH
    Cipher.IDEA
    Alg.Alias.Cipher.1.2.840.113549.1.1.1
    AlgorithmParameterGenerator.RIJNDAEL
    Alg.Alias.Signature.1.2.840.113549.1.1.5
    Alg.Alias.AlgorithmParameters.1.3.14.3.2.12
    Alg.Alias.Signature.1.2.840.113549.1.1.4
    and so on.
    but it doesn't work in -cipher.getInstance()-
    I will try bouncycastle as you recommended, thanks again.

  • How to sign the data with DHPrivateKey

    I am testing DH key exchange protocol. When I run the following code, it works.
    import java.io.*;
    import java.math.BigInteger;
    public class DH2 {
        private DH2() {}
        public static void main(String argv[]) {
            try {
                String mode = "USE_SKIP_DH_PARAMS";
                DH2 keyAgree = new DH2();
                if (argv.length > 1) {
                    keyAgree.usage();
                    throw new Exception("Wrong number of command options");
                } else if (argv.length == 1) {
                    if (!(argv[0].equals("-gen"))) {
                        keyAgree.usage();
                        throw new Exception("Unrecognized flag: " + argv[0]);
                    mode = "GENERATE_DH_PARAMS";
                keyAgree.run(mode);
            } catch (Exception e) {
                System.err.println("Error: " + e);
                System.exit(1);
        private void run(String mode) throws Exception {
            DHParameterSpec dhSkipParamSpec;
            if (mode.equals("GENERATE_DH_PARAMS")) {
                // Some central authority creates new DH parameters
                System.out.println
                    ("Creating Diffie-Hellman parameters (takes VERY long) ...");
                AlgorithmParameterGenerator paramGen
                    = AlgorithmParameterGenerator.getInstance("DH");
                paramGen.init(512);
                AlgorithmParameters params = paramGen.generateParameters();
                dhSkipParamSpec = (DHParameterSpec)params.getParameterSpec
                    (DHParameterSpec.class);
            } else {
                // use some pre-generated, default DH parameters
                System.out.println("Using SKIP Diffie-Hellman parameters");
                dhSkipParamSpec = new DHParameterSpec(skip1024Modulus,
                                                      skip1024Base);
            System.out.println("ALICE: Generate DH keypair ...");
            KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
            aliceKpairGen.initialize(dhSkipParamSpec);
            KeyPair aliceKpair = aliceKpairGen.generateKeyPair();
            System.out.println("ALICE: Initialization ...");
            KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH");
            aliceKeyAgree.init(aliceKpair.getPrivate());
            byte[] alicePubKeyEnc = aliceKpair.getPublic().getEncoded();
            KeyFactory bobKeyFac = KeyFactory.getInstance("DH");
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec
                (alicePubKeyEnc);
            PublicKey alicePubKey = bobKeyFac.generatePublic(x509KeySpec);
            DHParameterSpec dhParamSpec = ((DHPublicKey)alicePubKey).getParams();
            System.out.println("BOB: Generate DH keypair ...");
            KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
            bobKpairGen.initialize(dhParamSpec);
            KeyPair bobKpair = bobKpairGen.generateKeyPair();
            System.out.println("BOB: Initialization ...");
            KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH");
            bobKeyAgree.init(bobKpair.getPrivate());
            byte[] bobPubKeyEnc = bobKpair.getPublic().getEncoded();
            KeyFactory aliceKeyFac = KeyFactory.getInstance("DH");
            x509KeySpec = new X509EncodedKeySpec(bobPubKeyEnc);
            PublicKey bobPubKey = aliceKeyFac.generatePublic(x509KeySpec);
            System.out.println("ALICE: Execute PHASE1 ...");
            aliceKeyAgree.doPhase(bobPubKey, true);
            System.out.println("BOB: Execute PHASE1 ...");
            bobKeyAgree.doPhase(alicePubKey, true);
            byte[] aliceSharedSecret = aliceKeyAgree.generateSecret();
            int aliceLen = aliceSharedSecret.length;
            byte[] bobSharedSecret = new byte[aliceLen];
            int bobLen;
            try {
                bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 1);
            } catch (ShortBufferException e) {
                System.out.println(e.getMessage());
            bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 0);
            System.out.println("Alice secret: " +
              toHexString(aliceSharedSecret));
            System.out.println("Bob secret: " +
              toHexString(bobSharedSecret));
            if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret))
                throw new Exception("Shared secrets differ");
            System.out.println("Shared secrets are the same");
            System.out.println("Return shared secret as SecretKey object ...");
            bobKeyAgree.doPhase(alicePubKey, true);
            SecretKey bobDesKey = bobKeyAgree.generateSecret("DES");
            aliceKeyAgree.doPhase(bobPubKey, true);
            SecretKey aliceDesKey = aliceKeyAgree.generateSecret("DES");
            Cipher bobCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            bobCipher.init(Cipher.ENCRYPT_MODE, bobDesKey);
            byte[] cleartext = "This is just an example".getBytes();
    //        Signature signature = Signature.getInstance("SHA1withDSA");
    //        signature.initSign(bobKpair.getPrivate());
    //        signature.update(cleartext);
    //        byte[] data = signature.sign();
            byte[] ciphertext = bobCipher.doFinal(cleartext);
            Cipher aliceCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            aliceCipher.init(Cipher.DECRYPT_MODE, aliceDesKey);
            byte[] recovered = aliceCipher.doFinal(ciphertext);
            if (!java.util.Arrays.equals(cleartext, recovered))
                throw new Exception("DES in CBC mode recovered text is " +
                  "different from cleartext");
            System.out.println("DES in ECB mode recovered text is " +
                "same as cleartext");
            bobCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            bobCipher.init(Cipher.ENCRYPT_MODE, bobDesKey);
            cleartext = "This is just an example".getBytes();
            ciphertext = bobCipher.doFinal(cleartext);
            byte[] encodedParams = bobCipher.getParameters().getEncoded();
            AlgorithmParameters params = AlgorithmParameters.getInstance("DES");
            params.init(encodedParams);
            aliceCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            aliceCipher.init(Cipher.DECRYPT_MODE, aliceDesKey, params);
            recovered = aliceCipher.doFinal(ciphertext);
            if (!java.util.Arrays.equals(cleartext, recovered))
                throw new Exception("DES in CBC mode recovered text is " +
                  "different from cleartext");
            System.out.println("DES in CBC mode recovered text is " +
                "same as cleartext");
    }I want to sign the data with Signature,So i add the following code to the sample.
            byte[] cleartext = "This is just an example".getBytes();
         Signature signature = Signature.getInstance("SHA1withDSA");
            signature.initSign(bobKpair.getPrivate());
            signature.update(cleartext);
            byte[] data = signature.sign();
            byte[] ciphertext = bobCipher.doFinal(cleartext);Run the code again, the output is
    Error: java.security.InvalidKeyException: No installed provider supports this key: com.sun.crypto.provider.DHPrivateKey
    What's wrong with the code, It seems that the bob's private key is not instance of DSAPrivateKey but DHPrivateKey.
    what's your comment? thanks a lot.

    slamdunkming wrote:
    thank sabre150 for your reply. But the key pair is generated when I use DH to exchange the secret key. Yes! It is a DH key pair and cannot be used for signing. The DH key pair can only be used for secret sharing.
    If I can not use this private key to sign the data, what can i do?Do I have to generate another key pair for signature? In that way, I will have two key pair. Yep. You can generate a DSA or an RSA key pair to be used for signing.
    Because I use http protocol to exchange the key to get the shared secret key, Yep.
    If I generate another key pair, how can i send the public key to server? Since public keys are 'public' then you can send them in the open to anyone you like. In fact, if you don't publish your public keys then they are pretty much a waste of time. The biggest problem one has with public key is proving 'ownership' - if someone sends me a public key how do I know that the sender is actually who they say they are?.
    I am confused.Some reading might help. A pretty good starting point is "Beginning Cryptography with Java" by David Hook published by Wrox.

  • Javax.crypto.BadPaddingException

    Hi there,
    java gurus could you please provide me at least one well format answer why does it happen. I have checked out the forum and I would say that there are many work around answers, but nothing usefull. So my problem is:
    I'm trying to execute the same application twice
    first time the sequence of operations is following encrypt the string and then decrypt result of previous operation and execution is OK!
    [af@juja db2file]$ java -classpath db2file.jar Crypter e a1a2a3a4
    97 49 97 50 97 51 97 52
    -39 -23 5 45 88 70 -57 -38 -124 -38 -111 -102 -61 106 0 -104
    -39 -23 5 45 88 70 -57 -38 -124 -38 -111 -102 -61 106 0 -104
    97 49 97 50 97 51 97 52
    Result e: 2ekFLVhGx9qE2pGaw2oAmA==; 24
    Result d: a1a2a3a4; 8
    second time the sequence of operations is following decrypt result of previous execution and execution isn't OK! at all
    [af@juja db2file]$ java -classpath db2file.jar Crypter d 2ekFLVhGx9qE2pGaw2oAmA==
    -39 -23 5 45 88 70 -57 -38 -124 -38 -111 -102 -61 106 0 -104
    javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.SunJCE_h.b(DashoA6275)
    at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA6275)
    at javax.crypto.Cipher.doFinal(DashoA6275)
    at com.net2s.mobistar.util.Crypter.decrypt(Crypter.java:66)
    at com.net2s.mobistar.util.Crypter.main(Crypter.java:85)
    Result e: 2ekFLVhGx9qE2pGaw2oAmA==; 24
    Result d: ; 0
    As you can see the number of the bytes and its value are the same.
    That is the code:
    import java.security.Key;
    import java.security.Provider;
    import java.security.Security;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    import javax.crypto.*;
    public class Crypter {
    private static Crypter crypter;
    private Cipher cipher;
    private Key key;
    private Crypter() {
    try {
    Security.addProvider(new com.sun.crypto.provider.SunJCE());
    key = KeyGenerator.getInstance("DES","SunJCE").generateKey();
    cipher = Cipher.getInstance("DES");
    } catch (Exception ex) {
    ex.printStackTrace();
    public static Crypter getDefault() {
    if(crypter == null) {
    crypter = new Crypter();
    return crypter;
    public String encrypt(String str) {
    String result = "";
    try {
    cipher.init(Cipher.ENCRYPT_MODE,key);
    byte[] utf8 = str.getBytes("UTF8");
    printBytes(utf8);
    byte[] enc = cipher.doFinal(utf8);
    printBytes(enc);
    result = new sun.misc.BASE64Encoder().encode(enc);
    } catch (Exception ex) {
    ex.printStackTrace();
    return result;
    public String decrypt(String str) {
    String result = "";
    try {
    cipher.init(Cipher.DECRYPT_MODE,key);
    byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
    printBytes(dec);
    byte[] utf8 = cipher.doFinal(dec);
    printBytes(utf8);
    result = new String(utf8,"UTF8");
    } catch (Exception ex) {
    ex.printStackTrace();
    return result;
    public static void main(String[] args) {
    String e = "";
    String d = "";
    if(args[0].equals("e")) {
    e = Crypter.getDefault().encrypt(args[1]);
    d = Crypter.getDefault().decrypt(e);
    System.out.println("Result e: " + e + "; " + e.length());
    System.out.println("Result d: " + d + "; " + d.length());
    } else {
    e = args[1];
    d = Crypter.getDefault().decrypt(e);
    System.out.println("Result e: " + e + "; " + e.length());
    System.out.println("Result d: " + d + "; " + d.length());
    private void printBytes(byte[] toPrint) {
    for(int i = 0;i < toPrint.length;i++) {
    System.out.print(toPrint);
    System.out.print(" ");
    System.out.println("");
    Enjoy!

    I am getting the same BadPaddingException when using (what I thought was the same key on different versions of the JDK. The original code is not mine, I would not have tried to get fancy with seed generation, but opted for secure key storage. Anyway, this code works on one verion of the JDK, but not another. I now assume, after reading these posts, that the SecureRandom has changed so that a different key is being generated. Is this correct, or am I doing something else wrong?
    -C
    public class SimpleDESEncryption {
         final static String PNRG_ALGORITHM = "SHA1PRNG";
         final static String KEYGEN_ALGORITHM = "DESede";
         final static String CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";
         final static String STRING_FORMAT = "UTF-16";
         final static String PROVIDER = "com.sun.crypto.provider.SunJCE";
         static {
              try {
                   Security.addProvider((Provider) Class.forName(PROVIDER).newInstance());
              catch(Exception e) {
          * C'tor
         private SimpleDESEncryption() {
          * Static, reentrant method to encrypt a given string using the specified key.
          * @param key The Stringified long value used for PRNG seeds.
          * @param raw The String to encrypt.
          * @return Base64 encoded version of encrypted text.
          * @throws PaygovSystemException if a system exception occurs
          * @throws PaygovException if a known expected error occurs
         public static String encrypt(String key, String raw) throws PaygovSystemException, PaygovException {
              Cipher cipher = null;
              String  encryptedString = null;
              String encodedString =  null;
              if(raw == null || raw.length() == 0) {
                   // Nothing to encrypt
                   return raw;
              try {
                   // Instantiate and initialize the cipher
                   long longKey = Long.parseLong(key);
                   SecretKey secretKey = deriveSecretKey(longKey);
                   cipher = Cipher.getInstance(CIPHER_ALGORITHM);
                   cipher.init(Cipher.ENCRYPT_MODE, secretKey);
                   // Encrypt and Base64 encode the data
                   BASE64Encoder  encoder = new BASE64Encoder();
                   byte[] clearBfr = raw.getBytes(STRING_FORMAT);
                   byte[] cipherBfr = cipher.doFinal(clearBfr);
                   encodedString = encoder.encodeBuffer(cipherBfr);
                   return(encodedString);
              catch(java.security.InvalidKeyException err) {
                   throw new PaygovSystemException(err);
              catch(javax.crypto.NoSuchPaddingException err) {
                   throw new PaygovSystemException(err);
              catch(java.security.NoSuchAlgorithmException err) {
                   throw new PaygovSystemException(err);
              catch(java.io.UnsupportedEncodingException err) {
                   throw new PaygovSystemException(err);
              catch(javax.crypto.IllegalBlockSizeException err) {
                   throw new PaygovSystemException(err);
              catch(javax.crypto.BadPaddingException err) {
                   throw new PaygovSystemException(err);
          * Static, reentrant method to decrypt a given string using the specified key
          * @param key The Stringified long value used for <code>PRNG</code> seeds.
          * @param encryptedDataString The Base64 encoded <code>String</code> to decrypt.
          * @return Base64 encoded version of encrypted text.
          * @throws PaygovSystemException if a system exception occurs
          * @throws PaygovException if a known expected error occurs
         public static String decrypt(String  key, String encryptedDataString) throws PaygovSystemException, PaygovException
              Cipher cipher = null;
              String decryptedString = null;
              String decodedString = null;
              if(encryptedDataString == null || encryptedDataString.length() == 0) {
                   // Nothing to decrypt
                   return encryptedDataString;
              // Instantiate and initialize the cipher
              try {
                   // Instantiate and initialize the cipher
                   long longKey = Long.parseLong(key);
                   SecretKey secretKey = deriveSecretKey(longKey);
                   cipher = Cipher.getInstance(CIPHER_ALGORITHM);
                   cipher.init(Cipher.DECRYPT_MODE, secretKey);
                   BASE64Decoder decoder = new BASE64Decoder();
                   byte[] decodedBfr = decoder.decodeBuffer(encryptedDataString);
                   byte[] decryptedBfr = cipher.doFinal(decodedBfr);
                   decryptedString = new String(decryptedBfr, STRING_FORMAT);
                   return(decryptedString);
              catch(javax.crypto.BadPaddingException err) {
                   err.printStackTrace();
                   throw new PaygovException(err);
              catch(java.security.InvalidKeyException err) {
                   throw new PaygovException(err);
              catch(javax.crypto.IllegalBlockSizeException err) {
                   throw new PaygovException(err);
              catch(javax.crypto.NoSuchPaddingException err) {
                   throw new PaygovSystemException(err);
              catch(java.security.NoSuchAlgorithmException err) {
                   throw new PaygovSystemException(err);
              catch(java.io.IOException err) {
                   throw new PaygovSystemException(err);
          * Get the private key
         private static SecretKey deriveSecretKey(long key) throws PaygovSystemException {
              SecureRandom prng = null;
              KeyGenerator keyGen = null;
              SecretKey secretKey = null;
              try {
                   prng = SecureRandom.getInstance(PNRG_ALGORITHM);
                   prng.setSeed(twiddle(key));
                   // get the key generator
                   keyGen = KeyGenerator.getInstance(KEYGEN_ALGORITHM, "SunJCE");
                   // initialize it with _our_ carefuly seeded PRNG
                   keyGen.init(prng);
                   //  Get the key
                   secretKey = keyGen.generateKey();
              catch(java.security.NoSuchAlgorithmException err) {
                   throw new PaygovSystemException(err);
              catch(java.security.NoSuchProviderException err) {
                   throw new PaygovSystemException(err);
              return(secretKey);
         private static long twiddle(long key) {
              long twiddleBytes = (key % 8) << 3;
              return(key ^ twiddleBytes);
          * For testing different versions of the JDK. Tests encryption and decryption within
          * the VM and also saves encrypted text to a file and tries to decrypt it on the next
          * pass so that it can be run first with one version and then again with a different
          * version to ensure that the algorithm, padding, and decoding work consistently.
         public static void main(String[] args) {
              //Define our static key for testing
              String key = "1524567842321251673";
              String clearText = "Mary had a little lamb";
              String readText = null;
              String encryptedText = null;
              File outputFile = new File("encryptiontest.txt");
              try {
                   //Encrypt cleartext
                   encryptedText = SimpleDESEncryption.encrypt(key, clearText);
                   //Test in memory decryption
                   if(! SimpleDESEncryption.decrypt(key, encryptedText).equals(clearText)) {
                        System.out.println("In memory decryption failed. Exitting.");
                        return;
                   System.out.println("In memory decryption passed.");
                   //Check if saved output file exists
                   if(outputFile.exists()) {
                        System.out.println("Checking file from last run.");
                        FileInputStream fis = null;
                        try {
                             fis = new FileInputStream(outputFile);
                             LineNumberReader lineNumberReader = new LineNumberReader(new InputStreamReader(fis));
                             readText = lineNumberReader.readLine();
                             fis.close();
                        catch(IOException ioe) {
                             System.out.println("Error reading test file. Exitting.");
                             return;
                        //Test cross invocation decryption
                        if(! SimpleDESEncryption.decrypt(key, readText).equals(clearText)) {
                             System.out.println("Decrypted file test failed. Exitting.");
                             return;
                        System.out.println("File decryption passed.");
              catch(Exception pgse) {
                   System.out.println("Exception occured: " + pgse);
                   pgse.printStackTrace();
                   return;
              //Save the encrypted text from this run.
              PrintStream printStream = null;
              try {
                   System.out.println("Saving file for next run.");
                   printStream = new PrintStream(new FileOutputStream(outputFile));
                   printStream.println(encryptedText);
                   printStream.close();
              catch(IOException ioe) {
                   System.out.println("Error writing test file. Exitting.");
                   return;
              System.out.println("Test complete.");

  • Javax.crypto.BadPaddingException: unknown block type - URGENT

    I am trying to encryp-decrypt a file (serialized xml file ) using BC provider with RSA algorithm and PKCS1Padding padding..
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC")
    Sequence of action is encrypt - base64encode -
    base64decode - decrypt.
    Encryption seems to be working fine but while decrypting it gives the error mentioned below:
    javax.crypto.BadPaddingException: unknown block type
    I tried using OAEPPadding - In that scenario I get this error
    javax.crypto.BadPaddingException: data hash wrong
    I tried searching the cause and resolution of the problems on various resources on net but in vain. Need it urgently. PLS HELP. THANKS
    I am pasting my code below :
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.security.Key;
    import java.security.KeyFactory;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.NoSuchAlgorithmException;
    import java.security.NoSuchProviderException;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.Security;
    import java.security.spec.EncodedKeySpec;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    import javax.crypto.Cipher;
    import org.apache.log4j.Logger;
    import org.bouncycastle.jce.provider.*;
    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;
    public class EncryptBase64File
    protected static final String ALGORITHM = "RSA";
         private static Logger logger = Logger.getLogger(EncryptFiles.class.getClass());
    private EncryptBase64File()
    * Init java security to add BouncyCastle as an RSA provider
    public static void init()
    Security.addProvider(new BouncyCastleProvider());
    * Generate key which contains a pair of privae and public key using 1024 bytes
    * @return key pair
    * @throws NoSuchAlgorithmException
    public static KeyPair generateKey() throws NoSuchProviderException,NoSuchAlgorithmException
    //KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
              KeyPairGenerator keyGen =
                                  KeyPairGenerator.getInstance("RSA", "BC");
    keyGen.initialize(1024);
    KeyPair key = keyGen.generateKeyPair();
    return key;
    * Encrypt a text using public key.
    * @param text The original unencrypted text
    * @param key The public key
    * @return Encrypted text
    * @throws java.lang.Exception
    public static byte[] encrypt(byte[] text, PublicKey key) throws Exception
    byte[] cipherText = null;
    try
    // get an RSA cipher object and print the provider
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
                   //Cipher cipher = Cipher.getInstance("RSA");
                   System.out.println("\nProvider is: " + cipher.getProvider().getInfo());
                   System.out.println("\nStart encryption with public key");
    if (logger.isDebugEnabled())
                        logger.debug("\nProvider is: " + cipher.getProvider().getInfo());
                        logger.debug("\nStart encryption with public key");
    // encrypt the plaintext using the public key
    cipher.init(Cipher.ENCRYPT_MODE, key);
    cipherText = cipher.doFinal(text);
    catch (Exception e)
                   logger.error(e, e);
    throw e;
    return cipherText;
    * Encrypt a text using public key. The result is enctypted BASE64 encoded text
    * @param text The original unencrypted text
    * @param key The public key
    * @return Encrypted text encoded as BASE64
    * @throws java.lang.Exception
    public static String encrypt(String text, PublicKey key) throws Exception
    String encryptedText;
    try
    byte[] cipherText = encrypt(text.getBytes("UTF8"),key);
    encryptedText = encodeBASE64(cipherText);
                   System.out.println("Enctypted text is: " + encryptedText);
                   logger.debug("Enctypted text is: " + encryptedText);
    catch (Exception e)
                   logger.error(e, e);
    throw e;
    return encryptedText;
    * Decrypt text using private key
    * @param text The encrypted text
    * @param key The private key
    * @return The unencrypted text
    * @throws java.lang.Exception
    public static byte[] decrypt(byte[] text, PrivateKey key) throws Exception
    byte[] dectyptedText = null;
    try
    // decrypt the text using the private key
    //Cipher cipher = Cipher.getInstance("RSA/CBC/PKCS1Padding","BC");
                   Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
                   //Cipher cipher = Cipher.getInstance("RSA");
                   logger.debug("Start decryption");
                   System.out.println("Start decryption");
    cipher.init(Cipher.DECRYPT_MODE, key);
    dectyptedText = cipher.doFinal(text);
    catch (Exception e)
                   logger.error(e, e);
    throw e;
    return dectyptedText;
    * Decrypt BASE64 encoded text using private key
    * @param text The encrypted text, encoded as BASE64
    * @param key The private key
    * @return The unencrypted text encoded as UTF8
    * @throws java.lang.Exception
    public static String decrypt(String text, PrivateKey key) throws Exception
    String result;
    try
    // decrypt the text using the private key
    byte[] dectyptedText = decrypt(decodeBASE64(text),key);
    result = new String(dectyptedText, "UTF8");
                   logger.debug("Decrypted text is: " + result);
    catch (Exception e)
                   logger.error(e, e);
    throw e;
    return result;
    * Encode bytes array to BASE64 string
    * @param bytes
    * @return Encoded string
    private static String encodeBASE64(byte[] bytes)
    BASE64Encoder b64 = new BASE64Encoder();
    return b64.encode(bytes);
    * Decode BASE64 encoded string to bytes array
    * @param text The string
    * @return Bytes array
    * @throws IOException
    private static byte[] decodeBASE64(String text) throws IOException
    BASE64Decoder b64 = new BASE64Decoder();
    return b64.decodeBuffer(text);
    * Encrypt file using 1024 RSA encryption
    * @param srcFileName Source file name
    * @param destFileName Destination file name
    * @param key The key. For encryption this is the Private Key and for decryption this is the public key
    * @param cipherMode Cipher Mode
    * @throws Exception
    public static void encryptFile(String srcFileName, String destFileName, PublicKey key) throws Exception
    encryptDecryptFile(srcFileName,destFileName, key, Cipher.ENCRYPT_MODE);
    * Decrypt file using 1024 RSA encryption
    * @param srcFileName Source file name
    * @param destFileName Destination file name
    * @param key The key. For encryption this is the Private Key and for decryption this is the public key
    * @param cipherMode Cipher Mode
    * @throws Exception
    public static void decryptFile(String srcFileName, String destFileName, PrivateKey key) throws Exception
    encryptDecryptFile(srcFileName,destFileName, key, Cipher.DECRYPT_MODE);
    * Encrypt and Decrypt files using 1024 RSA encryption
    * @param srcFileName Source file name
    * @param destFileName Destination file name
    * @param key The key. For encryption this is the Private Key and for decryption this is the public key
    * @param cipherMode Cipher Mode
    * @throws Exception
    public static void encryptDecryptFile(String srcFileName, String destFileName, Key key, int cipherMode) throws Exception
    OutputStream outputWriter = null;
    InputStream inputReader = null;
    try
              Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    String textLine = null;
    byte[] buf = cipherMode == Cipher.ENCRYPT_MODE? new byte[100] : new byte[128];
    int newBuffer;
    // init the Cipher object for Encryption...
    cipher.init(cipherMode, key);
    // start FileIO
    outputWriter = new FileOutputStream(destFileName);
    inputReader = new FileInputStream(srcFileName);
    while ( (bufl = inputReader.read(buf)) != -1)
    String encText = null;
    String base64EncText = null ;
    if (cipherMode == Cipher.ENCRYPT_MODE)
    encText = encrypt(getBytes(buf,newBuffer).toString(),(PublicKey)key);
    else
    encText = decrypt(getBytes(buf,newBuffer).toString(),(PrivateKey)key);
                   outputWriter.write(encText.getBytes());
    outputWriter.flush();
    catch (Exception e)
                   logger.error(e,e);
    throw e;
    finally
    try
    if (outputWriter != null)
    outputWriter.close();
    if (inputReader != null)
    inputReader.close();
    catch (Exception e)
    public static byte[] getBytes(byte[] arr, int length)
    byte[] newArr = null;
    if (arr.length == length)
    newArr = arr;
    else
    newArr = new byte[length];
    for (int i = 0; i < length; i++)
    newArr[i] = (byte) arr;
    return newArr;
         public static void main(String args[])
              throws Exception
              init();
              KeyPair keyPair = generateKey();
              PublicKey pubKey = keyPair.getPublic();
              PrivateKey privKey = keyPair.getPrivate();
              encryptFile("C:\\Temp\\TestFile.xml","C:\\Temp\\RSAEncryptedText.xml",pubKey);
              decryptFile("C:\\Temp\\RSAEncryptedText.xml","C:\\Temp\\RSADecryptedText.xml",privKey);

    I think you are the same poster as 'contebral'. Why the multiple identities?
    First off, the code you posted doesn't even compile. The getBytes() method has an error. Also, in method encryptDecryptFile() the variable bufl is not declared.
    The rest of the code is a mess. The toString() method does not do what you think it does; you're just going to get the object reference id. There is no reason to keep converting to/from byte arrays and Strings. Most of the time your data should be kept as a byte array, only possibly converting for I/O operations.
    The size of the base64 encoded output is not 128 bytes, it is 172 bytes. At this point I ran out of patience and stopped looking.
    There is no shame in being a beginner in Java, but you must walk before you can run. Stop running.

  • Encrypting 16 bytes to 16 bytes

    I need to encrypt a byte[16] using AES and get another byte[16]. But the following code computes a byte[32]. I understand that is happens because of the usage of 16 bytes blocks and the necessity to keep track of the input length, But in this application I know that the input length is always exactly 16 bytes, so a 16 bytes output can be computed. But how?
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    public class AaesDemo {
        public static void main(String[] args) throws Exception {
            final String alg = "AES";
            final byte[] original = new byte[16];
            final byte[] passPhrase0 = new byte[16];
            final Cipher cipher0 = Cipher.getInstance(alg);
            final SecretKey key0 = new SecretKeySpec(passPhrase0, alg);
            cipher0.init(Cipher.ENCRYPT_MODE, key0);
            final byte[] encoded = cipher0.doFinal(original);
            System.out.println(encoded.length);
    }

    It does not work:
    Exception in thread "main" java.security.InvalidKeyException: Wrong algorithm: AES or Rijndael required
         at com.sun.crypto.provider.SunJCE_f.a(DashoA14*..)
         at com.sun.crypto.provider.SunJCE_j.a(DashoA14*..)
         at com.sun.crypto.provider.SunJCE_i.a(DashoA14*..)
         at com.sun.crypto.provider.SunJCE_i.a(DashoA14*..)
         at com.sun.crypto.provider.AESCipher.engineInit(DashoA14*..)
         at javax.crypto.Cipher.a(DashoA14*..)
         at javax.crypto.Cipher.a(DashoA14*..)
         at javax.crypto.Cipher.init(DashoA14*..)
         at javax.crypto.Cipher.init(DashoA14*..)
    ...

Maybe you are looking for

  • Infotype 0057 - Invisible fields - Check on amount/number

    Hi guys, I am using the infotype 57 to use the field P0057-MGART only. So in the table V_T588M I have put all the other fields in invisible mode. Anyway, a check is still activated: when I try to save a new record, I have the error message "Enter amo

  • Swapping values in an array of type Node

    I have a simple class called Node that is storing integers and from this class I am creating an array: public class Node { private int iData; public Node(int key) iData = key; public int getKey() { return iData; public void setKey(int id) { iData = i

  • Re: Using simple java class in an .war file.

    Hi All, I have a simple question, Can I access an simple java class from a jsp file that I have written by putting it in the "classes" folder?? What entry should go in the web.xml file? Here is my directory structure: sample.war | ----test.jsp <file>

  • I cannot download Photoshop CS6 from the cloud

    I had a beta version of Photoshop CS6 on my Macbook (OS X 10.7.4) and forgot to uninstall it before downloading Photoshop CS6 through the Adobe Application Manager. When I tried to download Photoshop CS6 I received an error message in the Adobe Appli

  • Is DVD Studio Pro faster than iDVD?

    Sorry I'm double posting this but I didn't get my question in the Subject line. Is DVDSP faster than iDVD? If so, by how much? I'm on the endless quest for more speed.