进行椭圆曲线加密时无效的密钥异常

时间:2013-11-07 09:32:36

标签: java security cryptography jce elliptic-curve

当我使用flexyprovider进行椭圆曲线加密时,我遇到了这个错误。我收到了InvalidKeyException,但我无法弄清楚如何解决它:

Exception in thread "main" java.security.InvalidKeyException: Illegal key size
at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1024)
at javax.crypto.Cipher.init(Cipher.java:1345)
at javax.crypto.Cipher.init(Cipher.java:1282)
at ExampleECIES.main(ExampleECIES.java:43)

这是我的代码

public class ExampleECIES {

    public static void main(String[] args) throws Exception {

    Security.addProvider(new FlexiCoreProvider());
    Security.addProvider(new FlexiECProvider());

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECIES", "FlexiEC");

    CurveParams ecParams = new BrainpoolP160r1();

    kpg.initialize(ecParams, new SecureRandom());
    KeyPair keyPair = kpg.generateKeyPair();
    PublicKey pubKey = keyPair.getPublic();
    PrivateKey privKey = keyPair.getPrivate();

    // Encrypt

    Cipher cipher = Cipher.getInstance("ECIES", "FlexiEC");

    IESParameterSpec iesParams = new IESParameterSpec("AES128_CBC",
        "HmacSHA1", null, null);
    System.out.println(iesParams);
    cipher.init(Cipher.ENCRYPT_MODE, pubKey, iesParams);

    String cleartextFile = "cleartext.txt";
    String ciphertextFile = "ciphertextECIES.txt";

    byte[] block = new byte[64];
    FileInputStream fis = new FileInputStream(cleartextFile);
    FileOutputStream fos = new FileOutputStream(ciphertextFile);
    CipherOutputStream cos = new CipherOutputStream(fos, cipher);

    int i;
    while ((i = fis.read(block)) != -1) {
        cos.write(block, 0, i);
    }
    cos.close();

    // Decrypt

    String cleartextAgainFile = "cleartextAgainECIES.txt";

    cipher.init(Cipher.DECRYPT_MODE, privKey, iesParams);

    fis = new FileInputStream(ciphertextFile);
    CipherInputStream cis = new CipherInputStream(fis, cipher);
    fos = new FileOutputStream(cleartextAgainFile);

    while ((i = cis.read(block)) != -1) {
        fos.write(block, 0, i);
    }
    fos.close();
    }

}

任何人都可以帮助我吗?我正在使用JDK版本1.7.0_25。

1 个答案:

答案 0 :(得分:2)

在查看相同的示例时,我遇到了同样的问题。我用answer解决了这个问题。

根本原因:

默认JDK附带的密钥大小限制 - 将其限制为128.如果您的安全策略使用的密钥大小大于此值,则抛出异常。

解决方案:

您需要使用Java Cryptography Extension(JCE)Unlimited Strength Jurisdiction Policy Files修补JDK。

Instructions on how to download JCE Policy files

src:java.security.InvalidKeyException: Illegal key size or default parameters