Javax.crypto .. NoSuchAlgorithmException

import javax.crypto.Cipher;
public class CipherClass
public static void main(String[] args)
Cipher c=Cipher.getInstance("DES");
Compiling this file gives me a java.security.NoSuchAlgorithmException. Kindly guide me. I'm using jdk 1.6.

Hi,
now i am getting foolowing exception,after making small changes to above program can anyone help me in finding out what does it mean?
Exception in thread "main" java.lang.ExceptionInInitializerError
at javax.crypto.KeyGenerator.getInstance(DashoA6275)
at AAACreateKey.doIt(waste.java:17)
at waste.main(waste.java:27)
Caused by: java.lang.SecurityException: Cannot set up certs for trusted CAs
at javax.crypto.SunJCE_b.<clinit>(DashoA6275)
... 3 more
Caused by: java.security.PrivilegedActionException: java.security.cert.CertificateException: X.509 not fo
und
at java.security.AccessController.doPrivileged(Native Method)
... 4 more
Caused by: java.security.cert.CertificateException: X.509 not found
at java.security.cert.CertificateFactory.getInstance(CertificateFactory.java:191)
at javax.crypto.SunJCE_b.b(DashoA6275)
at javax.crypto.SunJCE_b.a(DashoA6275)
at javax.crypto.SunJCE_v.run(DashoA6275)
... 5 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:324)
at java.security.cert.CertificateFactory.getInstance(CertificateFactory.java:177)
... 8 more
Caused by: java.security.NoSuchAlgorithmException: X.509 CertificateFactory not available
at java.security.Security.getEngineClassName(Security.java:583)
at java.security.Security.getEngineClassName(Security.java:594)
at java.security.Security.getImpl(Security.java:1043)
... 13 more

Similar Messages

  • Using javax.crypto in oracle 10g

    Hi,
    I have a java stored procedure for oracle 10g (running jdk1.4) that
    uses the javax.crypto package and the bouncy castle provider for RSA
    decryption. Here is a snippet of the code in the procedure:
    Security.addProvider(new
    org.bouncycastle.jce.provider.BouncyCastleProvider());
    Cipher rsaCipher = Cipher.getInstance("RSA");
    RSAPrivateKey key = (RSAPrivateKey)
    MSPrivKeytoJKey.getPrivateKey(aKey);
    rsaCipher.init(Cipher.DECRYPT_MODE, key);
    rsaCipher.doFinal(encryptedByteArray);
    This works fine on my own machine running jdk1.4. However, when I load
    my stored procedure into the database and run it, I get the following
    exception after the line
    Cipher rsaCipher = Cipher.getInstance("RSA");
    tries to execute:
    java.security.NoSuchAlgorithmException: Cannot find any provider
    supporting RSA
    I have tried the following (based on information gathered from various
    forums):
    - ran
    loadjava -u username/pass@DB -v bcprov-jdk14-137.jar
    - added the following line to java.security
    security.provider.4=org.bouncycastle.jce.provider.BouncyCastleProvider
    but i still get the same error.
    I am reaching out desperately to all you experts for help :)
    Pouria

    Hi,
    Unfortunately, the Java VM only supports the basic JDK functionalities; you could try the Metalink Note 356123.1 which should work using BC library but this note only addresses AES.
    Furthermore, you need the following two extra permissions:
    exec dbms_java.grant_permission('SCOTT', 'SYS:java.security.SecurityPermission','putProviderProperty.BC', '' );
    exec dbms_java.grant_permission( 'SCOTT', 'SYS:java.security.SecurityPermission','insertProvider.BC', '' );
    Oboviously SCOTT would be changed to whichever schema you are using.
    Kuassi http://db360.blogspot.com

  • Issue with javax.crypto.SecretFactory

    I am getting the following error in the following code:
    DESedeKeySpec spec = new DESedeKeySpec( baKey );
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstanc( "DESede" );
    Here is the error message:
    java.security.NoSuchAlgorithmException: Algorithm DESede not available
         at javax.crypto.SunJCE_b.a(DashoA6275)
         at javax.crypto.SecretKeyFactory.getInstance(DashoA6275)
    I will really appreciate any help.

    Looks like it has something to do with the jdk installed on my machine. I changed the location of jdk and I get the following error:
    javax.crypto.BadPaddingException: Given final block not properly padded
         at com.sun.crypto.provider.DESedeCipher.engineDoFinal(DashoA6275)
         at com.sun.crypto.provider.DESedeCipher.engineDoFinal(DashoA6275)
         at javax.crypto.Cipher.doFinal(DashoA6275)

  • AES -javax.crypto.BadPaddingException: Given final block notproperly padded

    I have an Encrypt Util class to encrypt and decrypt CLOB content in the database(Oracle). During encryption there is no error/exception thrown., But while decryption it throws the exception javax.crypto.BadPaddingException: Given final block notproperly padded.
    The error is thrown only for selected records, not for all. For most of them it works fine. I use 256 bit AES Encryption.The sequence of steps to generate and retrieve the key is as follows:
    (Generating and Storing the Key)
    Generate original Key Using JCE --> Then XOR it with a known String (Key) --> Write to a file in DB Server (Solaris 10) using a Stored Procedure.
    (Retrieving the Key)
    Read the key file using s Stored Procedure --> XOR it with known String(Key) --> Retrieve the original Key
    The decryption works fine for most of the records (70%) but failing 30% of the time. There is no exception in the way the encrypted content gets stored in the db
    The key is generated as a one time step in the application and stored in the file. It is retrieved and cached in the application once, everytime the appserver is restarted.
    Could someone pls. help?
    Attaching below (1) code snippet for generating the key and (2) The code snipped to retrieve the key (3) the class which does the encryption and decryption of data
    (1) code snippet for generating the key
    String xorRefKey = "*&^%$#@!AiMsKey!*&^%$#@!AiMsKey!";
    KeyGenerator kg = KeyGenerator.getInstance("AES");
                kg.init(256);
                String initialKey = new String (kg.generateKey().getEncoded());
             char[] refArr =  xorRefKey.toCharArray();
              char[] initKeyArr = initialKey.toCharArray();
                char[] finalKeyArr = new char[refArr.length];
                 for(int i=0;i<initKeyArr.length;i++){
                     finalKeyArr= (char)(initKeyArr[i] ^ refArr[i]);
    String finalKey = new String(finalKeyArr);----------------------
    (2) The code snipped to retrieve the keyString xorRefKey = "*&^%$#@!AiMsKey!*&^%$#@!AiMsKey!";
    char[] refArr = xorRefKey.toCharArray();
    //initialKey is the key read from the file using a db call
    char[] initKeyArr = initialKey.toCharArray();
    char[] finalKeyArr = new char[refArr.length];
    for(int i=0;i<initKeyArr.length;i++){
    finalKeyArr[i]= (char)(initKeyArr[i] ^ refArr[i]);
    String finalKey= new String(finalKeyArr);
    Class to encrypt/decrypt
    (3) EncryptUtil classpublic class EncryptUtil {
    private static SecretKeySpec skeySpec = null;
    private static final String encryptionAlgorithm = "AES";
    private static IGOLogger logger = IGOLogger.getInstance(IGOLogger.ENCRYPTION);
    private static final String UNICODE_FORMAT = "UTF8";
    private Cipher cipher = null;
    public EncryptUtil(String key){
    String lFuncName = "EncryptUtil :: EncryptUtil(): ";
    try{
    cipher = Cipher.getInstance(encryptionAlgorithm);
    skeySpec = new SecretKeySpec(key.getBytes(), encryptionAlgorithm);
    } catch (NoSuchAlgorithmException e) {
    logger.error(lFuncName + "No Such Algorithm Error while creating Cipher and KeySpec ",e);
    } catch (NoSuchPaddingException e) {
    logger.error(lFuncName + "No Such Padding Error while creating Cipher and KeySpec ",e);
    * Encrypts the data based on the key and algorithm
    * @param data
    * @return encrypted data
    public String encrypt(String data){
    String lFuncName = "EncryptUil :: encrypt(): ";
    byte[] encryptedData = null;
    String encryptedFinal = "";
    try{
    if(data!=null && data.length()>0){
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec,cipher.getParameters());
    encryptedData = (cipher.doFinal(data.getBytes(UNICODE_FORMAT)));
    encryptedFinal = new BASE64Encoder().encode(encryptedData);
    } catch (InvalidKeyException e) {
    logger.error(lFuncName + "Invalid Key Error while Encrypting Data ",e);
    } catch (BadPaddingException e) {
    logger.error(lFuncName + "Bad Padding Error while Encrypting Data ",e);
    } catch (IllegalBlockSizeException e) {
    logger.error(lFuncName + " Illegal Block Size Error while Encrypting Data ",e);
    } catch (InvalidAlgorithmParameterException e) {
    logger.error(lFuncName + " Invalid Alogirthm Parameter Error while Encrypting Data ",e);
    } catch (UnsupportedEncodingException e) {
    logger.error(lFuncName + " Unsupported Encoding Exception Error while Encrypting Data ",e);
    }catch(Exception e){
    logger.error(lFuncName + " Error while Encrypting Data ",e);
    return encryptedFinal;
    * Decrypts the encrypted data based on the key and algorithm
    * @param data
    * @return
    public String decrypt (String data){
    String lFuncName = "EncryptUil :: decrypt(): ";
    byte[] decrypted = null;
    byte[] decryptedFinal = null;
    String decryptedData = "";
    try{
    if(data!=null && data.length()>0){
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    decrypted = new BASE64Decoder().decodeBuffer(data);
    decryptedFinal = (cipher.doFinal(decrypted));
    decryptedData = this.bytes2String(decryptedFinal);
    } catch (InvalidKeyException e) {
    logger.error(lFuncName + "Invalid Key Error while Decrypting Data ",e);
    } catch (BadPaddingException e) {
    logger.error(lFuncName + "Bad Padding Error while Decrypting Data ",e);
    } catch (IllegalBlockSizeException e) {
    logger.error(lFuncName + " Illegal Block Size Error while Decrypting Data ",e);
    } catch (IOException e) {
    logger.error(lFuncName + " IO Exception while Decrypting Data ",e);
    }catch (Exception e){
    logger.error(lFuncName + " Error while Decrypting Data ",e);
    return decryptedData;
    private String bytes2String( byte[] bytes )
              StringBuffer stringBuffer = new StringBuffer();
              for (int i = 0; i < bytes.length; i++)
                   stringBuffer.append( (char) bytes[i] );
              return stringBuffer.toString();
    }The EncryptUtil is invoked as follows:EncryptUtil encryptUtil = new EncryptUtil("finalKey retrieved when application starts");
    encryptUtil.encrypt(unencryptedData);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    shannara wrote:
    thanks for your reply.
    I am sorry but I am not able to get you exactly. Every time I invoke the Utility class, I do a
    EncryptUtil eUtil = new EncryptUtil() Good. You seem to be using it in a thread safe manner since you create a new instance each time you need to use one.
    >
    and then invoke the decrypt() or encrypt() method, which gets the key from the cache (it is a read only object, so no problems of concurrent modification or any thing of that sort). And also these methods are called from a normal java class only, which inturn may be called from a jsp/servlet, but no scenarios of any concurrent access as such, so based on what you said, I am not able to figure out where exactly the thread safety could come as an issue.Each instance of a jsp or servlet can be being processed by many threads at the same time. Your statement above hints at a possible lack of understand on this point though I could be just reading it wrong. It indicates to me that your problem may be nothing to do with the encryption and everything to do with 'concurrent access' .
    Make sure you have no instance variables or class variables in your jsp(s) and servlet(s).
    Edit: The more I think about this the more I believe you have a thread safety problem in the code that reads the key. I would concentrate on that.
    Edited by: sabre150 on Dec 18, 2007 10:10 AM

  • 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.* and javax.crypto.spec.* problem with MHP receiver

    Hello to everyone, I started to program in MHP 1.0.2 on a MHP receiver and now i'm practicing in encrypting and decrypting. I load from the smart card in the MHP receiver an X509Certificate object (I have it both in byte[] form, called certArray, and X509Certificate object, called "certificate"). What i'd like to do is to :
    1)calculate digest of the certificate (line 1 and 2 of the following code)
    2) encrypt the digest using the same algorithm of the certificate (see line 3 and 4)
    The problem is generated at line 3 : the receiver, probably, doesn't find the class of the algorithm of encrypting. It is important to notice that the instruments to encrypt/decrypt are included in javax.crypto and javax.crypto.spec packages.
    MessageDigest md = MessageDigest.getInstance("SHA");
    byte[] digest = md.digest(certArray);
    Cipher encrypt = Cipher.getInstance(certificate.getSigAlgName());
    encrypt.init(Cipher.ENCRYPT_MODE, certificate.getPublicKey());
    The error message, in the log file, is the following :
    [0#1:2] java.security.NoSuchAlgorithmException: SHA1withRSA not found
         [0#1:2]      at javax.crypto.Cipher.getInstance(Ljava/lang/String;)Ljavax/crypto/Cipher;(Unknown Source)
         [0#1:2]      at it.csp.SecurelabXlet.encrypt()V(Unknown Source)
         [0#1:2]      at it.csp.SecurelabXlet.cardInserted(Lopencard/core/event/CardTerminalEvent;)V(Unknown Source)
         [0#1:2]      at opencard.core.event.EventGenerator.createEventsForPresentCards(Lopencard/core/event/CTListener;)V(Unknown Source)
         [0#1:2]      at it.csp.SecurelabXlet.register()V(Unknown Source)
         [0#1:2]      at it.csp.SecurelabXlet.startXlet()V(Unknown Source)
         [0#1:2]      at java.lang.reflect.Method.invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;(Unknown Source)
         [0#1:2]      at tv.osmosys.application.AppManager$XletApp.xletStart()Z(Unknown Source)
         [0#1:2]      at tv.osmosys.application.AppManager$XletApp.loop0(Ltv/osmosys/application/AppManager$XletAction;)V(Unknown Source)
         [0#1:2]      at tv.osmosys.application.AppManager$XletApp.run()V(Unknown Source)
         [0#1:2]      at java.lang.Thread.run()V(Unknown Source)
         [0#1:2]      at java.lang.Thread.startup(Z)V(Unknown Source)
    My question(s) is : how can I include javax.crypto and javax.crypto.spec in the Xlet application to upload it onto the MHP receiver?? Is it possibile to do so?
    Eventually, do other libraries exist to use encrypting algorithms, included in MHP? The version I use of MHP is 1.0.2. Thank you! Bye!

    Hello to everyone, I started to program in MHP 1.0.2 on a MHP receiver and now i'm practicing in encrypting and decrypting. I load from the smart card in the MHP receiver an X509Certificate object (I have it both in byte[] form, called certArray, and X509Certificate object, called "certificate"). What i'd like to do is to :
    1)calculate digest of the certificate (line 1 and 2 of the following code)
    2) encrypt the digest using the same algorithm of the certificate (see line 3 and 4)
    The problem is generated at line 3 : the receiver, probably, doesn't find the class of the algorithm of encrypting. It is important to notice that the instruments to encrypt/decrypt are included in javax.crypto and javax.crypto.spec packages.
    MessageDigest md = MessageDigest.getInstance("SHA");
    byte[] digest = md.digest(certArray);
    Cipher encrypt = Cipher.getInstance(certificate.getSigAlgName());
    encrypt.init(Cipher.ENCRYPT_MODE, certificate.getPublicKey());
    The error message, in the log file, is the following :
    [0#1:2] java.security.NoSuchAlgorithmException: SHA1withRSA not found
         [0#1:2]      at javax.crypto.Cipher.getInstance(Ljava/lang/String;)Ljavax/crypto/Cipher;(Unknown Source)
         [0#1:2]      at it.csp.SecurelabXlet.encrypt()V(Unknown Source)
         [0#1:2]      at it.csp.SecurelabXlet.cardInserted(Lopencard/core/event/CardTerminalEvent;)V(Unknown Source)
         [0#1:2]      at opencard.core.event.EventGenerator.createEventsForPresentCards(Lopencard/core/event/CTListener;)V(Unknown Source)
         [0#1:2]      at it.csp.SecurelabXlet.register()V(Unknown Source)
         [0#1:2]      at it.csp.SecurelabXlet.startXlet()V(Unknown Source)
         [0#1:2]      at java.lang.reflect.Method.invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;(Unknown Source)
         [0#1:2]      at tv.osmosys.application.AppManager$XletApp.xletStart()Z(Unknown Source)
         [0#1:2]      at tv.osmosys.application.AppManager$XletApp.loop0(Ltv/osmosys/application/AppManager$XletAction;)V(Unknown Source)
         [0#1:2]      at tv.osmosys.application.AppManager$XletApp.run()V(Unknown Source)
         [0#1:2]      at java.lang.Thread.run()V(Unknown Source)
         [0#1:2]      at java.lang.Thread.startup(Z)V(Unknown Source)
    My question(s) is : how can I include javax.crypto and javax.crypto.spec in the Xlet application to upload it onto the MHP receiver?? Is it possibile to do so?
    Eventually, do other libraries exist to use encrypting algorithms, included in MHP? The version I use of MHP is 1.0.2. Thank you! Bye!

  • Javax.crypto.IllegalBlockSizeException help?

    I am making a plain text encrypt/decrypt program for personal use.
    It will compile just fine, but if I try to run the decryption part, it freaks out on me.
    It keeps on saying:
    javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
    This is my code. I cannot figure out what is wrong...
    import java.io.*;
    import java.util.*;
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.SecretKeySpec;
    import javax.crypto.spec.IvParameterSpec;
    import static methods.methods.*;
    public class Base
        public static void main()
            Scanner kbReader = new Scanner(System.in);
            clear("Method > ");
            String s = kbReader.next();
            if(s.equals("output"))
                try{output();}
                catch(Exception e){e.printStackTrace();}
            if(s.equals("input"))
                try{input();}
                catch(Exception e){e.printStackTrace();}
            if(s.equals("genKey"))
                genKey();
            if(s.equals("x"))
                clear("Well it stopped.");
            else
                main();
        public static void output()
            throws IOException,
            NoSuchAlgorithmException,
            NoSuchPaddingException,
            InvalidKeyException,
            IllegalBlockSizeException,
            BadPaddingException,
            InvalidAlgorithmParameterException
            Scanner kbReader = new Scanner(System.in);
            Scanner kbr = new Scanner(System.in);
            clear("What is the name of the file?\nName > ");
            fileName = kbReader.next();
            String s2 = "/Users/ewsmith/base/" + fileName;
            FileWriter fw = new FileWriter(s2, true);
            PrintWriter output = new PrintWriter(fw, true);
            clear("Key > ");
            byte key[] = new byte[16];
            for(int j=0; j<16; j++)
                key[j] = kbReader.nextByte();
            clear("IV > ");
            byte ivBytes[] = new byte[16];
            for(int j=0; j<16; j++)
                ivBytes[j] = kbReader.nextByte();
            IvParameterSpec iv = new IvParameterSpec(ivBytes);
            String s = new String("");
            String ss = new String("");
            clear("Enter what you want output to a file.\nType 'x' to finish writing.\n\n");
            while(true)
                s = kbReader.nextLine();
                if(s.equalsIgnoreCase("x"))
                    break;
                ss = ss + s + "\n";
            byte data[] = ss.getBytes("UTF-8");
            Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            SecretKeySpec k = new SecretKeySpec(key, "AES");
            c.init(Cipher.ENCRYPT_MODE, k, iv);
            c.doFinal(data);
            for(int j=0; j<data.length; j++)
                output.print(data[j] + " ");
            clear("This is your key.\n\n");
            for(int j=0; j<key.length; j++)
            System.out.print(key[j] + "  ");
            println("\n\nType in 'x' and press enter to continue.");
            boolean alive = true;
            while(alive)
                String s3 = kbr.nextLine();
                if(s3.equalsIgnoreCase("x"))
                    alive = false;
            byte[] IV = c.getIV();
            clear("This is your IV:\n\n");
            for(int j=0; j<IV.length; j++)
                print(IV[j] + "  ");
            println("\n\nType x to continue.\n");
            String ew = "";
            while(true)
                ew = kbReader.nextLine();
                if(ew.equalsIgnoreCase("x"))
                    break;
            output.close();
            fw.close();
        public static void input()
            throws IOException,
            NoSuchAlgorithmException,
            NoSuchPaddingException,
            InvalidKeyException,
            IllegalBlockSizeException,
            BadPaddingException,
            InvalidAlgorithmParameterException
            Scanner kbReader = new Scanner(System.in);
            Scanner kbr = new Scanner(System.in);
            Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            clear("What is the name of the file?\nName > ");
            fileName = kbr.next();
            String s2 = "/Users/ewsmith/base/" + fileName;
            Scanner sf = new Scanner(new File(s2));
            int num = 1;
            clear("Key > ");
            byte key[] = new byte[16];
            for(int j=0; j<16; j++)
                key[j] = kbReader.nextByte();
            clear("IV > ");
            byte ivBytes[] = new byte[16];
            for(int j=0; j<16; j++)
                ivBytes[j] = kbReader.nextByte();
            IvParameterSpec iv = new IvParameterSpec(ivBytes);
            SecretKeySpec k = new SecretKeySpec(key, "AES");
            c.init(Cipher.DECRYPT_MODE, k, iv);
            clear("This text was stored inside the file.\n\n\n");
            int j = 0;
            ArrayList<Byte> ip = new ArrayList<Byte>();
            while(sf.hasNext())
                ip.add(sf.nextByte());
            byte input[] = new byte[ip.size()];
            for(j=0; j<ip.size(); j++)
                input[j] = ip.get(j);
            String recovered = new String(c.doFinal(input));
            println(recovered);
            sf.close();
            ip.clear();
            input = null;
            println("\n\nType in 'x' and press enter to continue.");
            boolean alive = true;
            while(alive)
                String s = kbReader.nextLine();
                if(s.equalsIgnoreCase("x"))
                    alive = false;
        public static void genKey()
            Scanner kbReader = new Scanner(System.in);
            clear();
            Random ranGen = new SecureRandom();
            byte[] aesKey = new byte[16];
            ranGen.nextBytes(aesKey);
            for(int j=0; j<aesKey.length; j++)
            System.out.print(aesKey[j] + "  ");
            println("\n\nType in 'x' and press enter to continue.");
            boolean alive = true;
            while(alive)
                String s = kbReader.nextLine();
                if(s.equalsIgnoreCase("x"))
                    alive = false;
        public static String fileName = "";
    }Thank you in advance for answering.
    EDIT:
    It now says:
    +     at com.sun.crypto.provider.SunJCE_h.b(DashoA12275)+
    +     at com.sun.crypto.provider.SunJCE_h.b(DashoA12275)+
    +     at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA12275)+
    +     at javax.crypto.Cipher.doFinal(DashoA12275)+
    +     at Base.input(Base.java:184)+
    +     at Base.main(Base.java:23)+
    +     at __SHELL3.run(__SHELL3.java:6)+
    +     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)+
    +     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)+
    +     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)+
    +     at java.lang.reflect.Method.invoke(Method.java:585)+
    +     at bluej.runtime.ExecServer$3.run(ExecServer.java:819)+
    Could this be an IV error?
    Can negative IV's be used?
    Edited by: eric_smith on Jan 6, 2010 9:25 PM
    Edited by: eric_smith on Jan 7, 2010 9:51 AM

    I turned this:
    String recovered = new String(c.doFinal(input));into this:
    String recovered = new String(input);and used 0's for the key and iv and the text was 'decrypted'.
    Something tells me the problem is in the output and input cipher.init()
    Can someone enlighten me as to what I am doing wrong?
    EDIT: btw, the code came from the input method.
    Edited by: eric_smith on Jan 7, 2010 9:28 PM

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

  • Javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8

    Hello!
    I have encrypted/decrypted one String with DES. I tried to do so on one computer and it seams to work fine. But what I realy want is to encrypt 3 String: username, id, and password, and send them to server. On server I want to decrypt them, and use them to check in database if the person exist. I save this 3 String in an ArrayList, and use ObjectInput/OutputStream to send and receive. Here is some of my code(I hope it is enough for you to help me solve this problem,othervice I will send more).
    I get this error: javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
    public class CryptDecryptString {
    public byte[] cryptString( String password) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{
    byte [] plainTextPassword = password.getBytes("UTF-8");
    System.out.println(new String(plainTextPassword,"UTF-8"));
    //SecureRandom sr = new SecureRandom();
    String nyckeln = "HELLOHEJ";
    byte rawKeyData[] = nyckeln.getBytes();
    DESKeySpec dks = new DESKeySpec(rawKeyData);
    SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(dks);
    Cipher cipher=Cipher.getInstance("DES");
    cipher.init(Cipher.ENCRYPT_MODE, key);//, sr);
         System.out.println("\nStart encryption:");
    cipher.init(Cipher.ENCRYPT_MODE,key);
         byte[] cipherTextPassword=cipher.doFinal(plainTextPassword);
         System.out.println("Finish encryption:");
         System.out.println(new String(cipherTextPassword));
    return cipherTextPassword;
    }// end cryptString
    public byte[]decryptString(byte[] cipherTextPassword) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
    String nyckeln = "HELLOHEJ";
    byte rawKeyData[] = nyckeln.getBytes();
    DESKeySpec dks = new DESKeySpec(rawKeyData);
    SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(dks);
    Cipher cipher=Cipher.getInstance("DES");
         System.out.println("\nStart decryption:");
    cipher.init(Cipher.DECRYPT_MODE,key);
         byte[] plainTextPassword=cipher.doFinal(cipherTextPassword);
         System.out.println(" Finnish decryption:");
         System.out.println(new String(plainTextPassword,"UTF-8"));
    return plainTextPassword;
    }// end decryptString
    {public boolean TryLogin(String uname, String insID, String pass) throws Exception{
            connect();
            //sendOutStream = new DataOutputStream(socket.getOutputStream());
            sendOutStream = new ObjectOutputStream(socket.getOutputStream());
            InputStream inpuStream;
            inpuStream = socket.getInputStream();
            BufferedReader in= new BufferedReader(new InputStreamReader(inpuStreamtext s));
            CryptDecryptString cryptString = new CryptDecryptString();
          String krypteradeUname = cryptString.cryptString(uname);
           String krypteradeInsID = cryptString.cryptString(insID);
            String krypteradePass = cryptString.cryptString(pass);
            ArrayList<String> loggInPersonInfo= new ArrayList<String>();
                                   loggInPersonInfo.add(krypteradeUname);
                                   loggInPersonInfo.add(krypteradeInsID);
                                   loggInPersonInfo.add(krypteradePass);
                                   Object[] elements = loggInPersonInfo.toArray();
    for(int i=0; i < elements.length ; i++)
    System.out.println(elements);
    sendOutStream.writeObject(loggInPersonInfo);
    sendOutStream.close();
    sendOutStream.flush();
    System.out.println("Skickade information...");
    int line = in.read();
    if(line > 0){
    user_id = line;
    return true;
    }else{
    return false;

    Here is the rest of code
    public void CheckLogin() throws SQLException, IOException, InterruptedException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, Exception{
    /**InputStream inpuStream;
    inpuStream = client.getInputStream();
    BufferedInputStream in= new BufferedInputStream(inpuStream);//(new BufferedReader(inpuStream));
    inpuStream = client.getInputStream();
    ObjectInputStream objectIn = new ObjectInputStream(inpuStream);
    ArrayList<String> personLoggIn = new ArrayList<String>();
    String krypteradeUname;
    String krypteradeInsID ;
    String krypteradePass ;
    personLoggIn = null;
    personLoggIn = (ArrayList<String>)objectIn.readObject();
    for (int i=0;i<personLoggIn.size();i++) {
    krypteradeUname=personLoggIn.get(0);
    krypteradeInsID =personLoggIn.get(1);
    krypteradePass = personLoggIn.get(2);
    System.out.println(i);
    inpuStream.close();
    CryptDecryptString decryptString = new CryptDecryptString();
    byte[] byteUname = decryptString.decryptString((krypteradeUname.getBytes()));
    String username = new String(byteUname);
    byte[] byteInsID = decryptString.decryptString((krypteradeInsID.getBytes()));
    String instanceID = new String(byteInsID);
    byte[] bytePassword = decryptString.decryptString((krypteradePass.getBytes()));
    String password = new String(bytePassword);
    Please help!
    Thanks!

  • Unable to Decrypt the data properly using javax.crypto class and SunJCE

    Hello all,
    I am not new to Java but new to this forums
    but and JCE and i wanted to write a program that Encrypts a file and also another program that decrypts it. As far Encryption is concerned i have been successful but When it comes to Decryption things aren't looking bright i have some or the other Problem with it. plz help me out .
    Here is the Code for my Programs
    Encryption
    Code:
    import java.io.*;
    import javax.crypto.*;
    import javax.crypto.spec.SecretKeySpec;
    import java.security.*;
    import javax.swing.*;
    class MyJCE
    public static void main(String args[])throws Exception
    Provider sunjce = new com.sun.crypto.provider.SunJCE();
    Security.addProvider(sunjce);
    JFileChooser jfc = new JFileChooser();
    int selection= jfc.showOpenDialog(null);
    if(selection==JFileChooser.APPROVE_OPTION)
    FileInputStream fis = new FileInputStream(jfc.getSelectedFile());
    System.out.println("Selected file " + jfc.getSelectedFile());
    try{
    KeyGenerator kg = KeyGenerator.getInstance("DESede");
    SecretKey key= kg.generateKey();
    byte[] mkey=key.getEncoded();
    System.out.println(key);
    SecretKeySpec skey = new SecretKeySpec(mkey, "DESede");
    Cipher cipher=Cipher.getInstance("DESede/ECB/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE,skey);
    byte[] data= new byte[fis.available()];
    //reading the file into data byte array
    byte[] result= cipher.update(data);
    byte[] enc= new byte [fis.read(result)];
    System.out.println("Encrypted =" + result);
    File fi= new File("/home/srikar/Encrypted");
    FileOutputStream fos= new FileOutputStream(fi);
    fos.write(enc);
    fos.close();
    byte[] encodedSpeckey = skey.getEncoded();
    FileOutputStream ks= new FileOutputStream("./key.txt");
    ks.write(encodedSpeckey);
    System.out.println("Key written to a file");
    }//try
    catch(Exception ex)
    ex.printStackTrace();
    }//catch
    }This Creates a Encrypted File. and a Encrypted key.txt
    Code:
    import java.io.*;
    import javax.crypto.*;
    import javax.crypto.spec.SecretKeySpec;
    import java.security.*;
    import javax.swing.*;
    class Decrypt
    public static void main(String[] args)
    try
    JFileChooser jfc = new JFileChooser();
    int selection= jfc.showOpenDialog(null);
    if(selection==JFileChooser.APPROVE_OPTION)
    FileInputStream fis = new FileInputStream(jfc.getSelectedFile());
    System.out.println("Selected file " + jfc.getSelectedFile());
    //Read from the Encrypted Data
    int ll= (int)jfc.getSelectedFile().length();
    byte[] buffer = new byte[ll];
    int bytesRead=fis.read(buffer);
    byte[] data= new byte[bytesRead];
    System.arraycopy(buffer,0,data,0,bytesRead);
    //Read the Cipher Settings
    FileInputStream rkey= new FileInputStream("./key.txt");
    bytesRead = rkey.read(buffer);
    byte[] encodedKeySpec=new byte[bytesRead];
    System.arraycopy(buffer,0,encodedKeySpec,0,bytesRead);
    //Recreate the Secret Symmetric Key
    SecretKeySpec skeySpec= new SecretKeySpec(encodedKeySpec,"DESede");
    //create the cipher for Decrypting
    Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
    cipher.init(Cipher.DECRYPT_MODE,skeySpec);
    byte[] decrypted= cipher.update(data);
    FileOutputStream fos= new FileOutputStream("/home/srikar/Decrypted");
    fos.write(decrypted);
    }//if
    }//try
    catch(Exception e)
    e.printStackTrace();
    }//catch
    }//main
    }//classthis Decrypt.java is expected to decrypt the above encrypted file but this simply creates a plaintext file of the same size as the Encrypted file but its contents are unreadable.
    Or I endup with Exceptions like BadPadding or IllegalBlockSize Exception if i use any other Algorithm .
    Please help out
    thanx in advance

    Srikar2871 wrote:
    Well thanx for ur reply but
    As i said there are No issues with ENCRYPTION and am getting an Encrypted file exactly of the same size as that of the original file and NOT as null bytes and Even am able to get a Decrypted file of again the same size of the Encrypted File but this time that data inside is in unreadable format.I ran your code EXACTLY* as posted and the contents of the file when viewed in a Hex editor was
    00 00 00 00 00 00 00 00 00 00 00 00 00 00 00So unless you are running different code to what you have posted, your file will look the same.
    Cheers,
    Shane

  • Javax.crypto.BadPaddingException: Given final block not properly padded

    import java.security.*;
    import javax.crypto.*;
    public class Cryptographer
    private final String DEFAULT_KEY="1111111111111111";
    private String KEY;
    public Cryptographer(String key)
    if((key==null)||key.equals(""))
    this.KEY = DEFAULT_KEY;
    else
    this.KEY = key;
    public byte[] encrypt(String toEncrypt)
    if((toEncrypt==null)||(toEncrypt.trim().equals("")))
    return null;
    try
    return DESEncrypt(toEncrypt,KEY);
    catch(Exception e)
    e.printStackTrace();
    return null;
    public String decrypt(byte[] bytes)
    if(bytes==null)
    return null;
    try
    return DESDecrypt(bytes,KEY);
    catch(Exception e)
    e.printStackTrace();
    return null+"hi";
    public String ToMac(byte[] bytes,String key)
    if(bytes==null)
    return null;
    try
    return getMac(bytes,KEY);
    catch(Exception e)
    return null;
    private byte[] DESEncrypt(String toEncrypt, String key)
    throws Exception
    // create a binary key from the argument key (seed)
    SecureRandom sr = new SecureRandom(key.getBytes("UTF-8"));
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    kg.init(56,sr);
    SecretKey sk = kg.generateKey();
    // do the encryption with that key
    Cipher cipher = Cipher.getInstance("DES");
    //DES/CFB8/NOPadding;DES/OFB32/PKCS5Padding;DESEDE/ECB/PKCS5Padding;DES/ECB/NOPadding==DES
    cipher.init(Cipher.ENCRYPT_MODE, sk);
    byte[] encrypted = cipher.doFinal(toEncrypt.getBytes("UTF-8"));
    return new sun.misc.BASE64Encoder().encode(encrypted).toUpperCase().getBytes();
    //return encrypted;
    private String DESDecrypt(byte[] toDecrypt, String key)
    throws Exception
    // create a binary key from the argument key (seed)
    SecureRandom sr = new SecureRandom(key.getBytes("UTF-8"));
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    kg.init(56,sr);
    SecretKey sk = kg.generateKey();
    // do the decryption with that key
    Cipher cipher = Cipher.getInstance("DES");
    cipher.init(Cipher.DECRYPT_MODE, sk);
    byte[] decrypted = cipher.doFinal(toDecrypt);
    return new sun.misc.BASE64Encoder().encode(decrypted).toUpperCase();
    //return new String(decrypted,"UTF-8");
    //create mac String; byte[] to be maced
    private String getMac(byte[] bytes,String key)
    byte[] bmac =null;
    try
    // create a binary key from the argument key (seed)
    SecureRandom sr = new SecureRandom(key.getBytes());
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    kg.init(56,sr);
    SecretKey sk = kg.generateKey();
    Mac mac = Mac.getInstance("HmacMD5");
    //HmacMD5;HmacSHA1;PBEWith<mac> e.g PBEWithHmacSHA1
    mac.init(sk);
    bmac = mac.doFinal(bytes);
    catch(Exception e)
    e.printStackTrace();
    return new String(bmac);
    public String byte2hex(byte[] b) //��������������
    String hs="";
    String stmp="";
    for (int n=0;n<b.length;n++)
    stmp=(java.lang.Integer.toHexString(b[n] & 0XFF));
    if (stmp.length()==1) hs=hs+"0"+stmp;
    else hs=hs+stmp;
    if (n<b.length-1) hs=hs+"";
    return hs.toUpperCase();
    public static void main(String args[])
    throws Exception
    String key = new String("1111111111111111");
    Cryptographer c = new Cryptographer(key); //use key to initialize the class
    String str = new String("4A6C98EAEF14EAB6");
    byte[] b = c.encrypt(str); //to encrypt data
    System.out.println(b.length);
    System.out.println("Encrypted data:"+new String(b)+":"+new String(c.byte2hex(b))); //println Encrypt data
    String st = c.decrypt(str.getBytes()); //to decrypt data
    System.out.println(st.getBytes().length);
    System.out.println(st.length());
    System.out.println("Decrypted data:"+st+":"+c.byte2hex(st.getBytes())); //println decrypt data
    please help me! thax

    One: Use the [ code ] tags. Please. It'll only help you get answers.
    Two: encrypt() is returning the getBytes() of the result of Base64'ing the ciphertext. Bad. The whole POINT to Base64 is to produce Strings from byte[]'s. Don't use Base64 to produce a byte[]. Change encrypt() to return the byte[] directly.
    Three: Given that encrypt() is returning the byte[] from the Base64 - decrypt() needs to be ready to UNDO that. It isn't. decrypt() assumes the byte[] it's getting is the ciphertext. That's not what you're giving to it. It's very, very unhappy.
    Four: your main() isn't even handing decrypt() the (bogus) return from encrypt(). Your main() is asking decrypt() to decrypt your plaintext. That trick never works...
    Five: your choice of variable names in your main() is...suboptimal. If you'd chosen names that reflected the purpose of the variable (things like, say, 'plaintext' and 'ciphertext'), some of this would have been obvious.
    Try the following:import java.security.SecureRandom;
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.Mac;
    import javax.crypto.SecretKey;
    public class Cryptographer {
        private final String DEFAULT_KEY = "1111111111111111";
        private String KEY;
        public Cryptographer(String key) {
            if ((key == null) || key.equals("")) {
                this.KEY = DEFAULT_KEY;
            } else {
                this.KEY = key;
        public byte[] encrypt(String toEncrypt) {
            if ((toEncrypt == null) || (toEncrypt.trim().equals("")))
                return null;
            try {
                return DESEncrypt(toEncrypt, KEY);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
        public String decrypt(byte[] bytes) {
            if (bytes == null)
                return null;
            try {
                return DESDecrypt(bytes, KEY);
            } catch (Exception e) {
                e.printStackTrace();
                return null +"hi";
        public String ToMac(byte[] bytes, String key) {
            if (bytes == null)
                return null;
            try {
                return getMac(bytes, KEY);
            } catch (Exception e) {
                return null;
        private byte[] DESEncrypt(String toEncrypt, String key) throws Exception {
            // create a binary key from the argument key (seed)
            SecureRandom sr = new SecureRandom(key.getBytes("UTF-8"));
            KeyGenerator kg = KeyGenerator.getInstance("DES");
            kg.init(56, sr);
            SecretKey sk = kg.generateKey();
            // do the encryption with that key
            Cipher cipher = Cipher.getInstance("DES");
            //DES/CFB8/NOPadding;DES/OFB32/PKCS5Padding;DESEDE/ECB/PKCS5Padding;DES/ECB/NOPadding==DES
            cipher.init(Cipher.ENCRYPT_MODE, sk);
            byte[] encrypted = cipher.doFinal(toEncrypt.getBytes("UTF-8"));
            return encrypted;
        private String DESDecrypt(byte[] toDecrypt, String key) throws Exception {
            // create a binary key from the argument key (seed)
            SecureRandom sr = new SecureRandom(key.getBytes("UTF-8"));
            KeyGenerator kg = KeyGenerator.getInstance("DES");
            kg.init(56, sr);
            SecretKey sk = kg.generateKey();
            // do the decryption with that key
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, sk);
            byte[] decrypted = cipher.doFinal(toDecrypt);
            return new String(decrypted,"UTF-8");
        //create mac String; byte[] to be maced
        private String getMac(byte[] bytes, String key) {
            byte[] bmac = null;
            try {
                // create a binary key from the argument key (seed)
                SecureRandom sr = new SecureRandom(key.getBytes());
                KeyGenerator kg = KeyGenerator.getInstance("DES");
                kg.init(56, sr);
                SecretKey sk = kg.generateKey();
                Mac mac = Mac.getInstance("HmacMD5");
                //HmacMD5;HmacSHA1;PBEWith<mac> e.g PBEWithHmacSHA1
                mac.init(sk);
                bmac = mac.doFinal(bytes);
            } catch (Exception e) {
                e.printStackTrace();
            return new String(bmac);
        public String byte2hex(byte[] b) //��������������
            String hs = "";
            String stmp = "";
            for (int n = 0; n < b.length; n++) {
                stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
                if (stmp.length() == 1)
                    hs = hs + "0" + stmp;
                else
                    hs = hs + stmp;
                if (n < b.length - 1)
                    hs = hs + "";
            return hs.toUpperCase();
        public static void main(String args[]) throws Exception {
            String key = new String("1111111111111111");
            Cryptographer c = new Cryptographer(key); //use key to initialize the class
            String str = new String("Hello world!");
            byte[] ciphertext = c.encrypt(str); //to encrypt data
            System.out.println(ciphertext.length);
            System.out.println("Encrypted data:"  + new String(c.byte2hex(ciphertext )));
            String plaintext = c.decrypt(ciphertext );  //to decrypt data
            System.out.println(plaintext.getBytes().length);
            System.out.println(plaintext.length());
            System.out.println("Decrypted data:" + plaintext ); //println decrypt data
    }And please, please, PLEASE use the [ code ] tags...
    Grant

  • Problem when using javax.crypto.KeyGenerator in netbeans

    This is my IDE information:
    Product Version: NetBeans IDE 6.0.1 (Build 200801291616)
    Java: 1.6.0_03; Java HotSpot(TM) Client VM 1.6.0_03-b05
    System: Windows XP version 5.1 running on x86; Cp1252; en_US (nb)
    I am trying to develop a Test jar file. I created some simple jar files and could upload it in mobile.
    Now I want to implement some encryption. For that I started writing codes. But when trying to import javax.crypto.KeyGenerator class, netbeans is showing "cannot find symbol" error. I can use javax.crypto.Cipher/BadPaddingException/IllegalBlockSizeException/NoSuchPaddingException/spec/ShortBuffrException only. If i try to use any other class of javax.crypto, i get an error.
    I am new to mobility.I downloaded netbean mobility package and Installed it.
    Please provide some help.. thank you....

    This is my IDE information:
    Product Version: NetBeans IDE 6.0.1 (Build 200801291616)
    Java: 1.6.0_03; Java HotSpot(TM) Client VM 1.6.0_03-b05
    System: Windows XP version 5.1 running on x86; Cp1252; en_US (nb)
    I am trying to develop a Test jar file. I created some simple jar files and could upload it in mobile.
    Now I want to implement some encryption. For that I started writing codes. But when trying to import javax.crypto.KeyGenerator class, netbeans is showing "cannot find symbol" error. I can use javax.crypto.Cipher/BadPaddingException/IllegalBlockSizeException/NoSuchPaddingException/spec/ShortBuffrException only. If i try to use any other class of javax.crypto, i get an error.
    I am new to mobility.I downloaded netbean mobility package and Installed it.
    Please provide some help.. thank you....

  • Import javax.crypto not found error

    Hi,
    I have just installed the JDK1.7 on a windows machine.
    Whenever I try to compile my module, I get an error on the import javax.crypto line. It tells me that it can't the javax\Crypto\Cipher.class.
    I have the jdk installed on d:\glassfish3 and am pointing the classpath to d:\glassfish3\jdk7 (also tried d:\glassfish3\jdk7\jre as well) with no luck.
    Any help would be greatly appreciated.
    Thanks,
    Drew Nathanson
    Technical Synergy, Inc.

    Thanks. Maybe I should explain a little better.
    I am using JBuilder 2006 to my IDE. This environment requires that you put in the path to the JRE/JDK.
    I have uninstalled and downloaded the jdk again and this time i'm getting a strange error:
    "test.java": cannot access javax.crypto.Cipher; bad class file: D:\Program Files\Java\jre7\lib\jce.jar\javax\crypto\Cipher.class, class file has wrong version 51.0, should be 49.0, Please remove or make sure it appears in the correct subdirectory of the classpath. at line 19, column 21
    Now this is strange because i'm using the right library.
    Is there something that I'm missing here?
    Again, thanks for your help.
    Drew Nathanson

  • Class javax.crypto.SecretKey not found in import.

    While compilation i am getting this error.
    Class javax.crypto.SecretKey not found in import.
    I am not able to figure it out . Please help me for that.
    Is it related to some classpath setting.

    This error is due to the c:\windows\system32\java.exe being first on the path instead of the d:\jdev9i\jdk\bin\java.exe being picked up.

  • Javax.crypto.* is not present in JDK 1.4 plz help

    Hi,
    Currently i am using jdk 1.4 and I am trying to compile the security applications which are using javax.crypto.* package.
    Hence it is giving error so can any one please help me how can I include this package into jdk 1.4 or is there any other alternative for it.
    Need help immediately.
    It would be apprciable if i get an immediate reply.
    Thanks in advance.

    What is a "marker" interface?
    Marker Interface pattern
    c2.com - Marker Interface
    experts.about.com - Marker Interfaces
    The Purpose of the Marker Interface
    Maximize your Design ROI with Marker Interfaces and JavaDoc

Maybe you are looking for