草庐IT

java - 请帮助-卡住无效 key 异常

coder 2024-03-30 原文

我收到 java.security.InvalidKeyException: Illegal key size or default parameters,我已经完成了所有必需的步骤,安装了 Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files。 我也经历过这些话题

Java.security.InvalidKeyException: Illegal key size or default parameters error

Java Security: Illegal key size or default parameters?

但我仍然卡住了并收到 java.security.InvalidKeyException: Illegal key size or default parameters ,

下面是我的代码: AESKeyGenerator.java

public class AESKeyGenerator {

    private Cipher mCipher;

    public AESKeyGenerator()
    {
        // default constructor
    }


    public byte[] generate_k(String dhkey, String toEncrypt)
    {
        byte[] retVal;

        try { // Set up the Cipher class of Android to use AES to generate keys
            byte[] iv = new byte[16];
            for (int i = 0; i < iv.length; i++)
                iv[i] = new Byte("0").byteValue();
            IvParameterSpec ivspec = new IvParameterSpec(iv);
            mCipher = Cipher.getInstance("AES");
            // Set up key to use in algorithm
            MessageDigest hasher = MessageDigest.getInstance("SHA-256"); // Initialize object that will hash my key.
            byte[] key256 = hasher.digest(dhkey.getBytes()); // Hash the key to 256 bits using SHA
            SecretKeySpec K = new SecretKeySpec(key256, "AES");
            System.out.println("SecretKeySpec : "+K  + "  key256 "+key256);
            mCipher.init(Cipher.ENCRYPT_MODE, K, ivspec);
            // Encrypt the parameter toEncrypt
            retVal = mCipher.doFinal(toEncrypt.getBytes());
            return retVal;
        }
        catch (Exception e) {
                        e.printStackTrace();
            System.err.println("Could not create and initialize object Cipher.");
        }

        return null;

    }

    public byte[] generate_r(byte[] sharedKey, String toEncrypt)
    {
        byte[] retVal;
        try {
            /*byte[] iv = new byte[16];
            for (int i = 0; i < iv.length; i++)
                iv[i] = new Byte("0").byteValue();
            IvParameterSpec ivspec = new IvParameterSpec(iv);*/

            // Set up the Cipher class of Android to use AES to generate keys
            mCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            // Set up key to use in algorithm
            MessageDigest hasher = MessageDigest.getInstance("SHA-256"); // Initialize object that will hash my key.
            byte[] key256 = hasher.digest(sharedKey); // Hash the key to 256 bits using SHA 256
            SecretKeySpec K = new SecretKeySpec(key256, "AES");
            mCipher.init(Cipher.ENCRYPT_MODE, K);
            // Encrypt the parameter toEncrypt
            System.out.println("toEncrypt AES: "+ toEncrypt);
            retVal = mCipher.doFinal(toEncrypt.getBytes());
            return retVal;
        }
        catch (Exception e) {
                        e.printStackTrace();
            System.err.println("exception: "+ e.toString());
            System.err.println("Could not create and initialize object Cipher.");
        }

        return null;

    }
}

我遇到了休闲错误:

java.security.InvalidKeyException: Illegal key size or default parameters
  at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1010)
  at javax.crypto.Cipher.implInit(Cipher.java:785)
  at javax.crypto.Cipher.chooseProvider(Cipher.java:848)
  at javax.crypto.Cipher.init(Cipher.java:1212)
  at javax.crypto.Cipher.init(Cipher.java:1152)
  at AESKeyGenerator.generate_r(AESKeyGenerator.java:74)
  at DetectionServer.storeGridInformation(DetectionServer.java:309)
  at DetectionServer.doPost(DetectionServer.java:103)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
  at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
  at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
  at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
  at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
  at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
  at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
  at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
  at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
  at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
  at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
  at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
  at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
  at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
  at java.lang.Thread.run(Unknown Source)
exception: java.security.InvalidKeyException: Illegal key size or default parameters
Could not create and initialize object Cipher.

我检查了与此相同的标准代码。我认为配置或缺少库存在一些问题。

最佳答案

不能重现这个 - 我已经安装了当前的 Unlimited Strength Jurisdiction Policy Files我使用了以下主要方法进行测试:

public static void main(String[] args) throws UnsupportedEncodingException {
   AESKeyGenerator aes = new AESKeyGenerator();
   String sharedKey = "Bar12345Bar12345Bar12345Bar12345";
   aes.generate_r(sharedKey.getBytes("US-ASCII"), "Hello World");
}

在安装策略文件之前,我遇到了和你一样的异常。

我首先做错的一件事是我将策略文件安装到 Program files/jdk_1.7.0_13/jre/lib/security 中,但是使用的 JRE 位于 Program files/jre7 - 因此请确保您已将策略文件安装在正确的位置,并使用上面的主要方法检查一个简单的独立 Java 应用程序是否有效。

关于java - 请帮助-卡住无效 key 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15153395/

有关java - 请帮助-卡住无效 key 异常的更多相关文章

  1. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  2. ruby-on-rails - Rails - 乐观锁定总是触发 StaleObjectError 异常 - 2

    我正在学习Rails,并阅读了关于乐观锁的内容。我已将类型为integer的lock_version列添加到我的articles表中。但现在每当我第一次尝试更新记录时,我都会收到StaleObjectError异常。这是我的迁移:classAddLockVersionToArticle当我尝试通过Rails控制台更新文章时:article=Article.first=>#我这样做:article.title="newtitle"article.save我明白了:(0.3ms)begintransaction(0.3ms)UPDATE"articles"SET"title"='dwdwd

  3. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  4. ruby - 有人可以帮助解释类创建的 post_initialize 回调吗 (Sandi Metz) - 2

    我正在阅读SandiMetz的POODR,并且遇到了一个我不太了解的编码原则。这是代码:classBicycleattr_reader:size,:chain,:tire_sizedefinitialize(args={})@size=args[:size]||1@chain=args[:chain]||2@tire_size=args[:tire_size]||3post_initialize(args)endendclassMountainBike此代码将为其各自的属性输出1,2,3,4,5。我不明白的是查找方法。当一辆山地自行车被实例化时,因为它没有自己的initialize方法

  5. ruby-on-rails - Rails 5 Active Record 记录无效错误 - 2

    我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa

  6. ruby - 在 Ruby 中重新分配常量时抛出异常? - 2

    我早就知道Ruby中的“常量”(即大写的变量名)不是真正常量。与其他编程语言一样,对对象的引用是唯一存储在变量/常量中的东西。(侧边栏:Ruby确实具有“卡住”引用对象不被修改的功能,据我所知,许多其他语言都没有提供这种功能。)所以这是我的问题:当您将一个值重新分配给常量时,您会收到如下警告:>>FOO='bar'=>"bar">>FOO='baz'(irb):2:warning:alreadyinitializedconstantFOO=>"baz"有没有办法强制Ruby抛出异常而不是打印警告?很难弄清楚为什么有时会发生重新分配。 最佳答案

  7. ruby-on-rails - Cucumber 是否只是 rspec 的包装器以帮助将测试组织成功能? - 2

    只是想确保我理解了事情。据我目前收集到的信息,Cucumber只是一个“包装器”,或者是一种通过将事物分类为功能和步骤来组织测试的好方法,其中实际的单元测试处于步骤阶段。它允许您根据事物的工作方式组织您的测试。对吗? 最佳答案 有点。它是一种组织测试的方式,但不仅如此。它的行为就像最初的Rails集成测试一样,但更易于使用。这里最大的好处是您的session在整个Scenario中保持透明。关于Cucumber的另一件事是您(应该)从使用您的代码的浏览器或客户端的角度进行测试。如果您愿意,您可以使用步骤来构建对象和设置状态,但通常您

  8. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  9. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  10. java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi? - 2

    什么是ruby​​的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht

随机推荐