Java 错误的算法:需要 AES 或 Rijndael

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22357583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:12:35  来源:igfitidea点击:

Wrong algorithm: AES or Rijndael required

javaencryptionaes

提问by Justin Yum

I am new to JAVA. I am going to build a security system for my project. However, I have encountered a problem. Eclipse always points out that "java.security.InvalidKeyException: Wrong algorithm: AES or Rijndael required". I am going to save the encryption key in database. I have checked that the key is correct. The only problem is that I cannot decrypt the ciphertext. Can anyone tell me what the problem is? Actually, I have searched some solutions but the problem is still not yet solved. Please help me. Thanks a lot!

我是 JAVA 新手。我将为我的项目构建一个安全系统。但是,我遇到了一个问题。Eclipse 总是指出“java.security.InvalidKeyException: Wrong algorithm: AES or Rijndael required”。我要将加密密钥保存在数据库中。我已经检查过密钥是否正确。唯一的问题是我无法解密密文。谁能告诉我是什么问题?实际上,我已经搜索了一些解决方案,但问题仍未解决。请帮我。非常感谢!

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class AES {
    public static void main(String[] args) throws Exception {
    String test = "HIHI";
    String tmp = null;
    SecretKey tempKey1 = generateKey();
    saveKey(tempKey1);
    SecretKey tempKey2 = loadKey();
    tmp = encrypt(test, tempKey1);
    String printString = decrypt(tmp, tempKey2);
    System.out.println(printString);

}

public static SecretKey generateKey() throws NoSuchAlgorithmException {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(128);
    SecretKey key = keyGenerator.generateKey();
    return key;
}

public static void saveKey(SecretKey key) throws IOException {
    String stringKey = Base64.encodeBase64String(key.getEncoded());
    System.out.println("stringKey: " + stringKey);
    try {
        final PreparedStatement pstmt;

        // Register the JDBC driver
        // for MySQL.
        Class.forName("com.mysql.jdbc.Driver");

        // Define URL of database
        // server for
        // database named JunkDB on
        // the localhost
        // with the default port
        // number 3306.
        String url = "jdbc:mysql://127.0.0.1:3306/fyp";

        // Get a connection to the
        // database for a
        // user named auser with the
        // password
        // drowssap, which is
        // password spelled
        // backwards.
        Connection con = DriverManager.getConnection(url, "user", "user");

        pstmt = con.prepareStatement("insert into compfyp values (?)");
        pstmt.setString(1, stringKey);

        pstmt.executeUpdate();

        pstmt.close();

        con.close();
    } catch (Exception e) {
        e.printStackTrace();
    }// end catch

}

public static SecretKey loadKey() throws IOException {
    String stringKey = null;
    try {
        Statement stmt;
        ResultSet rs;

        // Register the JDBC driver for MySQL
        Class.forName("com.mysql.jdbc.Driver");

        // Define URL of database server for database named comp2220
        String url = "jdbc:mysql://127.0.0.1:3306/fyp";

        // Get a connection to the database for a user named user with the
        // password userpassword, which is password spelled backwards
        Connection con = DriverManager.getConnection(url, "user", "user");

        // Get a Statement object
        stmt = con.createStatement();

        // Get another statement object initialized as shown
        stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);

        // Query the database, storing the result in an object of type
        // ResultSet
        rs = stmt.executeQuery("SELECT * from compfyp");

        // Use the methods of class ResultSet in a loop to display all of
        // the data in the database.
        while (rs.next()) {
            stringKey = rs.getString("encryptionkey");

        }// end while loop
        con.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    byte[] encodedKey = Base64.decodeBase64(stringKey);
    SecretKey trueKey = new SecretKeySpec(encodedKey, 0, encodedKey.length,
            "AES/ECB/PKCS5Padding");
    System.out.println("after encode & decode secret_key:"
            + Base64.encodeBase64String(trueKey.getEncoded()));

    return trueKey;
}

public static String encrypt(String plaintext, SecretKey encryptionKey)
        throws Exception {
    IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, iv);
    byte[] encryptData = cipher.doFinal(plaintext.getBytes());

    return encryptData.toString();

}

public static String decrypt(String ciphertext, SecretKey encryptionKey)
        throws Exception {
    IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
    SecretKeySpec spec = new SecretKeySpec(encryptionKey.getEncoded(),
            "AES/CBC/PKCS5Padding");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, spec, iv);
    byte[] encryptData = ciphertext.getBytes();
    ;

    byte[] original = cipher.doFinal(encryptData);
    return new String(original);

}

}

}

采纳答案by dario nascimento

The SecretKeySpecshould receive "AES", the mode is specified on Cipher. I cut some of your code to test. Here you have:

SecretKeySpec接收到“AES”,被指定的模式Cipher。我剪掉了你的一些代码来测试。在这里你有:

public class AES {
    public static void main(String[] args) throws Exception {
        byte[] data = "abcdefghijkl".getBytes();
        byte[] tmp = null;
        SecretKey tempKey1 = generateKey();
        // saveKey(tempKey1);
        // SecretKey tempKey2 = loadKey();
        tmp = encrypt(data, tempKey1);
        byte[] printString = decrypt(tmp, tempKey1);
        System.out.println(Arrays.equals(data, printString));

    }

    public static SecretKey generateKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        SecretKey key = keyGenerator.generateKey();
        return key;
    }

    public static byte[] encrypt(byte[] data, SecretKey encryptionKey) throws Exception {
        IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, iv);
        byte[] encryptData = cipher.doFinal(data);

        return encryptData;
    }

    public static byte[] decrypt(byte[] tmp, SecretKey encryptionKey) throws Exception {
        IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes());
        SecretKeySpec spec = new SecretKeySpec(encryptionKey.getEncoded(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, spec, iv);

        System.out.println(tmp.length);
        return cipher.doFinal(tmp);

    }
}

One extra detail: use base64 for cyphered data instead of String...

一个额外的细节:对加密数据使用 base64 而不是 String ...