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

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

  • 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

  • Error in running encryption/decryption using DES in Websphere Dev't Client

    Hello!
    I have a code used to encrypt / decrypt a string (password). I have already tested it using Netbeans and it is working. But when I tried to add the java code to an existing web project using Websphere Development Client,, javax.crypto.* is not recognized. Then I imported JCE.jar.
    The java code contains no errors then, but when I started to run the project, it gives an Error 500. And below is the Console's error message:
    E SRVE0026E: [Servlet Error]-[javax.crypto.spec.PBEKeySpec: method <init>&#40;[C[BI&#41;V not found]: java.lang.NoSuchMethodError: javax.crypto.spec.PBEKeySpec: method <init>([C[BI)V not found[/b]
    Have I missed something to add? Or other things that I should do upon importing this jar file?
    Please help.
    Advance thanks for your reply.
    misyel

    I dont know what version of Java that my Websphere's using. But I am very sure that it is outdated. I am using Websphere 5.0. For Netbeans, it is JDK1.5.
    I imported the JCE from JDK 1.5 on Websphere.
    I think the code works perfectly fine. Actually it was my friend's code for encryption but they are using Eclipse for development (almost the same from Websphere but somehow different from it.)
    My idea is that I cant match the versions of the jarfiles used in my project. As much as I wanted to change the imported jar files, I couldn't for when I replaced the existing jar files, more and more errors occur.
    can we have any alternative ways of importing the jar files? or is there any other code that might help that will not use the JCE.jar?
    I really appreciate your response. thanks
    misyel

  • 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

  • Encrypt/decrypt using update

    Hi,
    can someone give me an encrypt/decrypt pair of code samples that use the cipher.update() call.
    i am trying it like that but apparently it doesn't work
    byte[] temp = new byte[message.length/2];
    byte[] temp2 = new byte[message.length/2];
    System.arraycopy(message, 0, temp, 0, temp.length);
    System.arraycopy(message, temp.length, temp2, 0, temp.length);
    ciphertext = new byte[message.length];
    System.arraycopy(symmetricCipher.update(temp), 0, ciphertext, 0, temp.length);
    System.arraycopy(symmetricCipher.doFinal(temp2), 0, ciphertext, temp.length, temp.length);

    ode]
    >
    I don't see how using the inputstream i would avoid
    the memory error, when passing anything over
    10,000,000. Unless you mean I split the input, and
    write small chunks into disk as I encrypt them?Your basic problem is that you have the data as one large array. I don't know how and why you created this large array; I would not to create it unless there was no other way.
    Since it does not make sense to create one large encrypted byte array and given that you have a byte array then you can use either
    1) Create a ByteArrayInputStream and wrap it in a CipherinputStream. This would allow you to encrypt the array in a sequential manner a few KBytes at a time.
    or
    2) Encrypt the array a few KBytes at a time using a simple update(array, start, length) that returns the encrypted bytes.
    But first, I would try to avoid creating the large 'cleartext' array.

  • Encrypt/Decrypt using REPLACE/TRANSLATE function

    Hi,
    Can someone please provide me any procedure/function which encrypts/decrypts a string using REPLACE/TRANSLATE function?
    Thanks
    Dinakar

    example with TRANSLATE:
    CREATE OR REPLACE function temp_encrypt (p_value IN VARCHAR2)
    RETURN VARCHAR2 IS
    BEGIN
        RETURN(TRANSLATE(p_value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'BCDEFGHIJKLMNOPQRSTUVWXYZA'));
    END;
    CREATE OR REPLACE function temp_decrypt (p_value IN VARCHAR2)
    RETURN VARCHAR2 IS
    BEGIN
        RETURN(TRANSLATE(p_value, 'BCDEFGHIJKLMNOPQRSTUVWXYZA', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'));
    END;
    SQL> SELECT temp_decrypt('MY TEST') FROM dual;
    TEMP_DECRYPT('MYTEST')
    LX SDRS
    SQL> SELECT temp_encrypt('LX SDRS') FROM dual;
    TEMP_ENCRYPT('LXSDRS')
    MY TESTyou may combine this with REPLACE() ...

  • Newbie need to encrypt/decrypt using password

    Hi all,
    I need to encrypt some data store it in database and retrieve it at another time and decrypt it. The user will supply the password. I have no idea on how to do it. This encryption must be very strong like PGP. I can use the jars provided by Sun.
    rgds
    Antony Paul

    package login.view;
    import java.io.UnsupportedEncodingException;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    //import org.myorg.SystemUnavailableException;
    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;
    import sun.misc.CharacterEncoder;
    public final class PasswordService
    private static PasswordService instance;
    private PasswordService()
    public synchronized String encrypt(String plaintext) throws Exception
    MessageDigest md = null;
    try
    md = MessageDigest.getInstance("SHA"); //step 2
    catch(NoSuchAlgorithmException e)
    throw new Exception(e.getMessage());
    try
    md.update(plaintext.getBytes("UTF-8")); //step 3
    catch(UnsupportedEncodingException e)
    throw new Exception(e.getMessage());
    byte raw[] = md.digest(); //step 4
    String hash = (new BASE64Encoder()).encode(raw); //step 5
    return hash; //step 6
    public static synchronized PasswordService getInstance() //step 1
    if(instance == null)
    return new PasswordService();
    else
    return instance;
    You can use this classas below.................
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    HttpSession session=request.getSession(true);
    //HttpSession session = new HttpSession();
    LoginBean login =(login.view.LoginBean) form;
    String LoginName= login.getLoginName();
    String LoginPassword = login.getLoginPassword();
    try
    session.setAttribute("LoginPassword",PasswordService.getInstance().encrypt(LoginPassword));
    catch(Exception e)
    session.setAttribute("LoginName",LoginName);
    return mapping.findForward("success");
    }

  • 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 &Eacute;TATS->"assurant exclusivement des fonctions d&rsquo;authentification ou de contr&ocirc;le d&rsquo;int&eacute;grit&eacute;"->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 &trade; 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

  • Memory does not get released after encrypting/ decrypting files.

    I am using javax.crypto package to encypt/decrypt files but the problem is that once a big file (around 100- 700 mb) is encrypted there is spike in memory of 70 Mb (first time) and whole of this memory is not released after execution is finished. I have kept my application run for days but this memory do not come down.
    Interesting thing is if I encrpyt/ decrypt the same file again and again the memory do not rise by 70 Mb, but for first 3-4 iterations 5-8 Mb of memory is released in each iteration and after that memory starts increasing again in chunk of 2-5 Mb and after few iteration some memory get released but in all the memory always increases. The code to encrypt file is simple
    Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
    byte[] salt = generateRandomBytes(16);
    Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes("123456", salt, 1000);
    SecretKey key = new SecretKeySpec(rfc.getBytes(32), "AES");
    c.init(Cipher.ENCRYPT_MODE, key );
    FileOutputStream fos = new FileOutputStream(encryptedFile);
    CipherOutputStream cos = new CipherOutputStream(fos);
    FileInputStream fis = new FileInputStream(largeInputFile);
    int len = 0;
    byte[] buf = new byte[1024 * 128];
    while((len = fis.read(buf)) != -1) {
       cos.write(buf, 0, len);
    cos.close();
    fis.close();
    This is simple observation I have seen in my program:
    I am using Windows 7 64 bit with 16 GB RAM Intel Core 2 Duo 3.00 GHz and file encrypted was 700 MB size
    Explanation
    Memory Usage (As shown in Windows Task Manager Private Working Set column)
    When program starts
    9924 K
    After first iteration of encryption
    81,180 K
    Second Iteration
    78,254 K
    3 Iteration
    74,614 K
    4 Iteration
    69,523 K
    5 Iteration
    72,256 K
    6 Iteration
    70,152 K
    7 Iteration
    83,327 K
    8 Iteration
    85,613 K
    9 Iteration
    95,124 K
    10 Iteration
    92,698 K
    11 Iteration
    94,670 K
    I kept the iteration on for 2000 iteration, the same pattern was observed and at the end memory usage 184,951 K, this memory was not released after calling System.gc() also.
    What could be the possible problem, is it the CipherOutputStream or Cipher class having some memory leak or I am doing something wrong here?

    ash wrote:
    We are using WebLogic Server 7.0 runing on Solaris 2.7.
    We are experiencing a problem where the memory does not seem to be released after
    the application has been shut down.What do you mean by "application has been shut down"? Is the server
    process running or not? Is it a zombie?
    The
    Unix 'top' command reports that memory has not been reclaimed by the O/S. What exactly has it reported? If the process is gone, then I'm pretty
    sure your O/S has reclaimed the memory. What exactly are you looking at
    in top?
    -- Rob
    > Continue
    restarting it will forces us to reboot the server as there will be more and more
    memory lost when restarting the WebLogic.
    Advice to fix the problem is much appreciated. Thanks.

  • AES with two keys javax.crypto.BadPaddingException

    Hello,
    I'am trying to encrypt / decrypt using AES, which performs correctly for one level encryption / decryption. However, when I am trying a two level encryption / decryption. I have this code:
    String message="This is just an example";
    byte[] raw="df5ea29924d39c3be8785734f13169c6".getBytes("ISO-8859-1");
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal((args.length == 0 ? "This is just an example" : args[0]).getBytes());
    System.out.println("encrypted string: " + asHex(encrypted));
    raw="ef5ea29924d39c3be8785734f13169c7".getBytes("ISO-8859-1");
    skeySpec = new SecretKeySpec(raw, "AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypteded = cipher.doFinal(encrypted);
    raw="df5ea29924d39c3be8785734f13169c6".getBytes("ISO-8859-1");
    skeySpec = new SecretKeySpec(raw, "AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] original1 = cipher.doFinal(encrypteded);
    raw="ef5ea29924d39c3be8785734f13169c7".getBytes("ISO-8859-1");
    skeySpec = new SecretKeySpec(raw, "AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] original2 = cipher.doFinal(original1);
    I get this exception:
    Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:811)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
    at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:317)
    at javax.crypto.Cipher.doFinal(Cipher.java:1813)
    Thank you!

    marya_a wrote:
    Thank you for you replay. Can you tell me if there is a symmetric and commutative cryptosystem. Since XOR commutes I would expect that any of the stream ciphers that generate a stream of pseudo random bits and XOR these with the cleartext to create the ciphertext will work. RC4 and block algorithms (AES, DES etc) using modes such as CFB spring to mind.
    Of course these should only be used with random session keys since using fixed keys (as you seem to have) is fundamentally insecure.
    I know that RSA is commutative, I'm pretty sure that this applies only if all stages use the same modulus.
    but I want it to be also symmetric.Edited by: sabre150 on Apr 13, 2010 9:41 AM

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

  • Better Encryption/Decryption Method - SMIME or PGP ?

    1. Which is the default encryption/decryption method provided in BizTalk Server ?
    2. What is PGP Encryption/Decryption ?
    3. What is SMIME Encryption/Decryption ?
    4. Which is better out of the two ?

    There is no default encryption/decryption method provided in BizTalk Server. BizTalk uses encryption/decryption using certificates (when you use certificates ). More about them here.
    BizTalk Server : Encrypting and Decrypting a Message.
    Pretty Good Privacy (PGP) is a data encryption and decryption computer program that provides cryptographic privacy and authentication for data communication.
    Soruce: Wiki. In Specific to BizTalk, messages are encrypted/decrypted at the entry point into BizTalk, right place is in pipeline using custom pipeline component. There is one available
    which you can learn more here.
    https://code.msdn.microsoft.com/windowsdesktop/BizTalk-Sample-PGP-ebcbc8b2. Also there is a thrid party adapter and pipeline component available to implement extensive suite of PGP features in BizTalk-
    https://www.eldos.com/bizcrypto/biztalk-pgp-adapter-pipeline.php
    S/MIME (Secure/Multipurpose Internet Mail Extensions) is a standard for
    public keyencryption and
    signing of MIME data. S/MIME is on an
    IETFstandards track and defined in a number of documents, most importantly RFCs 3369, 3370, 3850 and 3851. S/MIME was originally developed by
    RSA Data Security Inc.
    soruce Wiki. In BizTalk, when you use certificates with two-key security, it supports public key encryption of outbound messages and decryption of inbound messages based on Secure Multipurpose
    Internet Mail Extensions (S/MIME). BizTalk Server uses S/MIME version 3 for encryption of outbound messages, and S/MIME versions 2 and 3 for decryption of inbound messages. Reference:
    http://msdn.microsoft.com/en-us/library/aa559843.aspx
    When you discuss about which is more native, I would choose S/MIME which can be implemented with certificates and out-of-MIME pipeline components. 
    If this answers your question please mark it accordingly. If this post is helpful, please vote as helpful by clicking the upward arrow mark next to my reply.

Maybe you are looking for