KickJava   Java API By Example, From Geeks To Geeks.

Java > Java SE, EE, ME > javax > crypto > Cipher

javax.crypto
Class Cipher

java.lang.Object
  extended by javax.crypto.Cipher
Direct Known Subclasses:
NullCipher
See Also:
Top Examples, Source Code, KeyGenerator, SecretKey

protected Cipher(CipherSpi cipherSpi,
                 Provider provider,
                 String transformation)
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[528]AES encryption
By Anonymous on 2004/08/09 17:18:10  Rate
import java.security.*; 
 importjavax.crypto.*; 
  
  
 // Get Provider 
 Provider sunJce = new com.sun.crypto.provider.SunJCE (  ) ; 
  
  
 // Obtain Cipher AES available 1.4.2 
 Cipher c = Cipher.getInstance ( "AES" ) ; 
  
  
 // Get the key Generator 
 KeyGenerator kgen = KeyGenerator.getInstance ( "AES" ) ; 
  
  
 // Generate the key specs 
 SecretKey skey = kgen.generateKey (  ) ; 
 byte [  ]  raw = skey.getEncoded (  ) ; 
 SecretKeySpec kspec = new 
 SecretKeySpec ( raw, "AES" ) ; 
  
  
 // Initialize cipher with keys, etc. 
 cipher.init ( Cipher.ENCRYPT_MODE, kspec ) ; 
  
  
 // Update buffers 
 while  ( msg [ i ]  != null )  
   enc = cipher.update ( msg [ i ] .getBytes (  )  ) ; 
  
  
  // Finish up 
 enc = cipher.doFinal (  ) ;


[2020]cipher
By agazi_a { at } yahoo { dot } com on 2012/02/20 06:18:29  Rate
 
  
  
  
 import java.security.*; 
 import javax.crypto.*; 
 import javax.crypto.spec.*; 
 import javax.crypto.KeyGenerator; 
 import javax.crypto.SecretKey; 
 import javax.crypto.spec.IvParameterSpec; 
 import javax.crypto.Cipher; 
 import java.io.*; 
 import javax.*; 
 public class encryptTest  {  
   public static void main ( String [  ]  args )  throws Exception 
  {  
  
  
 FileInputStream in = null; 
 FileOutputStream out = null; 
  
  
 byte [  ]  key = { 0,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7 } ;//... secret sequence of bytes 
  
  
 System.out.println ( "Please type the word to be encrypted" ) ; 
   String sentence;  
          BufferedReader inFromUser =  
          new BufferedReader ( new InputStreamReader ( System.in )  ) ;  
       sentence = inFromUser.readLine (  ) ;  
 byte [  ]  dataToSend =sentence.getBytes (  ) ; 
 //out = new FileOutputStream ( "plain.txt" ) ; 
 //out.write ( dataToSend ) ; 
 //out.close (  ) ; 
 String st = new String ( dataToSend ) ;  
 System.out.println ( "Plain text data to be encrypted: " +st ) ; 
 Cipher ci = Cipher.getInstance ( "AES" ) ; 
 SecretKeySpec ky = 
   new SecretKeySpec ( key, "AES" ) ; 
 ci.init ( Cipher.ENCRYPT_MODE, ky ) ; 
 byte [  ]  encryptedData = ci.doFinal ( dataToSend ) ; 
 //String str =new String ( encryptedData ) ; 
 //System.out.println ( "Cipher text data to be send to receiver: " //+str ) ; 
 FileOutputStream sot = new FileOutputStream ( "encryptedfile.txt" ) ; 
 sot.write ( encryptedData ) ; 
  
  
  
 FileOutputStream ou = new FileOutputStream ( "plains.txt" ) ; 
 ou.write ( dataToSend ) ; 
 MessageDigest md = MessageDigest.getInstance ( "MD5" ) ; 
         FileInputStream fis = new FileInputStream ( "plains.txt" ) ; 
   
         byte [  ]  dataBytes = new byte [ 1024 ] ; 
   
         int nread = 0;  
         while  (  ( nread = fis.read ( dataBytes )  )  != -1 )   {  
           md.update ( dataBytes, 0, nread ) ; 
     } ; 
         byte [  ]  mdbytes = md.digest (  ) ; 
 //convert the byte to hex format method 1 
         StringBuffer sb = new StringBuffer (  ) ; 
         for  ( int i = 0; i  <  mdbytes.length; i++ )   {  
           sb.append ( Integer.toString (  ( mdbytes [ i ]  & 0xff )  + 0x100, 16 ) .substring ( 1 )  ) ; 
          }  
   
         System.out.println ( "Digest ( in hex format ) :: " + sb.toString (  )  ) ; 
 fis.close (  ) ; 
 Cipher c = Cipher.getInstance ( "AES" ) ; 
 SecretKeySpec k = 
   new SecretKeySpec ( key, "AES" ) ; 
 c.init ( Cipher.ENCRYPT_MODE, k ) ; 
 byte [  ]  md5encryptedData = c.doFinal ( mdbytes ) ; 
 //String str =new String ( encryptedData ) ; 
 //System.out.println ( "Cipher text data to be send to receiver: " //+str ) ; 
 FileOutputStream ot = new FileOutputStream ( "md5encryptedfile.txt" ) ; 
 ot.write ( md5encryptedData ) ; 
  
  
  }  
  }  
  
  
 decryption 
  
  
  
 import java.security.*; 
 import javax.crypto.*; 
 import javax.crypto.spec.*; 
 import javax.crypto.KeyGenerator; 
 import javax.crypto.SecretKey; 
 import javax.crypto.spec.IvParameterSpec; 
 import javax.crypto.Cipher; 
 import java.io.*; 
 import javax.*; 
  
  
 import java.io.File; 
  
  
 public class decryptTest  {  
   public static void main ( String [  ]  args )  throws Exception {  
 byte [  ]  key =  { 0,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7 } ; 
  
  
  
  
 byte [  ]  buffer = new byte [  ( int ) new File ( "encryptedfile.txt" ) .length (  )  ] ; 
 FileInputStream is = new FileInputStream  ( "encryptedfile.txt" ) ;   
       is.read  ( buffer ) ;   
  
  
 Cipher c = Cipher.getInstance ( "AES" ) ; 
 SecretKeySpec k = 
   new SecretKeySpec ( key, "AES" ) ; 
 c.init ( Cipher.DECRYPT_MODE, k ) ; 
  
  
  
 byte [  ]  data = c.doFinal ( buffer ) ; 
 FileOutputStream out = new FileOutputStream ( "plain.txt" ) ; 
 out.write ( data ) ; 
 out.close (  ) ; 
 byte [  ]  buf = new byte [  ( int ) new File ( "md5encryptedfile.txt" ) .length (  )  ] ; 
 FileInputStream in = new FileInputStream  ( "md5encryptedfile.txt" ) ;   
     in.read  ( buf ) ;  
 Cipher ci = Cipher.getInstance ( "AES" ) ; 
 SecretKeySpec ky = 
   new SecretKeySpec ( key, "AES" ) ; 
 ci.init ( Cipher.DECRYPT_MODE, ky ) ; 
  
  
  
 byte [  ]  mddata = ci.doFinal ( buf ) ;  
       
 //convert the byte to hex format method 1 
         StringBuffer sb = new StringBuffer (  ) ; 
         for  ( int i = 0; i  <  mddata.length; i++ )   {  
           sb.append ( Integer.toString (  ( mddata [ i ]  & 0xff )  + 0x100, 16 ) .substring ( 1 )  ) ; 
          }  
   
 System.out.println ( "Digest ( in hex format ) :: " + sb.toString (  )  ) ; 
 String sb1=sb.toString (  ) ; 
 MessageDigest md = MessageDigest.getInstance ( "MD5" ) ; 
         FileInputStream fis = new FileInputStream ( "plain.txt" ) ; 
   
         byte [  ]  dataBytes = new byte [ 1024 ] ; 
   
         int nread = 0;  
         while  (  ( nread = fis.read ( dataBytes )  )  != -1 )   {  
           md.update ( dataBytes, 0, nread ) ; 
     } ; 
         byte [  ]  mdbytes = md.digest (  ) ; 
 //convert the byte to hex format method 1 
         StringBuffer st = new StringBuffer (  ) ; 
         for  ( int i = 0; i  <  mdbytes.length; i++ )   {  
           st.append ( Integer.toString (  ( mdbytes [ i ]  & 0xff )  + 0x100, 16 ) .substring ( 1 )  ) ; 
          }  
   
         System.out.println ( "Digest ( in hex format ) :: " + st.toString (  )  ) ; 
 String st1=st.toString (  ) ; 
 boolean bool=st1.equals ( sb1 ) ; 
 System.out.println ( "Compared the decrypted hashed value with hashed value and the result is:"+bool+"\nTherefore the integrity of the message is confirmed" ) ; 
  
  
  }  
  }  
 


public static final int DECRYPT_MODE
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final byte[] doFinal()
                     throws IllegalBlockSizeException,
                            BadPaddingException
See Also:
IllegalStateException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[743]Decrypt string
By rajganeshnaidu { at } yahoo { dot } com on 2004/04/23 04:22:29  Rate
public static String decryptString ( String inputString )  
      {  
         try 
          {  
             Security.addProvider ( new ABAProvider (  )  ) ; 
             ObjectInputStream in = new ObjectInputStream ( new FileInputStream ( SystemManager.get ( "db.key" )  )  ) ; 
             Key key =  ( Key ) in.readObject (  ) ; 
  
  
             in.close (  ) ; 
             Cipher cipher = Cipher.getInstance ( "DESede/ECB/PKCS5Padding" ) ; 
             cipher.init ( 2, key ) ; 
             BASE64Decoder decoder = new BASE64Decoder (  ) ; 
             byte inputBytes [  ]  = decoder.decodeBuffer ( inputString ) ; 
  
  
             String result=null; 
       try  {  
               byte outputBytes [  ]  = cipher.doFinal ( inputBytes ) ; 
         result = new String ( outputBytes, "UTF8" ) ; 
         System.out.println ( "\n\n result is: " + result + "\n\n" ) ; 
        } catch  ( Exception e )   {  
         System.out.println ( "\nNaidu, problem in calling cipher.doFinal method\n\n" ) ; 
         System.out.println ( e.toString (  )  ) ; 
        } ; 
  
  
       //String result = new String ( outputBytes, "UTF8" ) ; 
             return result; 
          }  
         catch ( Exception e )  
          {  
             LogManager.logError ( "Unable to decrypt input string.", e ) ; 
          }  
         return null; 
      }  
  }  
 


public final byte[] doFinal(byte[] input)
                     throws IllegalBlockSizeException,
                            BadPaddingException
See Also:
IllegalStateException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final int doFinal(byte[] output,
                         int outputOffset)
                  throws IllegalBlockSizeException,
                         ShortBufferException,
                         BadPaddingException
See Also:
IllegalStateException, getOutputSize
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[1565]Encrypt larger data
By Anonymous on 2005/10/08 18:10:23  Rate
//This piece of code could give you javax.crypto.IllegalBlockSizeException: Data must not be longer than 245 bytes 
  
  
 Cipher cipher = Cipher.getInstance ( "RSA" ) ; 
 cipher.init ( Cipher.ENCRYPT_MODE, rsaPublic ) ; 
 encryptedData = cipher.doFinal ( originalData ) ; 
  
  
  
 //The RSA algorithm can only encrypt data that has a maximum byte length of the RSA key length in bits divided with eight minus eleven padding bytes, i.e. number of maximum bytes = key length in bits / 8 - 11. In your case it means 2048 / 8 - 11 = 245. If you want to encrypt larger data, then use a larger key, for example, a key with 4096 bits will allow you to encrypt 501 bytes of data.   
 


public final byte[] doFinal(byte[] input,
                            int inputOffset,
                            int inputLen)
                     throws IllegalBlockSizeException,
                            BadPaddingException
See Also:
IllegalStateException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final int doFinal(byte[] input,
                         int inputOffset,
                         int inputLen,
                         byte[] output)
                  throws ShortBufferException,
                         IllegalBlockSizeException,
                         BadPaddingException
See Also:
IllegalStateException, getOutputSize
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final int doFinal(byte[] input,
                         int inputOffset,
                         int inputLen,
                         byte[] output,
                         int outputOffset)
                  throws ShortBufferException,
                         IllegalBlockSizeException,
                         BadPaddingException
See Also:
IllegalStateException, getOutputSize
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final int doFinal(ByteBuffer input,
                         ByteBuffer output)
                  throws ShortBufferException,
                         IllegalBlockSizeException,
                         BadPaddingException
See Also:
ReadOnlyBufferException, IllegalArgumentException, IllegalStateException, getOutputSize
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public static final int ENCRYPT_MODE
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final String getAlgorithm()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final int getBlockSize()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final ExemptionMechanism getExemptionMechanism()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public static final Cipher getInstance(String transformation)
                                throws NoSuchAlgorithmException,
                                       NoSuchPaddingException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


[1560]Add a new security provider
By Anonymous on 2005/10/07 05:25:11  Rate
//add a new security provider 
 import org.bouncycastle.jce.provider.BouncyCastleProvider; 
  
  
 java.security.Security.addProvider ( new org.bouncycastle.jce.provider.BouncyCastleProvider (  )  ) ;  
 Cipher c = Cipher.getInstance ( "RSA/ECB/PKCS1Padding", "BC" ) ;


public static final Cipher getInstance(String transformation,
                                       String provider)
                                throws NoSuchAlgorithmException,
                                       NoSuchProviderException,
                                       NoSuchPaddingException
See Also:
IllegalArgumentException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public static final Cipher getInstance(String transformation,
                                       Provider provider)
                                throws NoSuchAlgorithmException,
                                       NoSuchPaddingException
See Also:
IllegalArgumentException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final byte[] getIV()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public static final int getMaxAllowedKeyLength(String transformation)
                                        throws NoSuchAlgorithmException
See Also:
NullPointerException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public static final AlgorithmParameterSpec getMaxAllowedParameterSpec(String transformation)
                                                               throws NoSuchAlgorithmException
See Also:
NullPointerException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final int getOutputSize(int inputLen)
See Also:
IllegalStateException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final AlgorithmParameters getParameters()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final Provider getProvider()
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final void init(int opmode,
                       Certificate certificate)
                throws InvalidKeyException
See Also:
getIV, getParameters
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final void init(int opmode,
                       Certificate certificate,
                       SecureRandom random)
                throws InvalidKeyException
See Also:
getIV, getParameters
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final void init(int opmode,
                       Key key)
                throws InvalidKeyException
See Also:
SecureRandom, getIV, getParameters
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final void init(int opmode,
                       Key key,
                       AlgorithmParameters params)
                throws InvalidKeyException,
                       InvalidAlgorithmParameterException
See Also:
SecureRandom, getIV, getParameters
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final void init(int opmode,
                       Key key,
                       AlgorithmParameters params,
                       SecureRandom random)
                throws InvalidKeyException,
                       InvalidAlgorithmParameterException
See Also:
getIV, getParameters
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final void init(int opmode,
                       Key key,
                       SecureRandom random)
                throws InvalidKeyException
See Also:
getIV, getParameters
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final void init(int opmode,
                       Key key,
                       AlgorithmParameterSpec params)
                throws InvalidKeyException,
                       InvalidAlgorithmParameterException
See Also:
SecureRandom, getIV, getParameters
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final void init(int opmode,
                       Key key,
                       AlgorithmParameterSpec params,
                       SecureRandom random)
                throws InvalidKeyException,
                       InvalidAlgorithmParameterException
See Also:
getIV, getParameters
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public static final int PRIVATE_KEY
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public static final int PUBLIC_KEY
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public static final int SECRET_KEY
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final Key unwrap(byte[] wrappedKey,
                        String wrappedKeyAlgorithm,
                        int wrappedKeyType)
                 throws InvalidKeyException,
                        NoSuchAlgorithmException
See Also:
IllegalStateException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public static final int UNWRAP_MODE
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final byte[] update(byte[] input)
See Also:
IllegalStateException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final byte[] update(byte[] input,
                           int inputOffset,
                           int inputLen)
See Also:
IllegalStateException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final int update(byte[] input,
                        int inputOffset,
                        int inputLen,
                        byte[] output)
                 throws ShortBufferException
See Also:
IllegalStateException, getOutputSize
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final int update(byte[] input,
                        int inputOffset,
                        int inputLen,
                        byte[] output,
                        int outputOffset)
                 throws ShortBufferException
See Also:
IllegalStateException, getOutputSize
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final int update(ByteBuffer input,
                        ByteBuffer output)
                 throws ShortBufferException
See Also:
ReadOnlyBufferException, IllegalArgumentException, IllegalStateException, getOutputSize
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public final byte[] wrap(Key key)
                  throws IllegalBlockSizeException,
                         InvalidKeyException
See Also:
IllegalStateException
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  


public static final int WRAP_MODE
Geek's Notes:
Description  Add your codes or notes  Search More Java Examples  

Popular Tags