2014-12-19 85 views
0

我對這方面非常陌生。我試圖在Java中開發一個簡單的PCKS#7加密/解密函數。 加密還沒有簽名,我只是想測試加密/解密(密鑰來自密鑰庫)Java中的PKCS#7解密代碼

以下是我的加密代碼。

private static byte[] encryptData() throws Exception { 

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); 
    FileInputStream fIn = new FileInputStream(_keyStorePath); 
    KeyStore keystore = KeyStore.getInstance("JKS"); 
    keystore.load(fIn, _password); 
    Certificate cert = keystore.getCertificate("abc"); 
    fIn.close(); 

    // set up the generator 
    CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator(); 

    gen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator((X509Certificate) cert).setProvider("BC")); 

    // create the enveloped-data object 
    CMSProcessable data = new CMSProcessableByteArray("Hello World!".getBytes()); 
    CMSEnvelopedData enveloped = gen.generate((CMSTypedData) data,new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider("BC").build()); 
    return enveloped.getEncoded(); 
} 

如何編碼一個非常簡單的解密函數(無驗證簽名)來解密我的文件?

我在網上做了一些調查,其中的1個樣本代碼我google是`RecipientId recId = new RecipientId();

recId.setSerialNumber(cert.getSerialNumber()); 
    recId.setIssuer(cert.getIssuerX500Principal().getEncoded()); 

    RecipientInformationStore recipients = enveloped.getRecipientInfos(); 
    RecipientInformation recipient = recipients.get(recId); 

    byte[] recData = recipient.getContent(key, "BC");` 

但是,「RecipientId recId = new RecipientId();」沒有工作,錯誤信息:無法實例化類型收件人ID

非常感謝。

回答

0

我認爲新的API有一些變化。

下面應該是正確的,

X509Certificate cert9 = (X509Certificate) keystore.getCertificate("abc"); 
    KeyTransRecipientId recId = new JceKeyTransRecipientId(cert9.getIssuerX500Principal(), cert9.getSerialNumber());