Legal trouble possible using javax.crypto?

h4. The problem
I'm currently doing an internship in france, where we need to use RSA encryption in our application as a part of our authentification.
As we could possibly sell our application in all over the world and there seem to be complicate cryptological laws my question is:
Can one possibly get into legal trouble for using the java encryption methods?
I'm totally fine with using a relatively weak encryption (for exemple 512 Bit for RSA) and I do not need to change the policy files (as I understand it,
the RSA keysize is not restricted by the standard policy files anyways) or do stronger encryption than this.
I already found something to show that exporting an application like this is not a problem.
If someone has a similar question, it can be found here: +[http://www.ssi.gouv.fr/fr/reglementation/regl_crypto.html]->Exportation et transfert de moyens de+
cryptologie depuis la France->EXPORTATION VERS D'AUTRES ÉTATS->"assurant exclusivement des fonctions d’authentification ou de contrôle d’intégrité"->LIBRE.
But my problem is not the export OUT of france but the import INTO another country (like china or russia for example).
As I am only a student, consulting a lawyer is not an option for me (too expensive).
I've ready many documents who all state what is forbidden and allowed but they mostly talk about providing cryptography and not using it.
So while logically it makes sense to say "if its not written there it must be allowed", I would like to have something concrete to show my company.
Is there an easy to prove, logical argument for this?
h4. Sources I've already consulted:
*1. [The Wassenaar Arrangement|http://www.wassenaar.org/]*
In [5.A.2.a.1.b.1.|http://www.wassenaar.org/controllists/2007/WA-LIST%20(07)%202%20Corr.%20word%20files/08%20-%20WA-LIST%20(07)%202%20Corr.%20-%20Cat%205P2.doc] it states it regulates "An "asymmetric algorithm" where the security of the algorithm is based on any of the following:
1.     Factorisation of integers in excess of 512 bits (e.g., RSA);[...]"
So while it says "hey, be careful with anything more than 512 Bits" it does not explicitly state (at least I did not find it) "anything with 512 Bits or
less is totally unproblematic".
The list of participating states is quite huge so this could help me a lot if I could prove that this is not a problem:
The states are: Argentina, Australia, Austria, Belgium, Bulgaria, Canada, Croatia, Czech Republic, Denmark, Estonia, Finland, France, Germany, Greece,
Hungary, Ireland, Italy, Japan, Latvia, Lithuania, Luxembourg, Malta, Netherlands, New Zealand, Norway, Poland, Portugal, Republic of Korea, Romania,
Russian Federation, Slovakia, Slovenia, South Africa, Spain, Sweden, Switzerland, Turkey, Ukraine, United Kingdom,
United States
*2.[RSA Laboratories: What are the cryptographic policies of some countries?|http://www.rsa.com/rsalabs/node.asp?id=2333]*
There is a table showing each state in a category from 1 - no restriction for cryptography to 5 - "cryptography is tightly controlled". Unfortunately not a
great part of those countries are in category 1. Unfortunatly it does not seem to differentiate between providing cryptography and using it.
*3. [Java ™ Cryptography Architecture (JCA) Reference Guide|http://java.sun.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html]*
It speaks about cryptographic restrictions that are in place and how you can lift them with special certificates and whatnot but it does not state that
operating within those restrictions is legal inside every country.
*4. [Bert-Jaap Koops homepage - Crypto Law Survey - Overview per country|http://rechten.uvt.nl/koops/cryptolaw/cls2.htm#co]*
People's Republic of China
Export/ import controls
"+By State Council Order No. 273, "Commercial Use Password Management Regulations", published on 15 October 1999 and in effect since 7 October 1999, import and export of encryption products requires a license by the State Encryption Management Commission. According to a "clarification letter" sent to US+
+businesses in China in early March 2000, this involves only hardware and software for which encryption and decoding operations are core functions. As a+
+result, products in which cryptography is only built-in (such as mobile phones and browser software) are exempted. Moreover, the letter clarified that the+
+regulations do not entail key escrow.+
+However, the clarification letter only seems to apply to pre-2000 products. All products since 2000 seem to require a license.+"
So does this mean that Java needs a license (which it probably has I hope) or our product which uses it does also need it?
*5. Sun Developer Forums - Security - Cryptography*
Search for keyword "legal": nothing which matches my problem found
Search for keyword "import": nothing which matches my problem found within the first 13 pages
Search for keyword "china": nothing which matches my problem found
So, any backed up help will be greatly appreciated. Thanks!
Edited by: kirdie on Jun 30, 2008 2:54 AM
Edited by: kirdie on Jun 30, 2008 3:00 AM
Edited by: kirdie on Jun 30, 2008 3:01 AM
Edited by: kirdie on Jul 1, 2008 5:35 AM
Edited by: kirdie on Jul 3, 2008 6:29 AM

In my opinion you are only partly right, it's a legal question about software :-)
And unfortunately I can not pay a lawyer with my student earnings.
As this question is very broad (it concerns everyone who sells java software which utilises the crypto package) am very interested in how you cope with this problem.
Do you ignore it? Use weak encryption only? Ask each state for a licence? Don't sell your product to certain countries?
P.S: Or should i rather move the topic to "Other Security APIs, Tools, and Issues"?
Edited by: kirdie on Jul 4, 2008 12:39 AM

Similar Messages

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

  • 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

  • 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

  • HMAC_SHA1 encryption using javax.crypto.MAC performance problems in SPARC

    Hi, I'm trying to implement a method to synchronize TOTP cards. In case the server clock and the card clock were different. So I generate a lot of TOTP keys in case to compare it with the real key so at the end I get both of the times in the server. That works in x86 (Sunfire x2200) perfectly and does not take a lot of time doing that (like 2 minutes generating 800000 keys). But when I test it on Oracle BM SPARC (T1000 LDOM 1.1) takes I lot of time. I did all kind of profiling stuff but all point to the method of the generation the TOTP in the HMAC_SHA1.
    here is the code (based on JBoss 6 OTP implementation)
    public synchronized static String generateTOTP(String key, String time,  int returnDigits, String crypto) throws GeneralSecurityException {
              String result = null;
              byte[] hash;
              // Using the counter
              // First 8 bytes are for the movingFactor
              // Complaint with base RFC 4226 (HOTP)
              while(time.length() < 16 ) {
                   time = "0" + time;
              // Get the HEX in a Byte[]
              byte[] msg = hexStr2Bytes(time);
              // Adding one byte to get the right conversion
              byte[] k = hexStr2Bytes(key);
              hash = hmac_sha1(crypto, k, msg);
              // put selected bytes into result int
              int offset = hash[hash.length - 1] & 0xf;
              int binary =
                   ((hash[offset] & 0x7f) << 24) |
                   ((hash[offset + 1] & 0xff) << 16) |
                   ((hash[offset + 2] & 0xff) << 8) |
                   (hash[offset + 3] & 0xff);
              int otp = binary % DIGITS_POWER[ returnDigits ];
              result = Integer.toString(otp);
              while (result.length() < returnDigits ) {
                   result = "0" + result;
              return result;
    private static byte[] hmac_sha1(String crypto, byte[] keyBytes, byte[] text) throws GeneralSecurityException {
              Mac hmac;
              hmac = Mac.getInstance(crypto);
              SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW");
              hmac.init(macKey);
              return hmac.doFinal(text);
    }The release of the version to production is delayed about this. I need help either to use another library or finding the right configuration for the SPARC.
    Thanks in advance to everybody.
    danielfjb

    Well It is the only approach that I came up. It is supposed the code runs max. one time per user in production, that depends in the synchronization between the server clock and the OTP card clock.
    Basically the algorithm takes two consecutive keys (each 30 seconds the password changes) from the user, saving the time (server clock) for each one when the user clicks next. With both keys the server look up at what time (in server clock) the key has been generated. Performing a simple subtraction I can get the difference of times when the user generates the otp and when the server generates it.
    The algorithm simply look up five days ago, and five days further the same key each 30 simulated seconds, and reports the time when it founds an equal key. It's a brute force search, but in this case I really don't know how to do it differently.
    So the problem is in the type of server, because in the x86 runs the synchronization in 3 minutes or less, but in the SPARC takes 30 minutes or maybe more. It should be some native code that has problems with this implementation of javax.crypto.Mac
    Hope I do make my self clear
    Thank you

  • Crypt::cbc encrypt / decrypt using javax.crypto

    I am having a bit of a time encrypting with crypt::cbc and decrypting with java. To get to the point, here is my code, perl first, java 2nd - I have tried to keep things very simple.
    #!/usr/local/bin/perl -w
    use strict;
    use Crypt::CBC 2.30;
    die "Need to specify a file" if(!(my $infile = shift));
    my $key = q(nvA9s$233eOrlQG4);
    my $iv = q(0123456701234567);
    my $bufsize = 16384;
    my $cipher = Crypt::CBC->new({
              'key'          => $key,
              'iv'          => $iv,
              'header'     => 'none',
              'cipher'     => 'Rijndael',
              'keysize'     => '16',     #forced - default is 32 bytes
              'padding'     => 'standard',     #PKCS5
              'blocksize'     => '16',
              'literal_key'     => '1',          #do not MD5 hash key
    open (FORIG,"$infile")|| die "can't open file: $!";
    open (FCRYPT,">$infile.crypt")|| die "can't open file: $!";
    $cipher->start('encrypting');
    while(my $readsize = sysread(FORIG, my $buf, $bufsize)) {
         print FCRYPT $cipher->crypt($buf);
    print FCRYPT $cipher->finish();
    close FCRYPT;
    close FORIG;
    now the java:
    // i have elided the import stmts for brevity
    public class AESEncrypter {
         Cipher ecipher;
         Cipher dcipher;
         byte [] buf = new byte[1024];
         public AESEncrypter() {
              String strKey = "nvA9s$233eOrlQG4";
              byte[] keyBytes = null;
              try {
                   keyBytes = strKey.getBytes("UTF-8");
              } catch(java.io.UnsupportedEncodingException ex) {
                   ex.printStackTrace();
              byte[] iv = new byte[] { 0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7 };
              IvParameterSpec ivSpec = new IvParameterSpec(iv);
              try {
                   ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                   dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
              } catch (NoSuchAlgorithmException e) {
                   e.printStackTrace();
              } catch (NoSuchPaddingException e) {
                   e.printStackTrace();
              try {
                   SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
                   ecipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
                   dcipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
              } catch (InvalidKeyException e1) {
                   e1.printStackTrace();
              } catch (InvalidAlgorithmParameterException e1) {
                   e1.printStackTrace();
         public void encrypt(InputStream in, OutputStream out) {
              try {
                   out = new CipherOutputStream(out, ecipher);
                   int numRead = 0;
                   while((numRead = in.read(buf)) >= 0) {
                        out.write(buf, 0, numRead);
                   out.close();
              } catch(java.io.IOException e) {
                   e.printStackTrace();
         public void decrypt(InputStream in, OutputStream out) {
              try {
                   out = new CipherOutputStream(out, dcipher);
                   int numRead = 0;
                   while((numRead = in.read(buf)) >= 0) {
                        out.write(buf, 0, numRead);
                   out.close();
              } catch(java.io.IOException e) {
                   e.printStackTrace();
         public static void main(String args[]) {
              if(args.length != 1) {
                   System.out.println("Usage: java AESEncrypter filename");
                   System.exit(0);
              AESEncrypter encrypter = new AESEncrypter();
              try {
         //          encrypter.encrypt(new FileInputStream(args[0]), new FileOutputStream("Java_encrypted.txt"));
                   encrypter.decrypt(new FileInputStream(args[0]), new FileOutputStream("Java_decrypted.txt"));
              } catch (java.io.FileNotFoundException ex) {
                   ex.printStackTrace();
    so with file named whoop.txt containing the following contents:
    whoop
    whoop
    whoop
    whoop
    I do:
    $>./encrypt.pl whoop.txt
    and get the resulting file whoop.txt.crypt. then I do
    $>java AESEncrypter whoop.txt.crypt
    and get the resulting file Java_decrypted.txt. when I do a hex dump of this file:
    $>dump.pl Java_decrypted.txt
    i get the following
    /0 /1 /2 /3 /4 /5 /6 /7 /8 /9 /A /B /C /D /E /F 0123456789ABCDEF
    0000 : 47 58 5F 5F 40 3A 47 58 5F 5F 40 3A 47 58 5F 5F GX__@:GX__@:GX__
    0010 : 70 0A 77 68 6F 6F 70 0A p.whoop.
    I have tried to ensure that everything matches between the perl and java code, however I am obviously missing something. Thanks in advance for any ideas!
    Gregg

    i have hardcoded the IV in perl as:
    my $iv = q(0123456701234567);
    and in the .java file as:
    byte[] iv = new byte[] { 0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7 };
    IvParameterSpec ivSpec = new IvParameterSpec(iv)
    Are these not compatible?
    thanks - gh

  • How javax.crypto can do "ALG_DES_CBC_ISO9797_M2" padding?

    First Question :
    Do "javacardx.crypto, javacard.security" can use outside applet in card?
    I try to use this on client-side ?(in RMI, we say client-side is reader , card is host-side) but it's not work , throw exception.
    I write javacard RMI style. My problem is...
    Source code below is work when it write in applet (card - side)
    but in client-side (reader -side) I copy it to client - side code and test to run, if fail --> throw exception 0x3 - javacard.security.CryptoException.NO_SUCH_ALGORITHM
    It seem to be "javacardx.crypto" and "javacard.security" is make for use in applet in card only. Did I misunderstand?
    if it make for use in applet only, how is possible to do like this " card use privatekey to sign message and send to reader , reader use card's publickey to verify that card sign this signature or not."
    or
    "card use reader's publickey to encrypt message and send to reader, then reader use privatekey to decrypt message (reader authencate itself) "
    because I can't do any of cipher , keybuilder in RMI-client side(reader)
    Cipher.getInstance(Cipher.ALG_RSA_PKCS1,false);
    it will throw nullPointerException
    and if (change false to true)
    Cipher.getInstance(Cipher.ALG_RSA_PKCS1,true);
    throw exception 0x3 - javacard.security.CryptoException.NO_SUCH_ALGORITHM
    after that I swap this line with
    pri_key = (RSAPrivateKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PRIVATE,KeyBuilder.LENGTH_RSA_512, false);
    since it will do this first (i swap the line already) it also throw exception 0x3 - javacard.security.CryptoException.NO_SUCH_ALGORITHM
    also be the same result with swap
    kp = new KeyPair(KeyPair.ALG_RSA,(short)KeyBuilder.LENGTH_RSA_512 );
    to a first line
    it throw exception 0x3 - javacard.security.CryptoException.NO_SUCH_ALGORITHM
    Please help me
    RSAPrivateKey pri_key;
    RSAPublicKey pub_key;
    KeyPair kp;
    Cipher RSAcipher;
    RSAcipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1,false);
    pri_key = (RSAPrivateKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PRIVATE,KeyBuilder.LENGTH_RSA_512, false);
    pub_key =(RSAPublicKey) KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PUBLIC,KeyBuilder.LENGTH_RSA_512, false);
    kp = new KeyPair(KeyPair.ALG_RSA,(short)KeyBuilder.LENGTH_RSA_512 );
    kp.genKeyPair();
    pri_key = (RSAPrivateKey) kp.getPrivate();
    pub_key = (RSAPublicKey) kp.getPublic();
    //ENCRYPT
    RSAcipher.init(pub_key, Cipher.MODE_ENCRYPT);
    t_cipherLengthRSA = RSAcipher.doFinal(plaintxt,(short)0, (short)plaintxt.length, t_cipherText, (short)0);
    //DECRYPT
    RSAcipher.init(pri_key, Cipher.MODE_DECRYPT);
    RSAcipher.doFinal(ciphertxt,(short)0,(short) t_cipherLengthRSA, temp1, (short)0);
    I just think to new solution , client-side(reader) is use normal crypto class from javax.crypto , java.security
    if I use javax.crypto
    Question : Can it do "ALG_DES_CBC_ISO9797_M2" padding?
    I want to use card to encrypt/sign and send to reader. Then reader decrypt/verify it.

    See my answer to your other post "RMI client-side -> how to encrypt,decrypt in client-side"
    Jan

  • 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

  • Javax.crypto.* problem in WLW

    Hi,
    I am trying to encrypt a String in WLW 8.1 SP2.
    The IDE is not recognizing javax.crypto.* package. When I use the same code and
    execute it with TextPad, it works just fine.
    FYI, the non-WLS JDK is 1.4.1_01-b01 and WLS uses 1.4.1_05.
    What do I need to do to be able to use javax.crypto.* packages in WebLogic? Any
    helpis greatly appreciated.
    Thanks, Eric

    I had to add it manually:(
    * Go to application properties (Tools Menu > Application Properties... Menu
    Item)
    * Under WebLogic Server look for Server classpath additions:
    * Click add jar
    * Navigate to jdk\jre\lib\jce.jar
    * Add the jar file
    "Eric J" <[email protected]> wrote in message
    news:404e34a9$[email protected]..
    >
    Hi,
    I am trying to encrypt a String in WLW 8.1 SP2.
    The IDE is not recognizing javax.crypto.* package. When I use the samecode and
    execute it with TextPad, it works just fine.
    FYI, the non-WLS JDK is 1.4.1_01-b01 and WLS uses 1.4.1_05.
    What do I need to do to be able to use javax.crypto.* packages inWebLogic? Any
    helpis greatly appreciated.
    Thanks, Eric

  • Javax.crypto classes not found using JDK1.4

    We're trying to upgrade to using JDK 1.4, in which the Java Cryptography Extensions are incorporated into the JDK. However, iPlanet does not seem to be able to find the classes that make up the extension.
    If I write a simple Java app that creates a java.crypto.SecretKey, and run it from the command line on our web server machine using our Java 1.4 JDK, it runs fine.
    If I adapt the same program into a simple servlet and run it from within iPlanet, it fails with a ClassNotFound error trying to find javax/crypto/NoSuchPaddingException.
    I've done a lot of variations trying to hone in on the problem, but I'm running out of options. Does anyone have any information or experience with this particular problem?
    We're running iPlanet 6.0 SP5 and the JDK is build 1.4.1-b21.

    David,
    I'm also facing the same problem, none of the javax.crypto classes are found.When I'm running the Encryption code it's working standlone and in Tomcat 4.0 but in IPlanet it's giving me ClassNotFound.
    I have added jce.jar in the classpath as mentioned and it's getting picked.
    But you have mentioned some start-jvm files, I'm not able to find these files.
    Can u please summarize what all settings you did?.
    As it's urgent if possible mail me at,
    [email protected] (OR)
    [email protected]
    Sachin

  • Javax.crypto.BadPaddingException: pad block corrupted  when using Java 1.4

    I'm getting a javax.crypto.BadPaddingException: pad block corrupted Exception while working on converting our existing java jdk 1.2 to java 1.4. Any suggestions would be great. Here are the specifics:
    We have a web application that been running for 3+ years under java jdk 1.2 & jce_1_2.jar. Within the application we are exchanging data (XML) with a customer using the following encryption scheme:
    1) We create a one time DESede key through the KeyGenerator class passing in ("DESede", "BC")
    2) We encrypt the data with this one time key using ("DESede/ECB/PKCS5Padding", "BC")
    3) This one time key is then encrypted using ("RSA/ECB/PKCS1Padding", "BC") and customer's public key
    4) We create a signature with our private key, which they have the public key for.
    This is process/api that we required to use for their API's and its worked fine under 1.2, with "ABA" as the provider. Now moving to 1.4, I'm using BouncyCastle as the provider.
    Other differences, the keystore was created under 1.2 and in 1.2 it was defined as "JCEKS" provider "SunJCE" under 1.4 I changed them to "JKS" and "SUN" . I would get bad header exceptions when reading from the keystore until I changed it. I don't think its the BouncyCastle since I was able to download the 1.2 version of BC and get the existing app to work and I also got the 1.4 version of BC to work under the existing 1.2 application.
    So something seems to be different with the algorithms/padding, but I can't seem to find it. I tried the following: "RSA" "RSA/ECB" "RSA//PKCS1Padding" "NoPadding" also changed the DESede algorithm with no luck. All I know is that its failing on the decryption of the one time key, since its failing on the customer side, I don't have much other insight into it, other then the exception that they sent me.
    More info: getting error on Java: build 1.4.2_02-b03 on Solaris 5.8
    Existing application running: Java JDK_1.2.2_10 on Solaris 5.8
    BouncyCastle: bcprov-jdk14-124.jar
    Thanks

    Here is the stackTrace that I was sent:
    20040804;10:29:37: javax.crypto.BadPaddingException: pad block corrupted
    20040804;10:29:37: at org.bouncycastle.jce.provider.JCEBlockCipher.engineDo
    Final(JCEBlockCipher.java:460)
    20040804;10:29:37: at javax.crypto.Cipher.doFinal(Cipher.java:1129)
    20040804;10:29:37: at com.customer.crypto.SymmetricCryptor.decrypt(SymmetricCryptor.java:105)
    20040804;10:29:37: at com.customer.crypto.SymmetricCryptor.decryptToStr
    ing(SymmetricCryptor.java:95)
    20040804;10:29:37: at com.customer.api.Data.DataServlet doPost(DataServlet.java:88)

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

  • How can I print a html Using javax.print

    Hi friends,
    I am in big trouble . I use following code to print a html file using javax.print api.
    import java.io.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    import javax.print.event.*;
    public class PrintPS
         public static void main(String args[]) {
              PrintPS html = new PrintPS();
         public PrintPS() {
         DocFlavor flavor = DocFlavor.INPUT_STREAM.TEXT_HTML_HOST;
         PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
         aset.add(MediaSizeName.ISO_A4);
         aset.add(new Copies(1));
         aset.add(MediaTray.MAIN);
         PrintService pservices = PrintServiceLookup.lookupDefaultPrintService();
         if(pservices==null)
              System.out.println(" printer not found");
         if (pservices!= null) {
         System.out.println("selected printer " + pservices.getName());
         DocPrintJob pj = pservices.createPrintJob();
         try {
         InputStream fis = new FileInputStream("abc.html");
         Doc doc = new SimpleDoc(fis, flavor, null);
    System.out.println("printing started ");
         pj.print(doc, aset);
    System.out.println("printing completed");
         } catch (IOException ie) {
         System.err.println(ie);
         } catch (PrintException e) {
         System.err.println(e);
    This code gives me "sun.print.PrintJobFlavorException: invalid flavor"
    So i use all four TEXT_HTML flavor but i do not find the solution.
    I am able to print pdf, jpg, gif files but i can not able to print txt and html file.
    My printer supports txt and html printing becaue i do printing directolly by browser's or notpad's print command .

    Hi friends,
    I am in big trouble . I use following code to print a
    html file using javax.print api.Use Code Tags
    http://forum.java.sun.com/help.jspa?sec=formatting
    My printer supports txt and html printing becaue i do
    printing directolly by browser's or notpad's print
    command .Notepad & your browser prob. convert to the HTML/text(1) into the printers native format.
    1) I am suprised that it does not print text.

  • 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

Maybe you are looking for