Javax.crypto.spec.*

I am trying to encrypt passwords and have been given a code snipper which tries to import "javax.crypto.spec.*". Can you tell me what jar this is in and where to get it.
Thanks.

It appears to be new in 1.4.0.

Similar Messages

  • NoClassDefFoundError javax.crypto.spec.secretkeyspec from console

    Hello, I have done a program in eclipse, using the JCE to encrypt and decrypt some messages using AES. In the eclipse graphical interface it works perfect, but if i run it from console, i mean like this
    java -jar org.eclipse.osgi_3.6.0.v20100517.jar -console -configuration config_path -clean -dev file:dev.properties_path
    It works but throw the exception
    NoClassDefFoundError javax.crypto.spec.secretkeyspec
    I think there must be something wrong with the java path because JCE is already inside the jre environment. I need to know how can i indicate in the command line, the right path to the JCE
    I am working on windows
    Thank you!

    yes, i mean
    NoClassDefFoundError javax.crypto.spec.SecretKeySpec
    but i wrote it fast and i didn't realize....
    My output for java -version is
    java version "1.6.0_21"
    Java (TM) SE Runtime Environment (build 1.6.0_21-b06)
    Java HotSpot(TM) Client VM (build 17.0-b16, mixed mode, sharing)
    So i think that outside eclipse i am using the good one, then i don't know why it doesn't work. Actually, i forgot to say that in the log file, i get this exception message:
    !ENTRY org.eclipse.osgi 4 0 2010-10-15 11:35:12.273
    !MESSAGE Application error
    !STACK 1
    java.lang.IllegalStateException: Unable to acquire application service. Ensure that the org.eclipse.core.runtime bundle is resolved and started (see config.ini).
         at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:74)
         at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:369)
         at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
         at org.eclipse.core.runtime.adaptor.EclipseStarter.main(EclipseStarter.java:150)
    So maybe this is the real problem. I am sorry but i am not really used to launch java applications from console (i always do it with eclipse) so, i don't really know if i need some more parameters or what happen.
    My config.ini file is the same that eclipse uses when it launches the application, and the dev.properties file is also the same.

  • 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.spec.SecretKeySpec seems to ignore the last bit in every byte

    Hi All,
    I am having a problem with the SecretKeySpec class in JCE 1.2.2. I am using DES as algorithm, and a 8 byte long key. I am passing a hex array of 16 characters (each 2 representing a byte) and create a byte array of length 8 from that hex array. For example, the following "A12C3D4E5F6A7B8E" is equivalent to a byte array, having the values of the bytes (in signed byte) [-95, 44, 61, 78, 95, 106, 123, -114]. It works perfectly but what I observed is, if one of the bytes looks like "5E" and I change it to "5F," the code still works, the encrypted text using the key created with "5E" key is decrypted correctly using the "5F" key. It doesn't work if the byte is "E5" and I change it to "F5," and this led me to think that the SecretKeySpec implementation ignores the last bit of every byte (uses just the high 7 bits.)
    Anybody came accross this before? Any help appreciated.
    THanks,
    Marius

    As I said, "every implementation I'm aware of ignores them". They're not used during en/decryption, they exist only to provide (marginal) evidence that the key might have been mangled in-transit. Many implementations just skip that step. Note that i'm not saying this is a good thing - it's just been my experience.
    The 64-bit quntity you're playing with is NOT "the key" - the DES key is the 56 bits that do not include the parity bits. Ignoring the parity-bits doesn't yield more keys that will do the same decryption, since the parity bits aren't used by DES itself.
    The net? Don't worry about it. It's the 56 bits that are the important ones.
    Grant

  • 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

  • Cannot find javax.crypto.KeyGeneratorSpi

    The following code compiles but
    I get a runtime error as follows.
    NoClassDefFoundError for javax.crypto.KeyGeneratorSpi
    I did a jar tf on the sunjce_provider.jar file and
    this class is not contained?
    It is in the jce1_2_1.jar file and is abstract.
    When at runtime the factory tries to create an instance
    of the keyGeneratorSpi I think it tries to get a concrete
    implementation of the class from the SunJCE implementation and cant find it?
    Is this correct.
    Obviously the classpath is set correct as I am able to
    import all of the SunJCE classes.
    Heres the code.
    import java.io.*;
    import java.util.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import com.sun.crypto.provider.*;
    import java.security.*;
    public class CryptoTest {
    public static void main(String[] args)
    KeyGenerator keygen = null;
    SecretKey desKey = null;
    Cipher desCipher = null;
    Security.addProvider( new com.sun.crypto.provider.SunJCE() );
    byte[] ciphertext;
    try
    keygen = KeyGenerator.getInstance("DES","SunJCE");
    catch(Exception e){
    System.out.println("Exception getting keygenerator");
    e.printStackTrace();
    }

    What jdk version do you use?
    I use the J2SDK 1.4.0-beta(contains the jce and the Sun JCE provider).
    And the following code works fine to me:
    KeyGenerator keygen = null;
    try {
    keygen = KeyGenerator.getInstance("DES","SunJCE");
    } catch(Exception e) {
    System.out.println("Exception getting keygenerator");
    e.printStackTrace();
    }

  • Javax.crypto.IllegalBlockSizeException,javax.crypto.BadPaddingException

    hi friends
    iam writing and reading an encryted text to a file . this code executes well on windows xp o.s but does not executes on Macintosh ,solaris and linux systems.
    when executed it throws javax.crypto.IllegalBlockSizeException and javax.crypto.BadPaddingException .
    pls i am damp urgent need of it so kindly resolve my problem
    Below is the code.
    Thanks in advance.
    --------------------------------------------------code----------------------------------------
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileReader;
    import java.io.FileWriter;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.Cipher;
    import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
    public class EncryptionExample
         static SecretKey key = null;
         static String text="A=1,B=2,C=3";
         static String xform = "Blowfish/CFB/PKCS5Padding";
         private static byte[] iv =
    { 0x0a, 0x01, 0x02, 0x03, 0x04, 0x0b, 0x0c, 0x0d };
         public EncryptionExample() throws Exception
              key=EncryptionExample.getGeneratedKey();
         public static void writeToFile() throws Exception
              FileWriter file = null;
              BufferedWriter fileOutput = null;
              byte[] dataBytes = null;
              byte[] encBytes = null;
              try {
                        file = new FileWriter("C:\\Test.txt");
                        fileOutput= new BufferedWriter(file);
                        dataBytes = text.getBytes("UTF8");
                   encBytes = encrypt(dataBytes, key, xform);
                   String encStr = Base64.encode(encBytes);
                   fileOutput.write(encStr);
                        fileOutput.close();
                   } catch (Exception e) {
                   e.printStackTrace();
         //     reading encryted text from file
              public static void readFromFile() throws Exception
                   FileReader filerdr = null;
                   BufferedReader fileInput = null;
                   byte[] decBytes = null;
                   String decrystr = null;
                   String enText = null;
                   try {
                                  filerdr = new FileReader("C:\\Test.txt");
                                  fileInput = new BufferedReader(filerdr);
                                  while ((enText = fileInput.readLine())!=null)
                                       byte[] decrypted = Base64.decode(enText);
                                       decBytes = decrypt(decrypted, key, xform);
                                       decrystr=new String(decBytes,"UTF8");
                                       System.out.println("decrypted string token , "+decrystr);
                                  fileInput.close();
                             }catch (Exception e) {
                                  e.printStackTrace();
              private static byte[] encrypt(byte[] inpBytes,SecretKey key, String xform) throws Exception {
                   Cipher cipher = Cipher.getInstance(xform);
                   IvParameterSpec dps = new IvParameterSpec(iv);
                   cipher.init(Cipher.ENCRYPT_MODE, key,dps);
                   return cipher.doFinal(inpBytes);
         private static byte[] decrypt(byte[] inpBytes,SecretKey key, String xform) throws Exception
              Cipher cipher = Cipher.getInstance(xform);
              IvParameterSpec dps = new IvParameterSpec(iv);
              cipher.init(Cipher.DECRYPT_MODE, key,dps);
              return cipher.doFinal(inpBytes);
         private static SecretKey getGeneratedKey() throws Exception
    //          Generate a secret key
         KeyGenerator kg = KeyGenerator.getInstance("Blowfish");
         kg.init(128); // 56 is the keysize. Fixed for DES
         SecretKey key = kg.generateKey();
         return key ;
         public static void main(String[] unused) throws Exception {
              new EncryptionExample();
              EncryptionExample.writeToFile();
              EncryptionExample.readFromFile();
    }

    You are very lucky to get this working at all, even on Windows! You encrypt the whole of your string at one go and write it to a file using
    fileOutput= new BufferedWriter(file);
    dataBytes = text.getBytes("UTF8");
    encBytes = encrypt(dataBytes, key, xform);
    String encStr = Base64.encode(encBytes);
    fileOutput.write(encStr);
    fileOutput.close();but you then try to decrypt it a line at a time using
    while ((enText = fileInput.readLine())!=null)
    byte[] decrypted = Base64.decode(enText);
    decBytes = decrypt(decrypted, key, xform);
    decrystr=new String(decBytes,"UTF8");
    System.out.println("decrypted string token , "+decrystr);
    fileInput.close();This just does not make sense. If you encrypt all at one time you must decrypt all at one time.
    Your code happens to work because the Base64 encoding puts everything on one line. The fact that this seems to work does not make it correct.
    P.S. Your code works on my Linux FC5 so I have no idea why you get the exceptions!

  • 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 and Perl module Crypt::CBC

    Hi,
    My problem is when I encrypt on the JAVA side with :
    String inkey = "123456781234567812345678";
    final byte[] ivBytes =     {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
    byte[] rawkey = inkey.getBytes();
    DESedeKeySpec keyspec = new DESedeKeySpec(rawkey);
    SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
    SecretKey key = keyfactory.generateSecret(keyspec);
    encryptCipher = Cipher.getInstance("DESede/CBC/PKCS5Padding", "SunJCE");
    encryptCipher.init(javax.crypto.Cipher.ENCRYPT_MODE, key, iv);
    synchronized public String encrypt(String Entry) throws Exception {
    byte[] EntryBytes = Entry.getBytes(characterEncoding);
    byte[] encryptedEntryBytes = this.encryptCipher.doFinal(EntryBytes);
    String encodedEncryptedEntry = this.base64Encoder.encode(encryptedEntryBytes);
    return encodedEncryptedEntry;
    and try to decrypt on the Perl side with :
    $cbc_encrypt_key = "123456781234567812345678";
    $cbc_iv = "12345678";
    $css_cipher = Crypt::CBC->new(
    -cipher => DES_EDE3,
    -key => $cbc_encrypt_key,
    -iv => $cbc_iv,
    -header => 'none'
    $info = decode_base64($info);
    $info = $css_cipher->decrypt($info);
    it doesn't work at all, Perl can't decrypt. Is there any compatibilty problem ? or is my code wrong (i suppose so)
    Please help me
    Ed

    what readme file ?
    here my java class :
    package sso;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.security.*;
    import sun.misc.*;
    public class DESedeEntryEncrypt
         public DESedeEntryEncrypt(byte[] keyBytes, byte[] ivBytes, String characterEncoding) throws Exception
              try {     
    SecretKey key = new SecretKeySpec(keyBytes, "DESede");
                   IvParameterSpec iv = new IvParameterSpec(ivBytes);
                   this.characterEncoding = characterEncoding;
                   this.encryptCipher = Cipher.getInstance("DESede/CBC/PKCS5Padding", "SunJCE");
                   this.encryptCipher.init(javax.crypto.Cipher.ENCRYPT_MODE, key, iv);
                   this.decryptCipher = Cipher.getInstance("DESede/CBC/PKCS5Padding", "SunJCE");
                   this.decryptCipher.init(javax.crypto.Cipher.DECRYPT_MODE, key, iv);
              catch (Exception e)
                   System.err.println(e);
         synchronized public String encrypt(String Entry) throws Exception
              byte[] EntryBytes = Entry.getBytes(characterEncoding);
              byte[] encryptedEntryBytes = this.encryptCipher.doFinal(EntryBytes);
              String encodedEncryptedEntry = this.base64Encoder.encode(encryptedEntryBytes);
              return encodedEncryptedEntry;
         synchronized public String decrypt(String encodedEncryptedEntry) throws Exception
              byte[] encryptedEntryBytes = this.base64Decoder.decodeBuffer(encodedEncryptedEntry);
              byte[] EntryBytes = this.decryptCipher.doFinal(encryptedEntryBytes);
              String recoveredEntry = new String(EntryBytes, characterEncoding);
              return recoveredEntry;
         private String characterEncoding;
         private Cipher encryptCipher;
         private Cipher decryptCipher;
         private BASE64Encoder base64Encoder = new BASE64Encoder();
         private BASE64Decoder base64Decoder = new BASE64Decoder();
    here is the main class :
    final byte[] myKey = "123456781234567812345678".getBytes("ASCII");
    final byte[] ivBytes = "12345678".getBytes("ASCII");
    // Entry encrypt agent that assumes the Entry is only ASCII characters
    DESedeEntryEncrypt EntryEncryptAgent = new DESedeEntryEncrypt(myKey, ivBytes, "ASCII");
    String Entry = "test test test";
    String encodedEncryptedEntry = EntryEncryptAgent.encrypt(Entry);

  • NoSuchMethodError at javax.crypto.SunJCE_b

    Please help new to security.
    JDK Version: j2sdk1.4.1_02
    OS: windows
    I am getting NoSuchMethodError on the line that has
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    I have used the -Djava.security.debug=all feature and that is the only exception thrown.
    java.lang.NoSuchMethodError
         at javax.crypto.SunJCE_b.<clinit>(DashoA6275)
         at javax.crypto.KeyGenerator.getInstance(DashoA6275)
         at CipherData.main(CipherData.java:13)
    Exception in thread "main"
    Code sniplet
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    public class CipherData {
    public static void main(String[] argv) {
    try {
    // ******* ERROR HERE ********* //
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    Key key = kg.generateKey();
    cipher.init(Cipher.ENCRYPT_MODE, key);

    Please check current version of java,and sure wondows path refer right
    %JAVA_HOME%\bin.

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

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

  • Javax.crypto.BadPaddingException: unknown block type

    Hello,
    I`m trying to decode some data but it keeps getting me: javax.crypto.BadPaddingException: unknown block type
    Here is my code:
    import java.io.*;
    import java.security.*;
    import java.security.spec.*;
    import java.security.interfaces.*;
    import javax.crypto.*;
    public class Main{
      public static void main(String args[]){
        try{
          byte[] pubKeyBytes  = getBytesFromFile("RSAPublicKey.der");
          byte[] privKeyBytes = getBytesFromFile("RSAPrivateKey.der");
          Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
          KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
          // decode public key
          X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKeyBytes);
          RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubSpec);
          System.out.println("Public Ket Spec: " + pubSpec.toString());
          System.out.println("Public Key: " + pubKey.toString());
          // decode private key
          PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes);
          RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec);
          System.out.println("Private Ket Spec: " + privSpec.toString());
          System.out.println("Private Key: " + privKey.toString());
          Cipher enc = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
          enc.init(Cipher.ENCRYPT_MODE, pubKey);
          Cipher dec = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
          dec.init(Cipher.DECRYPT_MODE, privKey);
          byte[] cyphered = new byte[] {
                  (byte) 0xA7, (byte) 0x08, (byte) 0x9A, (byte) 0xC0, (byte) 0x0A, (byte) 0x2F, (byte) 0x8D,
                  (byte) 0xA2, (byte) 0x3C, (byte) 0xC1, (byte) 0x49, (byte) 0x5B, (byte) 0x6A, (byte) 0xFF,
                  (byte) 0xF4, (byte) 0xC1, (byte) 0x9B, (byte) 0x87, (byte) 0x7C, (byte) 0xA2, (byte) 0xC5,
                  (byte) 0x6D, (byte) 0xB7, (byte) 0x84, (byte) 0xA5, (byte) 0x1A, (byte) 0xA5, (byte) 0x99,
                  (byte) 0xFF, (byte) 0x02, (byte) 0x16, (byte) 0xC4, (byte) 0x2D, (byte) 0x2E, (byte) 0x35,
                  (byte) 0xAC, (byte) 0x5B, (byte) 0x72, (byte) 0x51, (byte) 0xC1, (byte) 0xC7, (byte) 0x84,
                  (byte) 0xB5, (byte) 0x73, (byte) 0xAA, (byte) 0xB2, (byte) 0x85, (byte) 0x42, (byte) 0x7F,
                  (byte) 0xD2, (byte) 0xED, (byte) 0x0B, (byte) 0x0F, (byte) 0xD3, (byte) 0x8D, (byte) 0xFA,
                  (byte) 0xC4, (byte) 0x75, (byte) 0x16, (byte) 0x18, (byte) 0x62, (byte) 0xDC, (byte) 0xF9,
                  (byte) 0x84, (byte) 0xEF, (byte) 0x41, (byte) 0x76, (byte) 0x97, (byte) 0x63, (byte) 0x55,
                  (byte) 0x65, (byte) 0x4E, (byte) 0x7A, (byte) 0x0E, (byte) 0xC5, (byte) 0x2F, (byte) 0xC7,
                  (byte) 0xBC, (byte) 0x17, (byte) 0x83, (byte) 0x67, (byte) 0x3F, (byte) 0xD9, (byte) 0xC8,
                  (byte) 0x62, (byte) 0x3D, (byte) 0x74, (byte) 0xC6, (byte) 0x15, (byte) 0xBE, (byte) 0xA2,
                  (byte) 0xD8, (byte) 0x7C, (byte) 0x9F, (byte) 0x2A, (byte) 0x5A, (byte) 0xE5, (byte) 0xE9,
                  (byte) 0x02, (byte) 0x12, (byte) 0x6B, (byte) 0x78, (byte) 0x07, (byte) 0xB6, (byte) 0xF7,
                  (byte) 0xE3, (byte) 0x80, (byte) 0xCB, (byte) 0x20, (byte) 0xF5, (byte) 0x6D, (byte) 0xA8,
                  (byte) 0x56, (byte) 0xC6, (byte) 0xF7, (byte) 0xEB, (byte) 0xA4, (byte) 0xA4, (byte) 0xA6,
                  (byte) 0x28, (byte) 0xC2, (byte) 0x2D, (byte) 0x70, (byte) 0xAE, (byte) 0x99, (byte) 0xC8,
                  (byte) 0x6E, (byte) 0x22, (byte) 0xA0, (byte) 0x4F, (byte) 0xE8, (byte) 0x69, (byte) 0x05,
                  (byte) 0x6B, (byte) 0x63, (byte) 0xF0, (byte) 0x83, (byte) 0xD8, (byte) 0x2D, (byte) 0xA4,
                  (byte) 0xE2, (byte) 0x6A, (byte) 0x45, (byte) 0x88, (byte) 0xF6, (byte) 0xF2, (byte) 0x3B,
                  (byte) 0xF9, (byte) 0x40, (byte) 0x27, (byte) 0x53, (byte) 0x4D, (byte) 0xDB, (byte) 0x22,
                  (byte) 0x50, (byte) 0x5E, (byte) 0x30, (byte) 0xAC, (byte) 0x70, (byte) 0x53, (byte) 0x32,
                  (byte) 0x93, (byte) 0xC0, (byte) 0xF4, (byte) 0x5D, (byte) 0xDE, (byte) 0xC7, (byte) 0xCF,
                  (byte) 0xCC, (byte) 0x79, (byte) 0x1E, (byte) 0xE3, (byte) 0xBA, (byte) 0x2A, (byte) 0xB5,
                  (byte) 0xB3, (byte) 0xBB, (byte) 0x2D, (byte) 0x0A, (byte) 0x2E, (byte) 0x13, (byte) 0x56,
                  (byte) 0xDA, (byte) 0x29, (byte) 0x28, (byte) 0x9D, (byte) 0xA3, (byte) 0xB6, (byte) 0x95,
                  (byte) 0xA0, (byte) 0xFF, (byte) 0xAC, (byte) 0x19, (byte) 0x35, (byte) 0xD9, (byte) 0x5A,
                  (byte) 0xA4, (byte) 0xF6, (byte) 0x38, (byte) 0xF0, (byte) 0xBB, (byte) 0x8A, (byte) 0xC8,
                  (byte) 0x01, (byte) 0xBA, (byte) 0xDE, (byte) 0x4D, (byte) 0x4C, (byte) 0xB0, (byte) 0xBA,
                  (byte) 0x44, (byte) 0xB1, (byte) 0x60, (byte) 0xA8, (byte) 0x81, (byte) 0x94, (byte) 0x15,
                  (byte) 0x88, (byte) 0x5D, (byte) 0x92, (byte) 0x88, (byte) 0x50, (byte) 0xC7, (byte) 0x25,
                  (byte) 0xEC, (byte) 0xAB, (byte) 0x03, (byte) 0x82, (byte) 0x30, (byte) 0x13, (byte) 0xB6,
                  (byte) 0xC0, (byte) 0xC8, (byte) 0xA6, (byte) 0x8F, (byte) 0xD5, (byte) 0xB7, (byte) 0x78,
                  (byte) 0x10, (byte) 0x81, (byte) 0x5D, (byte) 0xF3, (byte) 0x7C, (byte) 0xAB, (byte) 0x5B,
                  (byte) 0xC3, (byte) 0x38, (byte) 0xA5, (byte) 0xE3, (byte) 0x8B, (byte) 0x85, (byte) 0x0B,
                  (byte) 0xC9, (byte) 0x54, (byte) 0x29, (byte) 0x79};
          System.out.println("Testing encoding: ");
          byte[] uncyph = cyphered;
          System.out.println(dec.doFinal(uncyph));
        }catch(Exception e){
          System.out.println(e.toString());
      public static byte[] getBytesFromFile(String filePath) throws IOException {
        File file = new File(filePath);
        InputStream is = new FileInputStream(file);
        long length = file.length();
        byte[] bytes = new byte[(int)length];
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0)
            offset += numRead;
        if (offset < bytes.length)
            throw new IOException("Could not completely read file "+file.getName());
        is.close();
        return bytes;
    }

    jverd wrote:
    sabre150 wrote:
    Your ciphertext is 256 bytes so your RSA modulus needs to be 2048 bytes (256 bytes). ???
    2048 bits perhaps?:-)))) Aint this new site wonderful. I can edit my post even after someone has responded to it!

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

  • 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

Maybe you are looking for

  • Saving multiple scanned pages as single document with 8620

    I need to scan multiple pages and save as a single document. I am scanning using the AiO remote app and my iPad Air. I see the "Add Pages" icon and use it, but when I save, it saves as individual documents. I need multiple pages to be a single docume

  • How to get rid of timestamp when taking notes in preview?

    Hi, I frequently annotate (using the 'take note' function) when reading pdfs and I would like to get the date and timestamp off of the notes when I am taking them. Is there any setting where I can "disable" the date and timestamp from appearing? So t

  • ITunes 10.5.1 no longer plays purchased movies

    Hello guys/gals, So this is a problem I've been struggling to find an answer for and I've not gotten desperate enough to pay $30 for the one-time incident fee, YET. Currently own a Macbook Pro w/ i7 core. Running 10.6.8 (Snow Leopard) and iTunes 10.5

  • Moved drive to USB Port on Time Capsule and TM no longer sees backups

    I moved my FireWire attached HD from a direct attachment to my Mac Pro to attached via the USB port on my Time Capsule. Time Machine now wants to start over, and does not see the previous backups. The destination drive name did not change, other than

  • SAP Netweaver ABAP Trial 7 installation problem

    Hi, I tried installing SAP netweaver for ABAP trail in my virtual pc of windows XP. I am able to install sapinst successfully but when i am trying to install sapinstgui, I am getting error with JAVA JVM. Program is starting... Please wait!   Path: C: