java.security.InvalidKeyException:密钥长度不是 128/192/256 位

2023-12-30

我是 Java 新手,尝试使用混合加密,使用 AES-128 对称加密,然后对生成的对称密钥使用 RSA-1024 非对称加密。有人可以帮助我为什么会收到此异常吗?我已经关注了其他帖子,并在相应的文件夹中下载了 Java 加密扩展 (JCE) 无限强度管辖权策略文件版本 6。

Code snippet:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.Key;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Security;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

    public class MainClass {

        /**
         * @param args
         * Encryption and Decryption with AES/ECB/PKCS7Padding  and RSA/ECB/PKCS1Padding
         */
        public static void main(String[] args) throws Exception {
            // TODO Auto-generated method stub
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());   
            System.out.println("Enter a Message to be encrypted!");
            // Read an input from console
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);
            String s = br.readLine();

            // Get the bytes of the input stream. Convert the input text
            // to bytes.
            byte[] input = s.getBytes("UTF8");

            System.out.println("Input Message : " + new String(input));

            // AES 128 bits Symmetric encryption of data

            // Generate the AES key for Symmetric AES encryption
            KeyGenerator kgenerator = KeyGenerator.getInstance("AES", "BC");
            SecureRandom random = new SecureRandom();
            kgenerator.init(128, random);

            Key aeskey = kgenerator.generateKey();
            byte[] raw = aeskey.getEncoded();
            int sykLength = raw.toString().length();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

            System.out.println("Generated Symmetric Key :" + raw);
            System.out.println("Generated Symmetric Key Length :" + sykLength);
            System.out.println("Generated Key Length in Bytes: " + raw.length);

            // Encrypt the data using AES cipher
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);         
            byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
            int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
            ctLength += cipher.doFinal(cipherText, ctLength);

            System.out.println("Encrypted Message :" + new String(cipherText));
            System.out.println("Encrypted Message Length: " + ctLength);

           // RSA 1024 bits Asymmetric encryption of Symmetric AES key

          // Generate Public and Private Keys (Can also use a certificate for keys)
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
            kpg.initialize(1024, random);
            KeyPair kpa = kpg.genKeyPair();
            RSAPublicKey pubKey = (RSAPublicKey) kpa.getPublic();
            RSAPrivateKey privKey = (RSAPrivateKey)kpa.getPrivate();    

          // Encrypt the generated Symmetric AES Key using RSA cipher  
            Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");            
            rsaCipher.init(Cipher.ENCRYPT_MODE, pubKey);            
            byte[] rawRSA = raw.toString().getBytes("UTF8");
            byte[] cipherTextRSA = new byte[rsaCipher.getOutputSize(rawRSA.length)];
            int ctLengthRSA = rsaCipher.update(rawRSA, 0, rawRSA.length, cipherTextRSA, 0);
            ctLengthRSA += rsaCipher.doFinal(cipherTextRSA, ctLengthRSA);

            System.out.println("Encrypted Symmetric Key :" + cipherTextRSA);
            System.out.println("Encrypted Symmetric Key Length :" + ctLengthRSA);
            System.out.println("Encrypted Symmetric Key Length in Bytes: " + cipherTextRSA.length);

            // RSA Decryption of Encrypted Symmetric AES key
            rsaCipher.init(Cipher.DECRYPT_MODE, privKey);
            byte[] plainTextRSA = new byte[rsaCipher.getOutputSize(ctLengthRSA)];
            int ptLengthRSA = rsaCipher.update(cipherTextRSA, 0, ctLengthRSA, plainTextRSA, 0);
            ptLengthRSA += rsaCipher.doFinal(plainTextRSA, ptLengthRSA);
            SecretKeySpec DecrypskeySpec = new SecretKeySpec(plainTextRSA, "AES");  

            System.out.println("Decrypted Symmetric Key: " + new String(plainTextRSA));
            System.out.println("Decrypted Symmetric Key Length: " + ptLengthRSA);       
            System.out.println( "Decrypted Symmetric Key Length in Bytes: " + plainTextRSA.length);

                cipher.init(Cipher.DECRYPT_MODE, DecrypskeySpec, cipher.getParameters());
                byte[] plainText = new byte[cipher.getOutputSize(ctLength)];
                int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0);
                ptLength += cipher.doFinal(plainText, ptLength);
                System.out.println("Decrypted Message: " + new String(plainText));
                System.out.println("Decrypted Message Length: " + ptLength);
                System.out.println("Decrypted Message Length in Bytes: " + plainText.length);
        }
    }

我得到的异常:

Enter a Message to be encrypted!
test
Input Message : test
Generated Symmetric Key :[B@1c74f37
Generated Symmetric Key Length :10
Generated Key Length in Bytes: 16
Encrypted Message :ýÒSœW¶Þ34Ý­GÝ
Encrypted Message Length: 16
Encrypted Symmetric Key :[B@1df280b
Encrypted Symmetric Key Length :128
Encrypted Symmetric Key Length in Bytes: 128
Decrypted Symmetric Key: [B@1c74f37         (Some symbols I got along with this decrypted key which I could not paste here)
Decrypted Symmetric Key Length in Bytes: 117
Exception in thread "main" java.security.InvalidKeyException: Key length not 128/192/256 bits.
    at org.bouncycastle.jce.provider.JCEBlockCipher.engineInit(Unknown Source)
    at org.bouncycastle.jce.provider.JCEBlockCipher.engineInit(Unknown Source)
    at javax.crypto.Cipher.init(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
    at com.sap.srm.crpto.client.applet.MainClass.main(MainClass.java:99)

实际上,您尝试使用非对称 RSA 包装和解开对称密钥时出现了相当多的错误,因此我将其清理了(我的计算机上没有 Bouncy Castle,因此我使用了默认的 Sun 提供程序,请随意添加“BC” “ 需要时):

KeyGenerator kgenerator = KeyGenerator.getInstance("AES");
SecureRandom random = new SecureRandom();
kgenerator.init(128, random);
Key aeskey = kgenerator.generateKey();

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024, random);
KeyPair kpa = kpg.genKeyPair();
PublicKey pubKey = kpa.getPublic();
PrivateKey privKey = kpa.getPrivate();    

// Encrypt the generated Symmetric AES Key using RSA cipher  
Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");            
rsaCipher.init(Cipher.WRAP_MODE, pubKey);
byte[] encryptedSymmKey = rsaCipher.wrap(aeskey);            
// RSA Decryption of Encrypted Symmetric AES key
rsaCipher.init(Cipher.UNWRAP_MODE, privKey);
Key decryptedKey = rsaCipher.unwrap(encryptedSymmKey, "AES", Cipher.SECRET_KEY);

System.out.println("Decrypted Key Length: " + decryptedKey.getEncoded().length * 8); // -> 128
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

java.security.InvalidKeyException:密钥长度不是 128/192/256 位 的相关文章

随机推荐

  • c++ std::unique_ptr 不会在地图中编译

    我目前正在尝试将 std unique ptr 存储在 std unordered map 中 但出现奇怪的编译错误 相关代码 pragma once include Entity h include
  • java求n个数组之间的公共元素之和

    我有一个程序对两个数组的公共元素求和 为此 我使用了两个 for 循环 如果我有三个 那么我可以使用三个 for 循环 但是如何对运行时出现的 n 个数组的公共元素求和 我不知道如何在运行时更改循环数 或者是否有其他相关概念 这是我尝试对两
  • 如何测试变量是否是 Moment.js 对象?

    我的应用程序有一个 HTML 表单 其中一些输入是从后端填充的 其他输入是由用户输入的 在time输入 一个onChange当用户更改值时 函数会遍历每个输入 从后端填充的输入被转换为moment对象 用户输入的日期只是字符串 这意味着on
  • 为什么阻止未来被认为是一种不好的做法?

    我试图理解该声明背后的理性对于绝对需要封锁的情况 期货可以被封锁 尽管不鼓励这样做 http docs scala lang org sips pending futures promises html 背后的想法ForkJoinPool是
  • 为什么backgroundColor应用到了我不想要的地方| MUI 中的菜单组件 |样式组件

    我将 mui 中的菜单组件的背景颜色设置为粉红色 这就是我单击时看到的内容dashboard button 我预计这会为菜单添加背景颜色 但结果页面的一半变成了粉红色 如何将背景颜色应用于菜单 import as React from re
  • 在 Express 服务器上成功调用 api 后使用角度路由重定向页面

    在使用角度路由的单页面应用程序中 如何在 api 调用后重定向页面 就我而言 我想在用户调用登录 api 后将用户重定向到个人资料页面 所以这就是我认为可行的方法 但事实并非如此 在客户端 main js 我已经设置了角度路由 app co
  • 使用 PHP 查看 HTML 中的 base64 编码的 blob

    我遇到了一些麻烦 我正在尝试查看以 blob 形式保存在我的服务器上的 Base64 编码图像 我想使用图像标签查看内部内容 或者将其作为 html 文件回显 我可以使用图像标签引用该文件 问题是 blob 数据从我的服务器返回错误
  • 如何使用C#graphics.DrawString绘制unicode字符串

    我正在尝试使用 NET 框架提供的 PrintDocument 将高棉脚本 unicode 字符串发送到打印机 不幸的是 在我看来 Graphics DrawString 无法正确渲染高棉脚本 平台 Windows 7旗舰版IDE VS 2
  • 每次打开 Xcode 时 Xcode 都会意外退出

    当我打开 Xcode 版本 7 3 1 时显示此消息 Xcode 意外退出 我测试这个命令 sudo gem 安装 cocoapods sudo 应用程序 Xcode xcode 我看到这个链接但对我不起作用在此输入链接描述 https s
  • 为什么 std::is_copy_constructible_v> 为 true?

    在我的 clang 和 libc 版本中 接近HEAD this static assert passes static assert std is copy constructible v
  • 如何将应用程序生成的文件存储在Android的“下载”文件夹中?

    我正在我的应用程序中生成一个 Excel 工作表 生成后应自动保存在 下载 通常保存所有下载的任何 Android 设备的文件夹 我有以下内容将文件保存在 我的文件 文件夹下 File file new File context getEx
  • 在循环中评估 Tensorflow 操作非常慢

    我试图通过编码一些简单的问题来学习张量流 我试图使用直接采样蒙特卡罗方法找到 pi 的值 运行时间比我想象的要长得多for loop去做这个 我看过其他关于类似事情的帖子 并且我尝试遵循解决方案 但我认为我仍然一定做错了什么 下面附上我的代
  • Java 中用于拖动组件的 Swing 库

    我正在尝试创建一种图形编辑器 允许用户创建美式足球比赛的图形描述 为此 用户应该能够执行以下操作 1 单击鼠标左键并移动图像 2 更改图像 圆形 方形和线条 3 重置所有对象的大小 理想情况下 我希望能够添加可调整的颜色和线条粗细 但这还很
  • 调整包含的图形大小时,FigureCanvasTkAgg 画布小部件的正确滚动/调整大小行为

    我正在尝试使用 Tkinter 和 matplotlib python 3 7 和 matplotlib 3 0 0 制作交互式绘图 GUI 我希望用户能够调整屏幕上显示的图形大小 而无需调整窗口大小 并通过以下方式实现了这一点编辑图窗的
  • java swing 单选按钮 - java.lang.NullPointerException

    我正在尝试掌握 java swing 并正在测试单选按钮 我的代码是 import java awt import javax swing import javax swing ButtonGroup public class Scafho
  • 如何让 Rails 根据 headers 响应 json

    我正在使用 Rails 4 构建一个 API 并在我的控制器中使用respond to来区分html and json请求一切正常 在 Postman 中测试我的 API 时 我添加了以下标头 Content Type applicatio
  • Powershell 相当于 F# Seq.forall

    我写了这个 有效 function ForAll BEGIN allTrue true PROCESS if lt 1 allTrue false END allTrue aList 0 4 bList 1 4 aList ForAll r
  • UWP 检查当前页面的名称或实例

    在我的 UWP 应用程序中 我从协议或 toast 启动 在 onactivated 方法中 我想检查应用程序的主视图是否打开或正在显示哪个页面 全部来自 App xaml cs 我想做这样的事情 If Mainpage is not sh
  • JFreeChart:鼠标单击获取数据源值

    我有一个显示进程内存状态的 JFreeChart 实例 初始化如下 m data new TimeSeriesCollection TimeSeries vmsize new TimeSeries VMSize TimeSeries res
  • java.security.InvalidKeyException:密钥长度不是 128/192/256 位

    我是 Java 新手 尝试使用混合加密 使用 AES 128 对称加密 然后对生成的对称密钥使用 RSA 1024 非对称加密 有人可以帮助我为什么会收到此异常吗 我已经关注了其他帖子 并在相应的文件夹中下载了 Java 加密扩展 JCE