2010-03-31 67 views
1

下面的代碼是一個嘗試對數據進行加密使用AES與非對稱密鑰:AES碼投擲NoSuchPaddingException:填充NoPaddin未知

import java.io.OutputStream; 
import java.math.BigInteger; 
import java.security.Key; 
import java.security.KeyFactory; 
import java.security.interfaces.RSAPrivateKey; 
import java.security.interfaces.RSAPublicKey; 
import java.security.spec.RSAPrivateKeySpec; 
import java.security.spec.RSAPublicKeySpec; 

import javax.crypto.Cipher; 

public class AsyncronousKeyTest { 

    private final Cipher cipher; 
    private final KeyFactory keyFactory; 
    private final RSAPrivateKey privKey; 

    private AsyncronousKeyTest() throws Exception { 
cipher = Cipher.getInstance("AES/CBC/NoPaddin", "BC"); 
keyFactory = KeyFactory.getInstance("AES", "BC"); 

// create the keys 

RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(new BigInteger(
    "d46f473a2d746537de2056ae3092c451", 16), new BigInteger("57791d5430d593164082036ad8b29fb1", 
    16)); 
privKey = (RSAPrivateKey) keyFactory.generatePrivate(privKeySpec); 

    } 

    public void generateAuthorizationAct(OutputStream outputStream) throws Exception { 

KeyFactory keyFactory = KeyFactory.getInstance("AES", "BC"); 
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger("d46f473a2d746537de2056ae3092c451", 
    16), new BigInteger("11", 16)); 
RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec); 

byte[] data = new byte[] {0x01}; 

byte[] encrypted = encryptAO(pubKey, data); 
outputStream.write(encrypted); 
    } 

    /** Encrypt the AuthorizationObject. */ 
    public byte[] encryptAO(Key pubKey, byte[] data) throws Exception { 
cipher.init(Cipher.ENCRYPT_MODE, pubKey); 
byte[] cipherText = cipher.doFinal(data); 
return cipherText; 
    } 

    public byte[] decrypt(byte[] cipherText) throws Exception { 
cipher.init(Cipher.DECRYPT_MODE, privKey); 
byte[] decyptedData = cipher.doFinal(cipherText); 
return decyptedData; 

    } 

    public static void main(String[] args) throws Exception { 
System.out.println("start"); 

AsyncronousKeyTest auth = new AsyncronousKeyTest(); 
auth.generateAuthorizationAct(System.out); 

System.out.println("done"); 
    } 

} 

,但在行

cipher = Cipher.getInstance("AES/CBC/NoPaddin", "BC"); 

它拋出

NoSuchPaddingException: Padding NoPaddin unknown. 

這是什麼?以及如何解決?

回答

3

「Padding」不是「Paddin」。 「g」很重要。

此外,「用非對稱密鑰AES加密數據」是沒有意義的。正如其名稱所述,RSA密鑰用於RSA,而不用於AES。 AES使用對稱密鑰,即長度爲16,24或32字節的(任意)字節數組。 RSA密鑰是由兩個整數組成的數學對象,其中一個非常大(通常爲1024位)。

+0

「g」甚至沒有發音..:P 但它應該不重要.. :) 謝謝,順便說一下 – 2010-04-01 19:41:03