2010-11-10 53 views
2

我想运行一个简单的加密/解密程序。我得到一个填充异常。必须有隐藏的东西,我不知道。我基本上加密了一个字符串,把它写入一个文件,读回来并解密。原始加密阵列解密没有问题。我将原始加密阵列与从文件中读回的阵列进行了比较,它们与我所能看到的完全相同。文件中的缓冲区不起作用,所以一定有区别。我不知道该怎么办。javax.crypto.BadPaddingException:错误

import java.security.*; 
import java.security.spec.InvalidKeySpecException; 
import javax.crypto.Cipher; 
import javax.crypto.spec.SecretKeySpec; 

import java.io.*; 

public class sample 
{ 
    private static String _algo = "AES"; 
    private static byte[] _key = new byte[16]; 

    public static byte[] encrypt (String val) throws Exception 
    { 
     Key key = new SecretKeySpec (_key, _algo); 
     Cipher c = Cipher.getInstance (_algo); 

     c.init (Cipher.ENCRYPT_MODE, key); 

     byte[] encode = c.doFinal (val.getBytes()); 

     return encode; 
    } 

    public static String decrypt (byte[] val) throws Exception  
    { 
     Key key = new SecretKeySpec (_key, _algo); 
     Cipher c = Cipher.getInstance (_algo); 

     c.init (Cipher.DECRYPT_MODE, key); 

     byte[] decode = c.doFinal (val); 

     String decodeStr = new String (decode); 

     return decodeStr; 
    } 

    public static void main (String[] args) throws Exception 
    { 
     String str = "Good bye cruel world"; 

     // 
     // get password from command line 
     // 
     _key = args[0].getBytes(); 

     byte[] encodeArray = sample.encrypt (str); 

     // 
     // write encrypted array to file 
     // 
     FileOutputStream os = new FileOutputStream ("data"); 
     os.write (encodeArray); 
     os.close(); 

     // 
     // decode and print out string 
     // 
     String decodeStr = sample.decrypt (encodeArray); 
     System.out.println ("decodeStr = " + decodeStr); 

     // 
     // read back encrypted string 
     byte[] buffer = new byte[64]; 
     FileInputStream is = new FileInputStream ("data"); 
     is.read (buffer); 
     is.close(); 

     decodeStr = sample.decrypt (buffer); 
     System.out.println ("decodeStr = " + decodeStr); 
    } 
} 

输出:

java sample 123456789
decodeStr = Good bye cruel world 
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded 
     at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..) 
     at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..) 
     at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..) 
     at javax.crypto.Cipher.doFinal(DashoA13*..) 
     at sample.decrypt(sample.java:32) 
     at sample.main(sample.java:70) 

回答

5

的问题是,大小为64,其中您正在阅读的文件到字节的缓冲区,太大了。将其更改为32

或使用文件的长度是这样的:

byte[] buffer = new byte[(int)new File("data").length()]; 
+0

好,它的工作原理。谢谢。 – tadpole 2010-11-10 17:08:37

相关问题