代码之家  ›  专栏  ›  技术社区  ›  Student

aes代码引发nosuchpadingException:padding nopadin未知

  •  1
  • Student  · 技术社区  · 16 年前

    以下代码是尝试使用具有非对称密钥的AES加密数据:

    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.
    

    这是什么?如何解决?

    1 回复  |  直到 16 年前
        1
  •  3
  •   Thomas Pornin    16 年前

    “padding”不是“paddin”。“G”很重要。

    另外,“用非对称密钥加密数据”。顾名思义,RSA密钥是为RSA而不是为AES而设的。AES使用对称密钥,即长度为16、24或32字节的(任意)字节数组。RSA密钥是由两个整数组成的数学对象,其中一个非常大(通常为1024位)。