InvalidKeyException:无法识别密钥规范

时间:2014-07-17 18:20:00

标签: java linux bouncycastle pgp

我得到了

  

InvalidKeyException:非法密钥大小或默认参数

尝试运行已部署WAR的Web应用程序时。我在Linux环境中托管Tomcat。我已经将两个UnlimitedJCEPolicy文件放入目标/usr/lib/jvm/java-1.7.0-openjdk-1.7.0.55.x86_64/jre/lib/security,似乎错误仍然存​​在。注意,这只是在我在linux环境中运行时抛出的。在本地,它工作正常。这是我的代码:

public static final void decryptFile(File inputFile, File outputFile) throws 
IOException, PGPException {
    // Add Bouncy Castle provider
    Security.addProvider(new BouncyCastleProvider());

    // Grab secret key that's in folder with AE classes
    Resource resource = new ClassPathResource(Env.getSecretKeyAE());
    log.debug("Resource: " + Env.getSecretKeyAE());
    File keyFileName = resource.getFile();
    log.debug("Key File Name: " + keyFileName);
    // Decryption password
    String pass = "pass";
    char[] passwd = pass.toCharArray();

    // Read files into streams
    log.info("Reading files into streams");
    InputStream keyIn = new BufferedInputStream(new FileInputStream(keyFileName));
    InputStream in = PGPUtil.getDecoderStream(new BufferedInputStream(new 
FileInputStream(inputFile)));

    // I don't even know what these do
    PGPObjectFactory pgpObjFactory = new PGPObjectFactory(in);
    PGPEncryptedDataList pgpEncryptedDataList = null;

    Object o = pgpObjFactory.nextObject();
    log.info("Checking instance of PGPEncryptedDataList");
    if (o instanceof PGPEncryptedDataList) {
        pgpEncryptedDataList = (PGPEncryptedDataList)o;
    }
    else {
        pgpEncryptedDataList = (PGPEncryptedDataList)pgpObjFactory.nextObject();
    }

    // This will be the PGPPrivateKey we use to decrypt
    log.info("Initializing secret key");
    PGPPrivateKey secretKey = null;
    PGPPublicKeyEncryptedData publicKeyEncryptedData = null;
    PGPSecretKeyRingCollection pgpSecretKeyRingCollection = new    
PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn));

    // This iterates the key file as if it has many keys, this file has only one
    // This is the only way I could find to construct a PGPPrivateKey
    log.info("Iterating through key file");
    Iterator<?> it = pgpEncryptedDataList.getEncryptedDataObjects();
    while(it.hasNext() && secretKey == null) {
        publicKeyEncryptedData = (PGPPublicKeyEncryptedData) it.next();
        PGPSecretKey pgpSecKey = 
pgpSecretKeyRingCollection.getSecretKey(publicKeyEncryptedData.getKeyID());

        if (pgpSecKey != null) {
            Provider provider = Security.getProvider("BC");
            secretKey = pgpSecKey.extractPrivateKey(new   

JcePBESecretKeyDecryptorBuilder(new  
JcaPGPDigestCalculatorProviderBuilder().setProvider(provider)
.build()).setProvider(provider).build(passwd));
           }
    }
    log.info("PGPPrivateKey has been constructed");
    if (secretKey == null) {
        throw new IllegalArgumentException("secret key for message not found.");
    }
    log.info("Secret Key found!");

    if(publicKeyEncryptedData == null) {
        throw new NullPointerException("cannot continue with null public key encryption 
data.");
    }
    log.info("Public Key Encrypted Data found!");

    // More stuff I don't fully understand, I think this is just standard way to   
decrypt files once the above is all set up
    log.info("Starting actual decryption");
    //get data stream where our publicKeyDataDecrypterFactory sets ours provider to BC 
and we build our secretKey
    //secretkey is our PGPPrivateKey

    log.info("start");

    //=====================================================================
    //ERROR IS OCCURRING HERE
    InputStream clear = publicKeyEncryptedData.getDataStream(new  
JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(secretKey));
    log.info("1");
    PGPObjectFactory plainFact = new PGPObjectFactory(clear);
    log.info("2");
    PGPCompressedData compressedData = (PGPCompressedData)plainFact.nextObject();
    log.info("3");
    InputStream compressedStream = new 
BufferedInputStream(compressedData.getDataStream());
    log.info("4");
    PGPObjectFactory pgpFact = new PGPObjectFactory(compressedStream);
    log.info("5");
    Object message = pgpFact.nextObject();
    log.info("6");

    if (message instanceof PGPLiteralData) {
        log.info("Our message is an instance of PGP Literal Data.");
        PGPLiteralData literalData = (PGPLiteralData)message;
        InputStream literalDataInputStream = literalData.getInputStream();
        OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile));
        Streams.pipeAll(literalDataInputStream, out);
        out.close();
    }
    else if (message instanceof PGPOnePassSignatureList) {
        log.error("encrypted message contains a signed message - not literal data.");
        throw new PGPException("encrypted message contains a signed message - not  

literal data.");
    }
    else {
        log.error("message is not a simple encrypted file - type unknown.");
        throw new PGPException("message is not a simple encrypted file - type  
unknown.");
    }
    log.info("Checking if public key encrypted data is integrity protected");
    if (publicKeyEncryptedData.isIntegrityProtected()) {
        if (!publicKeyEncryptedData.verify()) {
            throw new PGPException("message failed integrity check");
        }
    }

    keyIn.close();
    in.close();
}

使用日志,我能够发现错误发生在

InputStream clear = publicKeyEncryptedData.getDataStream(new  
JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(secretKey));

但我不知道为什么。就像我说的,我已经适当地放置了JCEUnlimited文件,但仍然会出现错误。

编辑我修正了非法的密钥大小问题,但现在我的“密钥规范无法识别”

编辑更多详细说明错误“密钥规范无法识别”: 正如我所说,非法密钥大小已经消失,但“密钥规范未被识别”似乎仍然是一个问题。奇怪的是我的encryptFile方法工作得很好,但是decryptFile会抛出错误。我不完全确定为什么。在我离开工作之前,我又测试了一次,似乎没有抛出错误。我几乎看起来这个错误是随机发生的,具体取决于对tomcat的WAR部署。如果我部署我的WAR,错误在某些时候不会发生,但是如果我取消部署并使用更新的WAR文件重新部署,则会引发错误。我不知道造成这种情况的原因是什么,基于研究的人也不知道。显然这曾经是1.5之前的Bouncy Castle中的一个bug,但1.5是我正在运行的版本,所以这不是问题所在。如果我找到任何可以修复此错误的内容,我会发布。

3 个答案:

答案 0 :(得分:2)

要解决:

  

java.security.spec.InvalidKeySpecException:无法识别密钥规范

修改安全提供程序:

sudo nano $JAVA_HOME/jre/lib/security/java.security

添加安全提供程序:

security.provider.10=org.bouncycastle.jce.provider.BouncyCastleProvider

bcprov-jdk15on-1.54.jar复制到:

$JAVA_HOME/jre/lib/ext/bcprov-jdk15on-1.54.jar

重启Tomcat。

答案 1 :(得分:0)

if (o instanceof PGPEncryptedDataList) {
        pgpEncryptedDataList = (PGPEncryptedDataList)o;

如果o已经是PGPEncryptedDataList的一个实例,为什么要将它转换为PGPEncryptedDataLIST?

我对你所做的事情的具体细节不够了解,所以我想我会提供一些通用的代码分析。对不起,我无法提供更多帮助。

答案 2 :(得分:0)

为了防止错误“非法密钥大小或默认参数”,我只需将UnlimitedJCEPolicy文件放在我的工作java目录/opt/jre1.7.0_60/lib/security中。将文件放在那里并重新部署我的war文件后,我再也没有遇到过这个问题。

为了防止“密钥规范无法识别”错误,我必须在重新部署WAR文件时重新启动我的tomcat服务器。