Cipher DoFinal returns 0

Hi
I want to wrtite a program that would take
a)Plain password
b)Encode it
c)Write to a file
Second program
a)to read the file
b)get the encode password and decode it
c)get the plain password back.
First code is as follows:
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class EncryptFile
public static void main(String args[]) {
if (args.length < 1)
System.out.println("Usage: java EncryptFile <password>");
System.exit(-1);
try
File desFile = new File("encrypt.des");
if(desFile.exists())
desFile.delete();
FileInputStream fis=null;
FileOutputStream fos;
CipherInputStream cis;
// Creation of Secret key
byte key[] = "abcdEFGH".getBytes();
SecretKeySpec secretKey = new SecretKeySpec(key,"DES");
// Creation of Cipher objects
Cipher encrypt =
Cipher.getInstance("DES/ECB/PKCS5Padding");
encrypt.init(Cipher.ENCRYPT_MODE, secretKey);
// Open the Plaintext file
String password = args[0];
System.out.println(" Plain password " + password );
//Take the plain password + encode it + encrypt it
byte[] utf8 = password.getBytes("UTF8");
// Encrypt
byte[] enc = encrypt.doFinal();
// Encode bytes to base64 to get a string
password=new sun.misc.BASE64Encoder().encode(enc);
System.out.println(" Encode password " + password);
//write it to a file
byte[] encodearr = password.getBytes();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(desFile));
bos.write(encodearr);
bos.flush();
bos.close();
} catch (Exception e)
e.printStackTrace();
The decrypt code is as follows:
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class DecryptFile
public static void main(String args[]) {
try
File desFile = new File("encrypt.des");
File desFileBis = new File("decrypt.des");
FileInputStream fis;
FileOutputStream fos;
CipherInputStream cis;
// Creation of Secret key
byte key[] = "abcdEFGH".getBytes();
SecretKeySpec secretKey = new SecretKeySpec(key,"DES");
// Creation of Cipher objects
Cipher decrypt =
Cipher.getInstance("DES/ECB/PKCS5Padding");
decrypt.init(Cipher.DECRYPT_MODE, secretKey);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(desFile));
byte b[] = new byte[100];
int i = bis.read(b);
String temp=null;
while (i !=-1)
temp = new String(b,0,i);
System.out.println(" data is " + temp);
i = bis.read(b);
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(temp);
System.out.println( "dec " + dec.length);
// Decrypt
byte[] utf8 = decrypt.doFinal(dec);
System.out.println( "utf " + utf8.length);
} catch (Exception e)
e.printStackTrace();
First i run the EncryptFile.java the o/p is as follows:
C:\test\Alldump>java EncryptFile india123
Plain password india123
Encode password eYQJ953cHuI=
Now when i run the Decryptfile .java the o/p is as follows:
C:\test\Alldump>java DecryptFile
data is eYQJ953cHuI=
dec 8
utf 0
What can be the problem her
Best Regards
Manoj

I have not studied all your code but one obvious point -
//Take the plain password + encode it + encrypt it
byte[] utf8 = password.getBytes("UTF8");
// Encrypt
byte[] enc = encrypt.doFinal();You have never encrypted anything! Should this not be
//Take the plain password + encode it + encrypt it
byte[] utf8 = password.getBytes("UTF8");
// Encrypt
byte[] enc = encrypt.doFinal(utf8);

Similar Messages

  • Encrypting a digital signature

    Hi,
    I have a problem, I'm trying to encrypt a digital signature (SHA1withRSA) using symmetric encryption (Rijndael). But when I decrypt the signature bytes and verify the signature I get the message that the signature is not ok, even though I know it is.
    Does anybody know what's the problem?

    Hi floersh
    Thanks for answering.
    I'm sending you the code which I use, the functions and the main method.
    Please, if you have the time give it a look.
    Running the code I noticed that :
    1) The message digest is 20-bytes long
    2) The signature is 128-bytes long
    3) The encrypted signature is 32-bytes long
    4) The decrypted ciphertext (signature) is 16-bytes long
    And I also noticed that the decrypted signature bytes are the same with the 16 last bytes of the original signature.
    As you can see I'm using SHA1withRSA to create and verify the signature, where the public and private keys are 1024-bits long, and the Rijdael (192-bits key)cipher, with CBC and PKCS5Padding, for symmetric encryption and decryption. I have also tried to use Rijndael with ECB and PKCS5Padding and still doesn't work, and Rijndael with ECB and NoPadding where I get a BadPadding exception.
    I look forward for your reply.
    public static void generateAndLockKeys(String publicKeyFilename,String privateKeyFilename) throws Exception{
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024);
    KeyPair keyPair = keyPairGenerator.genKeyPair();
    byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
    FileOutputStream fos = new FileOutputStream(publicKeyFilename);
    fos.write(publicKeyBytes);
    fos.close();
    byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
    fos = new FileOutputStream(privateKeyFilename);
    fos.write(privateKeyBytes);
    fos.close();
    public static PrivateKey getPrivateKey(String privateKeyFilename, String password) throws Exception{
    FileInputStream fis = new FileInputStream(privateKeyFilename);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int theByte = 0;
    while ((theByte = fis.read())!= -1)
    baos.write(theByte);
    fis.close();
    byte[] keyBytes = baos.toByteArray();
    baos.close();
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
    return privateKey;
    public static PublicKey getPublicKey( String publicKeyFilename) throws Exception{
    FileInputStream fis = new FileInputStream(publicKeyFilename);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int theByte = 0;
    while ((theByte = fis.read())!= -1)
    baos.write(theByte);
    fis.close();
    byte[] keyBytes = baos.toByteArray();
    baos.close();
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey publicKey = keyFactory.generatePublic(keySpec);
    return publicKey;
    public static boolean checkSignature( PublicKey publicKey, byte[] plaintext, byte[] signedtext) throws Exception{
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initVerify(publicKey);
    signature.update(plaintext);
    boolean authorized = false;
    authorized = signature.verify(signedtext);
    return authorized;
    public static byte[] signWithSHAAndRSA(byte[] plaintext, PrivateKey privateKey) throws Exception{
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(privateKey);
    signature.update(plaintext);
    byte[] signedBytes = signature.sign();
    return signedBytes;
    public static byte[] encryptWithAES(byte[] plaintext, Key key, byte[] iv) throws Exception{
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec spec = new IvParameterSpec(iv);
    cipher.init(Cipher.ENCRYPT_MODE, key,spec);
    cipher.update(plaintext);
    byte[] ciphertext = cipher.doFinal();
    return ciphertext;
    public static byte[] decryptWithAESKey (Key AESKey, byte[] ciphertext, byte[] iv) throws Exception{
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec spec = new IvParameterSpec(iv);
    cipher.init(Cipher.DECRYPT_MODE,AESKey,spec);
    byte[] decryptedText = cipher.doFinal(ciphertext);
    return decryptedText;
    public static Key generateAESKey() throws Exception {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(192);
    Key key = keyGenerator.generateKey();
    return key;
    public static byte[] initAndReturnIV(){
    SecureRandom random = new SecureRandom();
    byte[] iv = new byte[16];
    random.nextBytes(iv);
    return iv;
    public static void main(String[] args) throws Exception{
    Security.addProvider(new BouncyCastleProvider());
    try {
    generateAndLockKeys(System.getProperty("user.dir") + System.getProperty("file.separator") +
    "PublicKey",System.getProperty("user.dir")
    + System.getProperty("file.separator") +"PrivateKey");
    } catch (Exception e) {}
    Key AESKey= generateAESKey();
    byte[] iv = initAndReturnIV();
    byte[] array2 = signWithSHAAndRSA("Hello".getBytes("UTF8"),getPrivateKey(System.getProperty("user.dir")
    + System.getProperty("file.separator") +"PrivateKey"));
    byte[] he = encryptWithAES(array2,AESKey,iv);
    byte[] hd = decryptWithAESKey(AESKey,he,iv);
    boolean ok = checkSignature(getPublicKey(System.getProperty("user.dir") + System.getProperty("file.separator") +
    "PublicKey"),"Hello".getBytes("UTF8"),hd);
    }

  • Why do i get an "IllegalBlockSizeException"?

    I have a piece of code which encrypts a string and stores it into a txt file. But when i come to decrypt the file i get the following error
    Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length
    (with padding) not multiple of 8 bytes
    at com.sun.crypto.provider.DESCipher.a(DashoA6275)
    at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA6275)
    at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA6275)
    at javax.crypto.Cipher.doFinal(DashoA6275)
    at javamailerprogram.DES.decrypt(DES.java:110)
    at javamailerprogram.DES.main(DES.java:120)
    This is my code
    package javamailerprogram;
    import java.security.*;
    import java.security.*;
    import javax.crypto.*;
    import java.io.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import javax.crypto.spec.SecretKeySpec;
    import java.util.*;
    import java.security.interfaces.*;
    public class DES {
    static SecretKey newKey;
    static String ENCRYPTION_TYPE = "DES";
    static int KEY_SIZE = 56;
    static SecretKeySpec skeySpec;
    static SecretKeySpec spec;
    static Cipher fileCipher;
    public DES(){
    Provider sunJce = new com.sun.crypto.provider.SunJCE();
    Security.addProvider(sunJce);
    try {
    Security.addProvider(new com.sun.crypto.provider.SunJCE());
    KeyGenerator keyGen = KeyGenerator.getInstance(ENCRYPTION_TYPE);
    keyGen.init(KEY_SIZE);
    ObjectInputStream in = new ObjectInputStream(new FileInputStream("c:/des.key"));
    SecretKey bfSKey = (SecretKey)in.readObject();
    byte[] raw = bfSKey.getEncoded();
    skeySpec = new SecretKeySpec(raw, ENCRYPTION_TYPE);
    } catch (Exception e) {
    e.printStackTrace();
    public void encrypt(String fileName, String fileNameTo) throws Exception {
    byte[] encryptedText;
    BufferedReader d
    = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
    StringBuffer line = new StringBuffer("");
    String lines = "";
    while((lines = d.readLine()) !=null){
         line.append(lines);
    fileCipher = Cipher.getInstance(ENCRYPTION_TYPE);
    fileCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    encryptedText = fileCipher.doFinal(line.toString().getBytes());
    FileOutputStream out = new FileOutputStream(fileNameTo);
    out.write(encryptedText);
    System.out.println("Done");
    public String encryptMessage(String textToEncrypt, String fileNameTo) throws Exception {
    byte[] encryptedText;
    fileCipher = Cipher.getInstance(ENCRYPTION_TYPE);
    fileCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    encryptedText = fileCipher.doFinal(textToEncrypt.getBytes());
    FileOutputStream out = new FileOutputStream(fileNameTo);
    out.write(encryptedText);
    System.out.println("Done");
    return fileNameTo;
    public String encryptMessage(String textToEncrypt) throws Exception {
    byte[] encryptedText;
    fileCipher = Cipher.getInstance(ENCRYPTION_TYPE);
    fileCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    encryptedText = fileCipher.doFinal(textToEncrypt.getBytes());
    System.out.println("Done");
    return new String(encryptedText);
    public String decrypt(String fileName) throws Exception {
    byte[] decryptedText;
    fileCipher = Cipher.getInstance(ENCRYPTION_TYPE);
    BufferedReader d
    = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
    StringBuffer line = new StringBuffer("");
    String lines = "";
    while((lines = d.readLine()) !=null){
         line.append(lines);
    System.out.println(line.length());
    byte[] theDecryptedText = line.toString().getBytes();
    fileCipher.init(Cipher.DECRYPT_MODE, skeySpec);
    decryptedText = fileCipher.doFinal(theDecryptedText);
    return new String(decryptedText);
    public static void main(String[] args) throws Exception {
    new DES();
    //new DES().encrypt("c:\\encr.txt", "C:\\Encr2.txt");
    new DES().encryptMessage("dsgfkdsfdsfudsagifugsadfuigsalidguflasgdfulagsdgfldsagfldsu", "C:\\Encr3.txt");
    System.out.println(new DES().decrypt("C:\\Encr3.txt"));
    } // end main
    } // end SourceViewer2

    That's because this byte[] encryptedText;
    encryptedText = fileCipher.doFinal(textToEncrypt.getBytes());
    return new String(encryptedText); is illegal. You cannot create a String out of any random binary array. Take a look at the API documentation of the String(byte[]) constructor. The only byte arrays you can construct a String out of are ones that conform to a supported encoding scheme, such as ASCII, UTF-8, etc. Cipher.doFinal() returns a byte array that does not conform to any encoding scheme. If you absolutely have to turn your encrypted byte array into a String, then you will need to use Base64 encoding. There is a Base64 encoding package to be found here: http://ostermiller.org/utils/Base64.html .
    HTH
    - Daniel

  • A problem about ALG_DES_CBC_ISO9797_M2 cipher

    I am doing a test for DES encryption/decryption using cref. Looks like only few cipher algorithms are support by Java card OS. I use ALG_DES_CBC_ISO9797_M2.
    The problem is as below:
    I use RMI.
    I think the operation block is 8 bytes.
    I want to encrypt an 8 bytes array 30 31 32 33 34 35 36 37.
    However, if I send an input array with 8 bytes, I got the error ILLGAL_USE.
    The strange thing is that if I append 8 bytes zeros and make the array like 30 31 32 33 34 35 36 37 00 00 00 00 00 00 00 00,
    I got a result 97 44 20 6c 39 80 c2 27 3d f6 77 5c 15 e7 84 18.
    And if I use the result array (16 bytes) for decryption, I got 30 31 32 33 34 35 36 37 00 00 00 00 00 00 00 00, which looks right,
    if I truncate last 8 bytes.
    Another experiment:
    Array1 (16 bytes): 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f (instead of append zeros, I append other numbers)
    Array2, encryption result for Array1: 9744206c3980c2273df6775c15e78418
    decrypt Array
    I got the result: 30 31 32 33 34 35 36 37 00 00 00 00 00 00 00 00 (looks like only the first 8 bytes of Array1 is used)
    So I have to keep a double-size encryption result? Anybody has more information?

    I know it's weird. But if I use 8 bytes as input, I got this for encryption:
    [java] java.lang.ArrayIndexOutOfBoundsException: Thrown on the card.
    my encryption code is like this:
    (if I double the size of outBuffer, I got an output array with size 16 bytes)
    public class DESCrypto {
         //DES Test Key
         static byte[] testDESKey = //Note this is the DES key definition
              (byte)0x38, (byte)0x12, (byte)0xA4, (byte)0x19, (byte)0xC6, (byte)0x3B, (byte)0xE7, (byte)0x71
         // constants
         byte     cryptKeyType = KeyBuilder.TYPE_DES;
         short     cryptKeyLen = KeyBuilder.LENGTH_DES;          // 64 bits
         short     cryptBlockLen = KeyBuilder.LENGTH_DES / 8;
         byte     cryptAlgo = Cipher.ALG_DES_CBC_ISO9797_M2;
        byte[] outBuffer = null;
         // input length is supposed to be half of the key length, otherwise giving arrayindexoutofboundary error
        public byte[] DESEncrypt(byte[] inBuffer) throws UserException, CryptoException {
              if(null == outBuffer) {
                   outBuffer = JCSystem.makeTransientByteArray((short)(this.cryptBlockLen), JCSystem.CLEAR_ON_DESELECT);
              if(null == outBuffer) {
                   UserException.throwIt(CardRmiCommon.NULL_POINTER);
              try {
                 Cipher cipher = Cipher.getInstance(this.cryptAlgo, false);
                 DESKey key = (DESKey) KeyBuilder.buildKey(this.cryptKeyType, this.cryptKeyLen, false);
                   key.setKey(testDESKey, (short)0);
                   cipher.init(key, Cipher.MODE_ENCRYPT);
                   cipher.doFinal(inBuffer,(short)0, (short)cryptBlockLen, outBuffer,(short)0);
              catch(CryptoException e){
                   CryptoException.throwIt(e.getReason());
              return outBuffer;
    }

  • Java.lang.IllegalStateException: Cipher not initialized during loadtest

    Hi All,
    Below is my code :
    static Cipher pbeCipher;
         byte[] encbytes = hexToByte( encrypted );
         pbeCipher.init( javax.crypto.Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec );
    byte[] decbytes ;
    synchronized (pbeCipher) {
         decbytes = pbeCipher.doFinal( encbytes );
              return new String( decbytes );
    I got the below exception when we are actually performing the load tests where in 4000 hits are made on the code in 1 min.
    java.lang.IllegalStateException: Cipher not initialized
    at javax.crypto.Cipher.c(Unknown Source)
    at javax.crypto.Cipher.doFinal(Unknown Source)
    My doubt here is : Is it occuring becuase of synchronizing issue? As shown in the code above i had synchronized the doFinal call. Still the exceptions are occuring. These are randomly coming say 1 out of 500 hits.
    Please suggest me a solution on how to fix this. We are using PBEWithMD5AndDES encryption mechanism in this case.
    Solution for this would help me a lot in terms of fixing it...
    Thanks in Advance......

    Cipher is not thread safe so that is almost certainly your problem. Your synchronisation does not include the init() method so it is possible that the instance is being initialised in one thread and used for decryption in a different thread.
    My approach is to create a pool of Cipher instances and then get an instance from the pool, use it and then put it back in the pool.
    P.S. DES is now considered deprecated in favour of AES. PBE is a poor man's approach since the chances are the password has far less entropy than the key size so will be much weaker than that implied by the algorithm being used. PBE is normally used for securing a user's data so in a Web based application it normally does not make sense to use PBE.

  • Cipher.getInstance("DES") not working in servlet!

    Hi - I'm working on Sun ONE Identity Server 6.1 using Sun ONE Web Server 6.1 using J2SDK 1.4.1_05
    I've modified one of the files to perform DES Encryption prior to getting some data.
    The code works fine when compiled separately - even works fine as a console program - but when I try running it as a servlet - I get a WHOLE bunch of errors when the program hits this line:
    cipher = Cipher.getInstance("DES");Here is the complete code:
    public String encryptPassword(String Password, String AppName)
         Key key;
         Cipher cipher;
         String Data = Password;
         String ApplicationName = AppName;
         String result = new String("hi");
         try
                    ObjectInputStream in = new ObjectInputStream(new FileInputStream("PrivateKey.ser"));
                  key = (Key)in.readObject();
                 in.close();
                 Security.addProvider(new com.sun.crypto.provider.SunJCE());
              cipher = Cipher.getInstance("DES"); // This LINE GIVES THE ERROR
              cipher.init(Cipher.ENCRYPT_MODE, key);
              byte[] stringBytes = Data.getBytes("UTF8");
              byte[] raw = cipher.doFinal(stringBytes);                    
              BASE64Encoder encoder = new BASE64Encoder();
              String result = encoder.encode(raw);
         catch (Exception e)
              // Print some error
    return result;
    }Here is the error log from the webserver:
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: Handler method "handleBtnSubmitRequest" threw an exception
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: java.lang.ExceptionInInitializerError
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at javax.crypto.Cipher.a(DashoA6275)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at javax.crypto.Cipher.getInstance(DashoA6275)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.am.console.user.UMChangeUserPasswordViewBean.encryptPassword(UMChangeUserPasswordViewBean.java:244)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.am.console.user.UMChangeUserPasswordViewBean.handleBtnSubmitRequest(UMChangeUserPasswordViewBean.java:172)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at java.lang.reflect.Method.invoke(Method.java:324)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.jato.view.command.DefaultRequestHandlingCommand.execute(DefaultRequestHandlingCommand.java:183)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.jato.view.RequestHandlingViewBase.handleRequest(RequestHandlingViewBase.java:299)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.jato.view.ViewBeanBase.dispatchInvocation(ViewBeanBase.java:811)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.jato.view.ViewBeanBase.invokeRequestHandlerInternal(ViewBeanBase.java:749)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.jato.view.ViewBeanBase.invokeRequestHandler(ViewBeanBase.java:596)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.jato.ApplicationServletBase.dispatchRequest(ApplicationServletBase.java:772)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.jato.ApplicationServletBase.processRequest(ApplicationServletBase.java:446)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.jato.ApplicationServletBase.doPost(ApplicationServletBase.java:324)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at javax.servlet.http.HttpServlet.service(HttpServlet.java:807)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at javax.servlet.http.HttpServlet.service(HttpServlet.java:908)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.apache.catalina.core.StandardWrapperValve.invokeServletService(StandardWrapperValve.java:771)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:322)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:509)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:212)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:509)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:209)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:509)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.ias.web.connector.nsapi.NSAPIProcessor.process(NSAPIProcessor.java:161)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.ias.web.WebContainer.service(WebContainer.java:586)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: Caused by: java.lang.SecurityException: Cannot set up certs for trusted CAs
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at javax.crypto.SunJCE_b.<clinit>(DashoA6275)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: ... 27 more
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: Caused by: java.security.PrivilegedActionException: java.security.InvalidKeyException: publicKey is not a PKCS #11 public key
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at java.security.AccessController.doPrivileged(Native Method)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: ... 28 more
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: Caused by: java.security.InvalidKeyException: publicKey is not a PKCS #11 public key 
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.mozilla.jss.pkcs11.PK11Signature.engineInitVerify(PK11Signature.java:172)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.mozilla.jss.crypto.Signature.initVerify(Signature.java:95) 
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.mozilla.jss.provider.Signature.engineInitVerify(Signature.java:94)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.mozilla.jss.provider.DSASignature.engineInitVerify(DSASignature.java:70)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at java.security.Signature.initVerify(Signature.java:297)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at sun.security.x509.X509CertImpl.verify(X509CertImpl.java:394)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at sun.security.x509.X509CertImpl.verify(X509CertImpl.java:363)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at javax.crypto.SunJCE_b.e(DashoA6275)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at javax.crypto.SunJCE_v.run(DashoA6275)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: ... 29 more
    [20/Oct/2003:16:58:01] failure ( 6417):  for host 10.42.7.235 trying to POST /amconsole/user/UMChangeUserPassword, service-j2ee reports: StandardWrapperValve[UMServlet]: WEB2792: Servlet.service() for servlet UMServlet threw exception   com.iplanet.jato.CompleteRequestException   at com.iplanet.am.console.base.ConsoleServletBase.onUncaughtException(ConsoleServletBase.java:331)   at com.iplanet.jato.ApplicationServletBase.fireUncaughtException(ApplicationServletBase.java:1023)   at com.iplanet.jato.ApplicationServletBase.processRequest(ApplicationServletBase.java:469)   at com.iplanet.jato.ApplicationServletBase.doPost(ApplicationServletBase.java:324)   at javax.servlet.http.HttpServlet.service(HttpServlet.java:807)   at javax.servlet.http.HttpServlet.service(HttpServlet.java:908)   at org.apache.catalina.core.StandardWrapperValve.invokeServletService(StandardWrapperValve.java:771)   at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:322)   at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:509)   at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:212)   at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:509)   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:209)   at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:509)   at com.iplanet.ias.web.connector.nsapi.NSAPIProcessor.process(NSAPIProcessor.java:161)   at com.iplanet.ias.web.WebContainer.service(WebContainer.java:586)    

    Hey.
    Not certain, but I think you need to make sure that your ciphers/certificates are installed on your server. Check the docs on the Sun server, and see what they say about installing certificates.
    Hope this helps.
    Vic

  • Maximum TDES length data to cipher

    Hi,
    I have been testing with the creation of TDES keys, and using to cipher data, and with the results I'm receiving i'm wondering If there is any limit on TripleDes with the length of the data to cipher because I'm only able to cipher data from 8,16 bytes, up to 32 it returns me an 6F00 error also doing a try catch:
    cipher= Cipher.getInstance(Cipher.ALG_DES_CBC_NOPAD,false);
    cipher.init(des,Cipher.MODE_DECRYPT,new byte[]{0,0,0,0,0,0,0,0},(short)0,(short)8);
         try{
                   cipheredataL=cipher.doFinal(data2cipher,(short)0, (short)32, randomD_cipher, (short)0);
         }catch(CryptoException crypto){
              if (crypto.getReason() == CryptoException.UNINITIALIZED_KEY)
                        ISOException.throwIt(ISO7816.SW_FILE_FULL);
                   else if (crypto.getReason() == CryptoException.INVALID_INIT)
                        ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
                   else if (crypto.getReason() == CryptoException.ILLEGAL_USE)
                        ISOException.throwIt(ISO7816.SW_FILE_INVALID);
                   else
                        ISOException.throwIt(ISO7816.SW_RECORD_NOT_FOUND);
    Thanks for your help another time :)

    I am not aware of a size limit for<tt> cipher.doFinal </tt>.
    Could it be that your<tt> data2cipher </tt> variable is shorter than 32 bytes, or/and its allocation fails?

  • Cipher.getInstance("DES") gives a Servlet Error!

    Hi - I'm working on Sun ONE Identity Server 6.1 using Sun ONE Web Server 6.1 using J2SDK 1.4.1_05
    I've modified one of the files to perform DES Encryption prior to getting some data.
    The code works fine when compiled separately - even works fine as a console program - but when I try running it as a servlet - I get a WHOLE bunch of errors when the program hits this line:
    cipher = Cipher.getInstance("DES");Here is the complete code:
    public String encryptPassword(String Password, String AppName)
         Key key;
         Cipher cipher;
         String Data = Password;
         String ApplicationName = AppName;
         String result = new String("hi");
         try
                    ObjectInputStream in = new ObjectInputStream(new FileInputStream("PrivateKey.ser"));
                  key = (Key)in.readObject();
                 in.close();
                 Security.addProvider(new com.sun.crypto.provider.SunJCE());
              cipher = Cipher.getInstance("DES"); // This LINE GIVES THE ERROR
              cipher.init(Cipher.ENCRYPT_MODE, key);
              byte[] stringBytes = Data.getBytes("UTF8");
              byte[] raw = cipher.doFinal(stringBytes);                    
              BASE64Encoder encoder = new BASE64Encoder();
              String result = encoder.encode(raw);
         catch (Exception e)
              // Print some error
    return result;
    }Here is the error log from the webserver:
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: Handler method "handleBtnSubmitRequest" threw an exception
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: java.lang.ExceptionInInitializerError
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at javax.crypto.Cipher.a(DashoA6275)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at javax.crypto.Cipher.getInstance(DashoA6275)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.am.console.user.UMChangeUserPasswordViewBean.encryptPassword(UMChangeUserPasswordViewBean.java:244)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.am.console.user.UMChangeUserPasswordViewBean.handleBtnSubmitRequest(UMChangeUserPasswordViewBean.java:172)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at java.lang.reflect.Method.invoke(Method.java:324)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.jato.view.command.DefaultRequestHandlingCommand.execute(DefaultRequestHandlingCommand.java:183)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.jato.view.RequestHandlingViewBase.handleRequest(RequestHandlingViewBase.java:299)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.jato.view.ViewBeanBase.dispatchInvocation(ViewBeanBase.java:811)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.jato.view.ViewBeanBase.invokeRequestHandlerInternal(ViewBeanBase.java:749)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.jato.view.ViewBeanBase.invokeRequestHandler(ViewBeanBase.java:596)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.jato.ApplicationServletBase.dispatchRequest(ApplicationServletBase.java:772)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.jato.ApplicationServletBase.processRequest(ApplicationServletBase.java:446)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.jato.ApplicationServletBase.doPost(ApplicationServletBase.java:324)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at javax.servlet.http.HttpServlet.service(HttpServlet.java:807)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at javax.servlet.http.HttpServlet.service(HttpServlet.java:908)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.apache.catalina.core.StandardWrapperValve.invokeServletService(StandardWrapperValve.java:771)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:322)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:509)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:212)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:509)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:209)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:509)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.ias.web.connector.nsapi.NSAPIProcessor.process(NSAPIProcessor.java:161)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at com.iplanet.ias.web.WebContainer.service(WebContainer.java:586)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: Caused by: java.lang.SecurityException: Cannot set up certs for trusted CAs
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at javax.crypto.SunJCE_b.<clinit>(DashoA6275)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: ... 27 more
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: Caused by: java.security.PrivilegedActionException: java.security.InvalidKeyException: publicKey is not a PKCS #11 public key
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at java.security.AccessController.doPrivileged(Native Method)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: ... 28 more
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: Caused by: java.security.InvalidKeyException: publicKey is not a PKCS #11 public key 
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.mozilla.jss.pkcs11.PK11Signature.engineInitVerify(PK11Signature.java:172)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.mozilla.jss.crypto.Signature.initVerify(Signature.java:95) 
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.mozilla.jss.provider.Signature.engineInitVerify(Signature.java:94)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at org.mozilla.jss.provider.DSASignature.engineInitVerify(DSASignature.java:70)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at java.security.Signature.initVerify(Signature.java:297)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at sun.security.x509.X509CertImpl.verify(X509CertImpl.java:394)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at sun.security.x509.X509CertImpl.verify(X509CertImpl.java:363)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at javax.crypto.SunJCE_b.e(DashoA6275)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: at javax.crypto.SunJCE_v.run(DashoA6275)
    [20/Oct/2003:16:58:01] warning ( 6417):  CORE3283: stderr: ... 29 more
    [20/Oct/2003:16:58:01] failure ( 6417):  for host 10.42.7.235 trying to POST /amconsole/user/UMChangeUserPassword, service-j2ee reports: StandardWrapperValve[UMServlet]: WEB2792: Servlet.service() for servlet UMServlet threw exception   com.iplanet.jato.CompleteRequestException   at com.iplanet.am.console.base.ConsoleServletBase.onUncaughtException(ConsoleServletBase.java:331)   at com.iplanet.jato.ApplicationServletBase.fireUncaughtException(ApplicationServletBase.java:1023)   at com.iplanet.jato.ApplicationServletBase.processRequest(ApplicationServletBase.java:469)   at com.iplanet.jato.ApplicationServletBase.doPost(ApplicationServletBase.java:324)   at javax.servlet.http.HttpServlet.service(HttpServlet.java:807)   at javax.servlet.http.HttpServlet.service(HttpServlet.java:908)   at org.apache.catalina.core.StandardWrapperValve.invokeServletService(StandardWrapperValve.java:771)   at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:322)   at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:509)   at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:212)   at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:509)   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:209)   at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:509)   at com.iplanet.ias.web.connector.nsapi.NSAPIProcessor.process(NSAPIProcessor.java:161)   at com.iplanet.ias.web.WebContainer.service(WebContainer.java:586)   

    Hi - I'm working on Sun ONE Identity Server 6.1 using
    Sun ONE Web Server 6.1 using J2SDK 1.4.1_05
    I've modified one of the files to perform DES
    Encryption prior to getting some data.
    The code works fine when compiled separately - even
    works fine as a console program - but when I try
    running it as a servlet - I get a WHOLE bunch of
    errors when the program hits this line:Actually, I think the errors are telling you the problem - you're just getting tangled up in the stacktraces. Let's get rid of everything except the "causes" lines:Handler method "handleBtnSubmitRequest" threw an exception
    java.lang.ExceptionInInitializerError
    Caused by: java.lang.SecurityException: Cannot set up certs for trusted CAs
    CORE3283: stderr: at javax.crypto.SunJCE_b.<clinit>(DashoA6275)
    Caused by: java.security.PrivilegedActionException: java.security.InvalidKeyException: publicKey is not a PKCS #11 public key
    at java.security.AccessController.doPrivileged(Native Method)
    Caused by: java.security.InvalidKeyException: publicKey is not a PKCS #11 public key 
    failure ( 6417):  for host 10.42.7.235 trying to POST amconsole/user/UMChangeUserPassword, service-j2eeLooks to me like the ctor for Cipher is unhappy because it's finding a key that isn't a PKCS#11 public key while it's trying to set up.
    What trust-store is your installation using? Have you run keytool -list on it? Possibly there's a bad key/cert in there.
    What do you expect "key" to be, in your code? How certain are you that it's really a DES key? If someone asked me to guess from the filename "PrivateKey.ser", I'd guess it was the private half an RSA keypair, which will NOT work for DES - but that may be just an unfortunate choice of filenames.
    The net is, you need to figure out where the installation is finding the thing that's causing the InvalidKeyException. Haven't used SunONE, so I'm not much help on exactly where to look - you might post on a SunONE list, to get help from admin-mavens...
    Good luck!
    Grant

  • Cipher - encrypt large String variable

    Hello,
    I have a jUnit test for a simple Cipher encryption/decryption.
    I want to write a test to encrypt large data.
    Do I have to change the encryption variable type from String to a Stream class?
    Anyone have suggestion?
    package no.ssb.cipher;
    import org.junit.*;
    import static org.junit.Assert.*;
    * Unit test for simple App.
    public class SimpleStringCipherTest {
    private SimpleStringCipher simpleStringCipher;
    * Create the test case
    * @param testName name of the test case
    @Before
    public void setUp()
    simpleStringCipher = new SimpleStringCipher("tvnw63ufg9gh5392");
    @Test
    public void testBasicEncyption() throws Exception {         
    String plainText = "2010 starts new decade.";
    String encrypted = simpleStringCipher.encrypt(plainText);
    System.out.println("Encrypted: " + encrypted);
    assertTrue(!plainText.equals(encrypted));
    String decrypted = simpleStringCipher.decrypt(encrypted);
    assertEquals(plainText, decrypted);
    @Test
    public void testEncryptionIsNotURLSafe() throws Exception{
    String plainText = "2010 starts new decade.";
    String expectedValue = "abe6vPUFQ4xSMezuFF2HBNC3dW98iifMeM027PKKnNw=";
    String encrypted = simpleStringCipher.encrypt(plainText);
    assertTrue(!plainText.equals(encrypted));
    assertTrue(expectedValue.equals(encrypted));
    String decrypted = simpleStringCipher.decrypt(encrypted);
    assertEquals(plainText, decrypted);
    @Test(expected=IllegalArgumentException.class)
    public void testInvalidSecretKey() throws Exception{
    SimpleStringCipher invalidCipher = new SimpleStringCipher("tull");
    @Test(expected=Exception.class)
    public void testDecryptInvalidEncryptedString() throws Exception {
    simpleStringCipher.decrypt("abe6vPUFQ4xSMezuFF2HBNC3dW98jjfMeM027PKKnNw");
    }

    Sorry, I am beginner and new in Cipher.
    Hope my following question make more sense.
    In production we have an error when decrypting
    large data.
    My existing unit test is shown and class I am testing
    How can I write a new test, simulating the production error we have?
    1.@Test
    2.public void testBasicEncyption() throws Exception {
    3.String plainText = "text to be encrypted."
    4.String encrypted = simpleStringCipher.encrypt(plainText);
    5.System.out.println("Encrypted: " + encrypted);
    6.assertTrue(!plainText.equals(encrypted));
    7.String decrypted = simpleStringCipher.decrypt(encrypted);
    8.assertEquals(plainText, decrypted);
    * Class to test *
    package no.ssb.cipher;
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import org.apache.commons.codec.binary.Base64;
    public class SimpleStringCipher {
    private static byte[] linebreak = {}; // Remove Base64 encoder default
    // linebreak
    private String secret; // secret key length must
    // be 16
    private SecretKey key;
    private Cipher cipher;
    private Base64 coder;
    public SimpleStringCipher(String secretKey) {
    if(secretKey.length()!=16){
    throw new IllegalArgumentException("secretKey must be 16 digits");
    this.secret = secretKey;
    try {
    key = new SecretKeySpec(secretKey.getBytes(), "AES");
    cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
    coder = new Base64(32, linebreak, false);
    } catch (Throwable t) {
    t.printStackTrace();
    public synchronized String encrypt(String plainText)
    throws Exception {
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] cipherText = cipher.doFinal(plainText.getBytes());
    return new String(coder.encode(cipherText));
    public synchronized String decrypt(String codedText)
    throws Exception {
    byte[] encypted = coder.decode(codedText.getBytes());
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decrypted = cipher.doFinal(encypted);
    return new String(decrypted);
    Edited by: 999969 on Apr 14, 2013 10:38 PM

  • Help in RSA cipher

    I need to encrypt a byte[] of size 426 using RSA algorithm but when i call cipher.doFinal(byte[]);
    I get
    javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes
         at com.sun.crypto.provider.RSACipher.a(DashoA6275)
         at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA6275)
         at javax.crypto.Cipher.doFinal(DashoA12275)
         at com.security.cert.KeyStre.encryptDecrypt(KeyStre.java:132)
         at com.security.cert.KeyStre.main(KeyStre.java:79)I know there is an update() in cipher but i am not sure how to use it.
    Could anyone help me out...
    thnx alot

    ok i think i got it...
    It should have been done earlier but i had a party to attend to.
    What i did was take 112 bytes of the 226 byte DH public key and encrypt it with the RSA public Key. I did the same for the next 112 bytes and so on till i encrypted the entire 226 bytes and appended each encrypted block into an byte array.
    For decryption i did the same but I used 128 bytes instead of 112 bytes block and decrypted with the RSA private key.
    but i have a problem the resulting decrypted key is appended with zeros because of the encryption algoritm. The only way to get the completely correct key is to use the length of the original DH public key. Is there any way to solve this small problem...
    Here is the code hope it helps someone....
    plz test it too...
    thnks
    public byte[] encryptDecrypt(String type,byte[] data,Key secretKey) throws EncryptDecryptException
              byte cryptedCipherText[] = null ;
              BufferedReader read;
              try {
              Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
              System.out.println("Provider is-->" + cipher.getProvider().getInfo());
              int j = 0;
              int k=0;
              boolean flag = false;
              byte[] bufferedEncryption = null;
                   if(type.equals("ENCRYPT"))
                        cipher.init(Cipher.ENCRYPT_MODE,secretKey);
                        j = 112;
                        k=112;
                        bufferedEncryption = new byte[k];
                   else
                        cipher.init(Cipher.DECRYPT_MODE,secretKey);
                        j = 128;
                        k=128;
                        bufferedEncryption = new byte[k];
                   int cipherlength = cipher.getOutputSize(data.length);
                   System.out.println("data size-->" + data.length);
                   System.out.println("cipher size-->" + cipherlength);
                   cryptedCipherText= new byte[cipherlength];
                   ByteArrayOutputStream cryptedTextBuffer = new ByteArrayOutputStream();
                   int count =0;
                   int i = 0;
                   while( i< data.length)
                        System.arraycopy(data,i,bufferedEncryption,0,j);
                        System.out.println("sizeof bufferedencryption-->"+bufferedEncryption.length);
                        cryptedCipherText = cipher.doFinal(bufferedEncryption);
                        count+=cryptedCipherText.length;
                        System.out.println("Length-->"+count);
                        cryptedTextBuffer.write(cryptedCipherText);
                        System.out.println("i-->"+i);
                             i+=k;
                             bufferedEncryption = new byte[k];
                             if(flag == true)
                                  break;
                             if(i+k > data.length)
                                  j = data.length - i;
                                  flag = true;
                   cryptedCipherText = cryptedTextBuffer.toByteArray();
                   //cryptedCipherText = cipher.doFinal(data);
              } catch (InvalidKeyException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   //throw new EncryptDecryptException("Invalid Key in encrypt/decrypt");
              } catch (NoSuchAlgorithmException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   //throw new EncryptDecryptException("No such algorithm in encrypt/decrypt");
              } catch (NoSuchPaddingException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   //throw new EncryptDecryptException("No such padding in encrypt/decrypt");
              } catch (IllegalBlockSizeException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (BadPaddingException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              return cryptedCipherText;
    just give the inputs as "ENCRYPT"/"DECRYPT", your data and the public key for encryption and privatekey for decryption.

  • Damn this cipher!!!

    I first tried public/private keys generated by DSA for assymetric encryption buy using Cipher class. But that didn't work out and ghstark pointed out that sun doesn't support encryption with DSA and adviced me to try out RSA.
    So I tried RSA and everything is woking out fine. But now i want to encrypt a key that is created by DH alogrithm. They ofcourse only create keys of size in the multiples of 64 from 512 onwards (duh!!). But this godforsaken RSA algorithm only accepts a maximum data size of 117 for encryption.
    So wht do i do now???????
    Is there any way to break up the key into blocks encrypt each block seperately and then decrypt and reattach all the blocks using the api( just a thought). or is there some other way.
    confused and tired

    ok i think i got it...
    It should have been done earlier but i had a party to attend to.
    What i did was take 112 bytes of the 226 byte DH public key and encrypt it with the RSA public Key. I did the same for the next 112 bytes and so on till i encrypted the entire 226 bytes and appended each encrypted block into an byte array.
    For decryption i did the same but I used 128 bytes instead of 112 bytes block and decrypted with the RSA private key.
    but i have a problem the resulting decrypted key is appended with zeros because of the encryption algoritm. The only way to get the completely correct key is to use the length of the original DH public key. Is there any way to solve this small problem...
    Here is the code hope it helps someone....
    plz test it too...
    thnks
    public byte[] encryptDecrypt(String type,byte[] data,Key secretKey) throws EncryptDecryptException
              byte cryptedCipherText[] = null ;
              BufferedReader read;
              try {
                   Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
               System.out.println("Provider is-->" + cipher.getProvider().getInfo());
               int j = 0;
               int k=0;
               boolean flag = false;
               byte[] bufferedEncryption = null;
                   if(type.equals("ENCRYPT"))
                        cipher.init(Cipher.ENCRYPT_MODE,secretKey);
                        j = 112;
                        k=112;
                        bufferedEncryption = new byte[k];
                   else
                        cipher.init(Cipher.DECRYPT_MODE,secretKey);
                        j = 128;
                        k=128;
                        bufferedEncryption = new byte[k];
                   int cipherlength = cipher.getOutputSize(data.length);
                   System.out.println("data size-->" + data.length);
                   System.out.println("cipher size-->" + cipherlength);
                   cryptedCipherText= new byte[cipherlength];
                   ByteArrayOutputStream cryptedTextBuffer = new ByteArrayOutputStream();
                   int count =0;
                   int i = 0;
                   while( i< data.length)
                        System.arraycopy(data,i,bufferedEncryption,0,j);
                        System.out.println("sizeof bufferedencryption-->"+bufferedEncryption.length);
                        cryptedCipherText = cipher.doFinal(bufferedEncryption);
                        count+=cryptedCipherText.length;
                        System.out.println("Length-->"+count);
                        cryptedTextBuffer.write(cryptedCipherText);
                        System.out.println("i-->"+i);
                             i+=k;
                             bufferedEncryption = new byte[k];
                             if(flag == true)
                                  break;
                             if(i+k > data.length)
                                  j = data.length - i;
                                  flag = true;
                   cryptedCipherText = cryptedTextBuffer.toByteArray();
                   //cryptedCipherText = cipher.doFinal(data);
              } catch (InvalidKeyException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   //throw new EncryptDecryptException("Invalid Key in encrypt/decrypt");
              } catch (NoSuchAlgorithmException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   //throw new EncryptDecryptException("No such algorithm in encrypt/decrypt");
              } catch (NoSuchPaddingException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   //throw new EncryptDecryptException("No such padding in encrypt/decrypt");
              } catch (IllegalBlockSizeException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (BadPaddingException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              return cryptedCipherText;
    }just give the inputs as "ENCRYPT"/"DECRYPT", your data and the public key for encryption and privatekey for decryption.

  • "java.lang.NullPointerException" when use doFinal(byte[])

    My code here:
    KeyFactory kf = null;
    Cipher cipher = null;
    PrivateKey pk = null;
    byte[] symKey = null;
    try {
    Security.addProvider(new BouncyCastleProvider());
    catch (Exception e) {
    System.err.println("Error loading security provider (" +
    e.getMessage() + ")");
    try {
    kf = KeyFactory.getInstance("RSA");
    catch (NoSuchAlgorithmException ex1) {
    try {
    pk = kf.generatePrivate(priServer);
    catch (InvalidKeySpecException ex3) {
    try {
    cipher = Cipher.getInstance("RSA");
    catch (NoSuchAlgorithmException ex2) {
    catch (NoSuchPaddingException ex2) {
    try {
    cipher.init(Cipher.DECRYPT_MODE, pk);
    catch (InvalidKeyException ex4) {
    try {
    symKey = cipher.doFinal(CEK); //get encode of symmetric key
    when CEK is byte[].
    I got exception :
    java.lang.NullPointerException
         at java.math.BigInteger.remainder(BigInteger.java:1239)
         at org.bouncycastle.crypto.engines.RSAEngine.processBlock(RSAEngine.java:133)
         at org.bouncycastle.jce.provider.JCERSACipher.engineDoFinal(JCERSACipher.java:288)
    where my code wrong? Please help me!
    Note : I use bouncycastle provider.
    Thanks

    bla bla bla
    kf = KeyFactory.getInstance("RSA");
    pk = kf.generatePrivate(priServer);
    cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, pk);IMHO RSA is 2-keys algorithm => you cannot use it in cipher class
    If u need encrypt use PBE for example
    PBEKeySpec pbeKeySpec;
    PBEParameterSpec pbeParamSpec;
    SecretKeyFactory keyFac;
    // Salt
    byte[] salt = ...;
    // Iteration count
    int count = 20;
    // Create PBE parameter set
    pbeParamSpec = new PBEParameterSpec(salt, count);
    // Prompt user for encryption password.
    pbeKeySpec = new PBEKeySpec(pass); //String with
    keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
    // Create PBE Cipher
    Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
    // Initialize PBE Cipher with key and parameters
    pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
    // Our cleartext
    byte[] cleartext = "This is another example".getBytes();
    // Encrypt the cleartext
    byte[] ciphertext = pbeCipher.doFinal(cleartext);

  • My SDK doesn't implement Cipher, course of action

    Hi, all. First of all let me tell you that I've checked the forum for this topic. Found 44 threads when searching for "Cipher". I've pretty clear that due to restrictions from the U.S. Goverment, the Sun JC kit doesn't implement the Cipher class. That's understood.
    Now, my SmartCard Vendor (DataCard Aptura) doesn't implement it neither the Cipher class on it's sdk. I've asked for support and they have told me that they won't add that Class. So I can't count on them.
    So, the purpose of this post is to find out the course of action. I've just two options, either I implement the class by myself or I get it (buy it, if it's possible) somewhere else. I don't want you to do my work, I just need some light because I'm new to this cryptography over smartCard thing.
    So I've this questions which require short answer (hope so):
    1.) According to your experience, should we implement it by ourselves? Or should we look for some vendor that has already implemented it?
    2.) I that were the case (that we should implement it by our own) could you estimate the amount of time (or resources) needed, considering just one programmer.
    3.) Are there some special considerations that I should take in order to save memory. Please notice that the current version of Aptura prohibits the use of transient arrays on the card, due to a bug inside the core of the VM. It doesn?t reclaim the space after it?s been used, for instance after a reset, it won?t reclaim the all the transient space used.
    4.) If it would take a considerable amount of time to implement the Cipher class by our own, do you know some vendor that has already implemented and can save us that time?
    Any other light or aspect that you might think it's important and I've missed here, would be appreciated.
    Many Thanks in advance.
    CL

    Well no. All I want is to have cryptography on my card (that I didn't choose for the project I just received like "this is the card"). And this vendor doesn't have an implementation of the Cipher class.
    As a parenthesis () there is not Int as you properly mentioned, but I implemented by hand, unsing Zhiqun Chen proposal (on her book JavaCard Technology for SmartCards). I know that approach is not quite efficient, but it works (considering that for financial purposes a short is not enough).
    Well, back to our business. Also I'm concious that the approach of implementing the cryptography by myself would not win the efficiency award for Smart Card, but I need to do something and trying to change the card at this point (I didn't choose it, as I told you) would not be the first solution, due to the fact that the production cards are already ordered. So that's the actual situation.
    So, I'm pretty sure the problem is on the side of my vendor. Is not that I'm washing my hands on him, it's just the fact. Here you'll find my little test I'm trying to run. It crashes after the following line on the process (APDU apdu) method:
    cipher.doFinal(data, START, (short) data.length, cipherText, START);
    And here's my code:
    //CVS Tests
    package com.datacode.bi.Purse;
    import javacard.framework.*;
    import javacardx.crypto.*;
    import javacard.security.*;
    public class Purse extends Applet
    public static final byte START = (byte) 0x00;
    private DESKey desKey;
    private Cipher cipher;
    private byte [] cipherText;
    protected Purse(byte[] bArray, short bOffset, byte bLength)
    cipherText = new byte [100];
    try {
    desKey = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES, false);
    desKey.setKey( keyData, START);
    cipher = Cipher.getInstance(Cipher.ALG_DES_ECB_ISO9797_M1, false);
    cipher.init(desKey, Cipher.MODE_ENCRYPT);
    catch (CryptoException e) {
    register();
    * Installs Java Purse applet.
    * @param bArray to pass to register() method.
    * @param bOffset to pass to register() method.
    * @param bLength to pass to register() method.
         public static void install( byte[] bArray, short bOffset, byte bLength )
    byte instanceLength = (byte) bArray[bOffset];
    short instanceOffset = (short)(bOffset + 1);
              new Purse(bArray, instanceOffset, instanceLength);
    * Performs the session finalization.
         public void deselect()
    * Dispatches APDU commands.
    * @param apdu APDU object
         public void process(APDU apdu)
    byte[] buffer = apdu.getBuffer();
    try {
    //ISOException.throwIt(
    cipher.doFinal(data, START, (short) data.length, cipherText, START);
    //ISOException.throwIt(DEBUG_CODE);
    apdu.setOutgoing();
    apdu.setOutgoingLength((short) cipherText.length);
    apdu.sendBytesLong(cipherText, START, (short) cipherText.length);
    catch (APDUException e) {
    catch (CryptoException e) {
    private final static byte [] keyData = {    (byte) 'C',
    (byte) 'a',
    (byte) 'r',
    (byte) 'p',
    (byte) 'e',
    (byte) ' ',
    (byte) 'D',
    (byte) 'i'
    private static final byte [] data = { (byte) 68,
    (byte) 111,
    (byte) 32,
    (byte) 121,
    (byte) 111,
    (byte) 117,
    (byte) 32,
    (byte) 98,
    (byte) 121,
    (byte) 116,
    (byte) 101,
    (byte) 44,
    (byte) 32,
    (byte) 119,
    (byte) 104,
    (byte) 101,
    (byte) 110,
    (byte) 32,
    (byte) 73,
    (byte) 32,
    (byte) 107,
    (byte) 110,
    (byte) 111,
    (byte) 99,
    (byte) 63,
    (byte) 65
    private static final short DEBUG_CODE = (short) 0x9999;
    >
    Aptura prohibits the use of transient arrays on the
    card,based on that I would try other vendors, IBM
    JCOP, Datakey, G&D Sm@rtCafe, Gem+ GemXpress RAD, and
    SLB all implement the javacard.security,
    javacard.crypto classes and the transient arrays are
    COD/COR.

  • Using Cipher on table data

    God Morning. I did solve the hash password part. And I have now learned that a password is never decrypt. My new goal is to encrypt the data that is sent from JTable before it is saved. Then read it, decrypt and put it back to table. I have come up with the code below. And I just want to ask if it is safe to use for that purpose.
    public void useCipher(byte[] string) throws Exception{
           KeyGenerator key = KeyGenerator.getInstance("DES");
           SecretKey secretKey = key.generateKey();
           Cipher cipher = Cipher.getInstance("DES");
           cipher.init(Cipher.ENCRYPT_MODE, secretKey);
           byte[] encrypted = cipher.doFinal(string);
           cipher.init(Cipher.DECRYPT_MODE, secretKey);
           byte[] decrypted = cipher.doFinal(encrypted);
           String cleartext = new String(decrypted);
        }

    It all depends on your objective - are you doing this as an exercise for a school project? If so, you really need to read the book referenced in this thread.
    Are you doing this for compliance to some regulation (such as PCI-DSS, 201 CMR 17.00, etc.)? If so, the problem isn't as simple as you think it is (Heartland Payment Systems just settled with Visa for US $60M for having breached credit card numbers despite being certified as compliant with the PCI's Data Security Standard; you can bet they are now spending millions of dollars on trying to encrypt their data and protect their keys better than they did so far).
    Are you doing this to comply with some internal security policy that isn't mandated by external regulation? If so, you need to understand the threats you are protecting the system from, and then design in the solution components to mitigate the threats. If these threats have not been identified, you should hire a competent security consultant to identify them for you. Once identified, the choice of solutions - and thus the focus of your attention - becomes easier.
    You are on a cryptography forum, MagnusT76, so a statement like "Don't need high level of security on it" is contradictory to why cryptography is used by people. The use of cryptography (encryption, digital signatures, etc.) is the penultimate line of defense in data-protection. The only other defensive position you can take to protect data (beyond the use of cryptography) is to eliminate it from the application or system completely.

  • Cipher Streams with AES in CFB8 mode

    I have had some problems using AES/CFB8/PKCS5Padding with Cipher Input/Output Streams. I recall from the doc that the flush() call does not actually flush the cipher buffer. From what I can tell this makes it undesirable for connections that require an ordered response (client server).
    I am making a vain attempt to force a flush of the buffer by calling cipher.doFinal() and then reinitializing it using the past 16 ciphertexts as the iv.
    Am I insane?
    Any help is appreciated.
    -sushi

    escanfail wrote:
    My problem is that Cipher Streams do not produce all of the data on each call.CFB8 turns a block cipher into a stream cipher which is usually a basic requirement for network communication because there is no buffering of data pending a complete block. If you are not getting all the data sent as expected then YOU are doing something wrong. There are a load of things you could be doing wrong but to give you a start - you need to make sure you use flush() after each write and don't rely on available() on each read.
    Without seeing your code it is going to be difficult for anyone to give you any further help.

Maybe you are looking for

  • Problem launching a jsp page with eclipse and tomcat

    Hi, I have just started using eclipse and tomcat for creating dynamic web pages. I tried to launch a jsp page after starting the tomcat server with the URL: http://locahost:8080/HelloWorld/, an error page was displayed as below: HTTP Status 404 -/ ty

  • New mac mini won't boot.

    Sorry I couldn't wait for a refresh.  So I went to FRYS and got the last 529 mini. Under 600 and I got a mini 2.3ghz i5 and and 16gb flash stick for under 600 which is normally 600 plus tax. Good deal. I'm so happy. Sorry I got impatient and couldn't

  • CRIO: Unflatten from string into lvclass not working in deployment

    Hello, I am working on a problem for some hours now and I need some help. I am using a cRIO-9022. I need to do some tasks, and I created a couple of classes which contain the parameters and the methods. They contain using dynamic dispatch VIs. I have

  • How do I find out what is causing a random black screen on iMac?

    Hello I get random black screen on a iMac and I haven't made any hardware changes. How can I find out what is causing this? Thanks Jer iMac 2.66 core 2 duo with Snow Leopard 10.6.8

  • Controlling IDOC processing at the adapter level

    Hi, Scenario :File --> XI --> IDOC My source file has multiple line items and for every line item an IDOC is generated. My requiremnt is that, these multiple IDOCs generated should reach R/3 with one trfc connection open , i.e if i have 1000 IDOCs ge