2010-01-20 58 views
0

我能夠使用AES 128進行加密,但密鑰長度更長時會失敗。在嵌入式java 1.4 api中使用256位的AES

使用AES 128的代碼如下。

import java.security.*; 
import javax.crypto.*; 
import javax.crypto.spec.*; 
import java.io.*; 

/** * 該程序生成一個AES密鑰,檢索其原始字節,和 *然後重新實例從密鑰字節的AES密鑰。 *重新實現的密鑰用於初始化加密和解密的AES密碼爲 *。 */

public class AES { 

/** 
* Turns array of bytes into string 
* 
* @param buf Array of bytes to convert to hex string 
* @return Generated hex string 
*/ 
public static String asHex (byte buf[]) { 
    StringBuffer strbuf = new StringBuffer(buf.length * 2); 
    int i; 

    for (i = 0; i < buf.length; i++) { 
    if (((int) buf[i] & 0xff) < 0x10) 
    strbuf.append("0"); 

    strbuf.append(Long.toString((int) buf[i] & 0xff, 16)); 
    } 

    return strbuf.toString(); 
} 

public static void main(String[] args) throws Exception { 

    String message="This is just an example"; 

    // Get the KeyGenerator 

    KeyGenerator kgen = KeyGenerator.getInstance("AES"); 
    kgen.init(128); // 192 and 256 bits may not be available 


    // Generate the secret key specs. 
    SecretKey skey = kgen.generateKey(); 
    byte[] raw = skey.getEncoded(); 

    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); 


    // Instantiate the cipher 

    Cipher cipher = Cipher.getInstance("AES"); 

    cipher.init(Cipher.ENCRYPT_MODE, skeySpec); 

    byte[] encrypted =cipher.doFinal("welcome".getBytes()); 
    System.out.println("encrypted string: " + asHex(encrypted)); 

    cipher.init(Cipher.DECRYPT_MODE, skeySpec); 
    byte[] original = 
    cipher.doFinal(encrypted); 
    String originalString = new String(original); 
    System.out.println("Original string: " + 
    originalString + " " + asHex(original)); 
    } 
} 

回答

3

這可能只是您需要升級/更改您的Java版本。由於有關美國加密產品出口的法律,因此某些版本的Java預先打包時不使用192/256位AES加密。

儘管如此,128位對於大多數情況來說已經足夠了。而不是使用這個代碼直接使用更高級別的庫,如Keyczar。由於各種原因(即ECB編碼),上述代碼是不安全的,我不會相信它。