自己改进后:package Fastmule.Android;import java.security.SecureRandom;    //文件流
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.InputStream;import javax.crypto.Cipher;    
import javax.crypto.KeyGenerator;    
import javax.crypto.SecretKey;    
import javax.crypto.spec.SecretKeySpec;    
/*
加密 – 
1.String encryptingCode = SimpleCrypto.encrypt(masterPassword,originalText);
解密 – 
1.String originalText = SimpleCrypto.decrypt(masterpassword, encryptingCode);
  
 */
   
public class AES {    
   
    public static String encrypt(String seed, String cleartext) throws Exception {    
        byte[] rawKey = getRawKey(seed.getBytes());    
        byte[] result = encrypt(rawKey, cleartext.getBytes());    
        return toHex(result);    
    }    
        
    public static String decrypt(String seed, String encrypted) throws Exception {    
        byte[] rawKey = getRawKey(seed.getBytes());    
        byte[] enc = toByte(encrypted);    
        byte[] result = decrypt(rawKey, enc);    
        return new String(result);    
    }    
   
    private static byte[] getRawKey(byte[] seed) throws Exception {    
        KeyGenerator kgen = KeyGenerator.getInstance("AES");    
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");    
        sr.setSeed(seed);    
        kgen.init(128, sr); // 192 and 256 bits may not be available    
        SecretKey skey = kgen.generateKey();    
        byte[] raw = skey.getEncoded();    
        return raw;    
    }    
   
        
    private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {    
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");    
        Cipher cipher = Cipher.getInstance("AES");    
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);    
        byte[] encrypted = cipher.doFinal(clear);    
        return encrypted;    
    }    
   
    private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {    
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");    
        Cipher cipher = Cipher.getInstance("AES");    
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);    
        byte[] decrypted = cipher.doFinal(encrypted);    
        return decrypted;    
    }    
   
    public static String toHex(String txt) {    
        return toHex(txt.getBytes());    
    }    
    public static String fromHex(String hex) {    
        return new String(toByte(hex));    
    }    
        
    public static byte[] toByte(String hexString) {    
        int len = hexString.length()/2;    
        byte[] result = new byte[len];    
        for (int i = 0; i < len; i++)    
            result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();    
        return result;    
    }    
   
    public static String toHex(byte[] buf) {    
        if (buf == null)    
            return "";    
        StringBuffer result = new StringBuffer(2*buf.length);    
        for (int i = 0; i < buf.length; i++) {    
            appendHex(result, buf[i]);    
        }    
        return result.toString();    
    }  
    // 加密文件 
    public static void EncryptFile(String pwd, File fileIn,File fileOut) throws Exception 
    { 
      try 
      {  
        //读取文件 
        FileInputStream fis = new FileInputStream(fileIn); 
        byte[] bytIn=readbyte(fis);
        //AES加密 
        KeyGenerator kgen = KeyGenerator.getInstance("AES"); 
        kgen.init(128, new SecureRandom(pwd.getBytes())); 
        SecretKey skey = kgen.generateKey(); 
        byte[] raw = skey.getEncoded(); 
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); 
        Cipher cipher = Cipher.getInstance("AES"); 
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec); 
        //写文件 
        byte[] bytOut = cipher.doFinal(bytIn); 
        FileOutputStream fos = new FileOutputStream(fileOut); 
        InputStream sbs = new ByteArrayInputStream(bytOut);  
        fos.write(readbyte(sbs));
        fos.close(); 
        fis.close(); 
      } 
      catch (Exception e) 
      { 
        throw new Exception(e.getMessage()); 
      } 
    } 
    
    // 解密文件 
    public static void DecryptFile(String pwd, File fileIn,File fileOut) throws Exception 
    { 
      try 
      { 
        //读取文件         FileInputStream fis = new FileInputStream(fileIn); 
        byte[] bytIn=readbyte(fis);
        
        //AES解密 
        KeyGenerator kgen = KeyGenerator.getInstance("AES"); 
        kgen.init(128, new SecureRandom(pwd.getBytes())); 
        SecretKey skey = kgen.generateKey(); 
        byte[] raw = skey.getEncoded(); 
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); 
        Cipher cipher = Cipher.getInstance("AES"); 
        cipher.init(Cipher.DECRYPT_MODE, skeySpec); 
        //写文件 
        byte[] bytOut = cipher.doFinal(bytIn); 
        FileOutputStream fos = new FileOutputStream(fileOut); 
        InputStream sbs = new ByteArrayInputStream(bytOut);  
        fos.write(readbyte(sbs));
        fos.close(); 
        fis.close(); 
      } 
      catch (Exception e) 
      { 
        throw new Exception(e.getMessage()); 
      } 
    } 
    //读取InputStream转换为byte函数 ----2011-02-23 by hrg
protected static byte[] readbyte(InputStream stream)
{
try 
{
ByteArrayOutputStream baos = new ByteArrayOutputStream( 8196 );
byte[] buffer = new byte[1024];
int length = 0;
while ( ( length = stream.read( buffer ) ) > 0 ) 
{
baos.write( buffer, 0, length );
    }
return baos.toByteArray();

}
catch ( Exception exception ) 
{
return exception.getMessage().getBytes();
}
}
    private final static String HEX = "0123456789ABCDEF";    
    private static void appendHex(StringBuffer sb, byte b) {    
        sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));    
    }    
        
}现在可以对文件加密解密了
但是却解不了delphi用AES加密过的文件,同样的文件用php的AES却可以解密,郁闷了
解密delphi的AES加密文件出现:java.lang .Exception:last block incomplete in decryption错误
而自己加密解密却没问题

解决方案 »

  1.   

    稍微改下:// 加密文件
        public static void EncryptFile(String pwd, File fileIn,File fileOut) throws Exception 
        { 
          try 
          {  
            //读文件
            FileInputStream fis = new FileInputStream(fileIn); 
            byte[] bytIn=readbyte(fis);
            //AES加密
            KeyGenerator kgen = KeyGenerator.getInstance("AES"); 
            kgen.init(128, new SecureRandom(pwd.getBytes())); 
            SecretKey skey = kgen.generateKey(); 
            byte[] raw = skey.getEncoded(); 
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); 
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); 
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec); 
            //写文件
            byte[] bytOut = cipher.doFinal(bytIn); 
            FileOutputStream fos = new FileOutputStream(fileOut); 
            InputStream sbs = new ByteArrayInputStream(bytOut);  
            fos.write(readbyte(sbs));
            fos.close(); 
            fis.close(); 
          } 
          catch (Exception e) 
          { 
            throw new Exception(e.getMessage()); 
          } 
        } 
        
        //解密文件
        public static void DecryptFile(String pwd, File fileIn,File fileOut) throws Exception 
        { 
          try 
          { 
            //读文件
            FileInputStream fis = new FileInputStream(fileIn); 
            byte[] bytIn=readbyte(fis);
            //AES解密
            KeyGenerator kgen = KeyGenerator.getInstance("AES"); 
            kgen.init(256, new SecureRandom(pwd.getBytes())); 
            SecretKey skey = kgen.generateKey(); 
            byte[] raw = skey.getEncoded(); 
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); 
            Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); 
            cipher.init(Cipher.DECRYPT_MODE, skeySpec); 
            //写文件
            //byte[] bytIn_tmp = interceptByte(bytIn,8,8);
            byte[] bytOut = cipher.doFinal(bytIn); 
            FileOutputStream fos = new FileOutputStream(fileOut);
            InputStream sbs = new ByteArrayInputStream(bytOut);  
            fos.write(readbyte(sbs));
            fos.close(); 
            fis.close(); 
          } 
          catch (Exception e) 
          { 
            throw new Exception(e.getMessage()); 
          } 
        } 可是在PHP加密过的文件,用JAVA解出来却是乱码
    PHP的AES加密函数:function fnEncrypt($sValue, $sSecretKey)
    {
      return trim(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $sSecretKey, $sValue, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND)));
    }哪个能帮我看看,JAVA的解密程序哪里有问题吗?