我正在用aes算法打印密钥但打印的密钥大小不是128位

moiiocjp  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(473)

打印密钥

KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
SecretKey secretKey = keyGenerator.generateKey();
cipher = Cipher.getInstance("AES");
String plainText = "AES Symmetric Encryption Decryption";
System.out.println("Plain Text Before Encryption: " + plainText);

String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted Text After Encryption: " + encryptedText);

String decryptedText = decrypt(encryptedText, secretKey);
System.out.println("Decrypted Text After Decryption: " + decryptedText);
System.out.println("srecretkey"+secretKey);

我得到的结果是:

Plain Text Before Encryption: AES Symmetric Encryption Decryption
Encrypted Text After Encryption: l4YZj1SjqS/vr1mK9K4LC7lBFfQ4wkJg2zIlb81ghpkM5qnvCyyfMeYop2ppHDoX
Decrypted Text After Decryption: AES Symmetric Encryption Decryption
srecretkeyjavax.crypto.spec.SecretKeySpec@15300

这里的密钥大小不是128位。

wlzqhblo

wlzqhblo1#

你的问题和代码有两个问题。
首先:您询问的是一个128位aes密钥,但keygenerator的参数是“256”,这意味着您生成了一个256位(=32字节)长的aes密钥:

keyGenerator.init(256);

第二:aes密钥是字节数组中的随机数据,不适合打印为字符串。当您需要密钥的打印输出时,有几种方法可以将密钥编码为(base64)编码字符串:

String aesKeyBase64 = Base64.getEncoder().encodeToString(aesKey);

这是示例程序的输出:

Generate a 256 bit = 32 byte long AES key
secretKey: javax.crypto.spec.SecretKeySpec@1518c
aesKey length: 32
aesKey:[B@6d9c638
aesKeyBase64: cWEo4+jv0SXBgbiZbdiouasFYuV3rUYKQ3403y4wU14=

下面是完整的代码,请使用我的联机编译器运行该示例:https://repl.it/@javacrypto/sogenerateaeskey#主.java

import java.security.*;
import javax.crypto.KeyGenerator;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import java.util.Base64;

public class Main {
    public static void main(String[] args) throws NoSuchAlgorithmException {
        System.out.println("Generate a 256 bit = 32 byte long AES key");
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(256);
        SecretKey secretKey = keyGenerator.generateKey();
        System.out.println("secretKey: " + secretKey);
        // the key is a 32 bytes long byte array
        byte[] aesKey = secretKey.getEncoded();
        System.out.println("aesKey length: " + aesKey.length);
        System.out.println("aesKey:" + aesKey);
        // convert to a base64 encoded String
        String aesKeyBase64 = Base64.getEncoder().encodeToString(aesKey);
        System.out.println("aesKeyBase64: " + aesKeyBase64);
    }
}

编辑:
要从base64编码字符串中获取密钥,请使用以下代码行:

SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode("base64string"), "AES");

并将其用作cipher.init的输入:

cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

相关问题