使用BouncyCastle不推荐的方法进行paypal按钮加密的Java代码-如何修复?

使用BouncyCastle不推荐的方法进行paypal按钮加密的Java代码-如何修复?,java,encryption,paypal,bouncycastle,Java,Encryption,Paypal,Bouncycastle,我一直在努力获取工作代码、好的示例,最重要的是,关于如何使用Paypal的Java SDK加密网站支付的好文档。我已经向Paypal寻求帮助(发布在他们的论坛上,联系支持人员),但到目前为止还没有得到任何帮助 我去下载了Paypal Java SDK。在zip中,有一个ReadMe.txt文件,其中包含安装说明。说明很简单 我去了Bouncy Castle的网站——下载了以下JAR的最新版本: bcmail-jdk16-146.jar bcpg-jdk16-146.jar bcprov-jdk1

我一直在努力获取工作代码、好的示例,最重要的是,关于如何使用Paypal的Java SDK加密网站支付的好文档。我已经向Paypal寻求帮助(发布在他们的论坛上,联系支持人员),但到目前为止还没有得到任何帮助

我去下载了Paypal Java SDK。在zip中,有一个ReadMe.txt文件,其中包含安装说明。说明很简单

我去了Bouncy Castle的网站——下载了以下JAR的最新版本:
bcmail-jdk16-146.jar
bcpg-jdk16-146.jar
bcprov-jdk16-146.jar
bctest-jdk16-146.jar

然后我去下载Java加密扩展(JCE)无限强度管辖权策略文件

我将所有JAR放在适当的文件夹中,更新了类路径,然后尝试编译Paypal java SDK附带的ClientSide.java类

编译器告诉我存在不推荐使用的类,并在使用-Xlint重新编译后向我显示以下错误

.\palmb\servlets\paypal\ClientSide.java:98: warning: [deprecation] addSigner(jav
a.security.PrivateKey,java.security.cert.X509Certi​ficate,java.lang.String) in org.bouncycastle.cms.CMSSignedDataGenerator has been deprecated
                signedGenerator.addSigner( privateKey, certificate, CMSSignedDataGenerator.DIGEST_SHA1 );
                               ^
.\palmb\servlets\paypal\ClientSide.java:101: warning: [unchecked] unchecked call
 to add(E) as a member of the raw type java.util.ArrayList
                certList.add(certificate);
                            ^
.\palmb\servlets\paypal\ClientSide.java:103: warning: [deprecation] addCertificatesAndCRLs(java.security.cert.CertStor​e) in org.bouncycastle.cms.CMSSignedGenerator has been deprecated
                signedGenerator.addCertificatesAndCRLs(certStore);
                               ^
.\palmb\servlets\paypal\ClientSide.java:110: warning: [deprecation] generate(org.bouncycastle.cms.CMSProcessable,boole​an,java.lang.String) in org.bouncycastle.cms.CMSSignedDataGenerator has been deprecated
                CMSSignedData signedData = signedGenerator.generate(cmsByteArray, true, "BC");
                                                  ​        ^
.\palmb\servlets\paypal\ClientSide.java:115: warning: [deprecation] addKeyTransRecipient(java.security.cert.X509Certif​icate) in org.bouncycastle.cms.CMSEnvelopedGenerator has been deprecated  envGenerator.addKeyTransRecipient(payPalCert);
                            ^
.\palmb\servlets\paypal\ClientSide.java:116: warning: [deprecation] generate(org.bouncycastle.cms.CMSProcessable,java.​lang.String,java.lang.String) in org.bouncycastle.cms.CMSEnvelopedDataGenerator has been deprecated
                CMSEnvelopedData envData = envGenerator.generate( new CMSProcessableByteArray(signed),
                                                  ​     ^
6 warnings
我的机器上运行着Java1.6。我对Paypal感到失望,因为他们没有提供足够的、易于理解的文档,而且,对于需要开箱即用设置的人来说,他们的代码不起作用

我去了bouncycastle的网站(www.bouncycastle.org),简单地看了一下文档(http://www.bouncycastle.org/documentation.html)对于1.6版-但我真的不知道如何使用这些方法来替换不推荐的方法

有没有人有使用这个Java Paypal代码的经验?或者体验过BouncyCastle及其代码?如果是这样,我非常需要帮助


客户端类
无法让Paypal提供的类正常工作,因此决定尝试使用Paypal按钮API。事实证明,这是最好的办法。我仍然可以使用Java,让Paypal负责加密按钮。一旦我把东西正确地编码好,这就变成了一个简单的过程


要查看有关Paypal Button API的信息,请单击。

由于没有将JCE文件安装在正确的位置,因此出现了非法密钥大小错误。您的系统上可能有多个JRE

至于回答你关于弃用函数的问题。。。我为PayPal的示例代码提供了以下替换函数,这些函数非常有效(基于):

private最终静态字符串getButtonEncryptionValue(字符串commandData、字符串keystRepath、,
字符串keystorePassword,boolean sandbox)抛出IOException,certificateeexception,KeyStoreException,
不可恢复的KeyException、InvalidAlgorithmParameterException、NoSuchAlgorithmException、,
无此ProviderException、CertStoreException、CMSExException、Operator CreationException{
addProvider(新org.bouncycastle.jce.provider.BouncyCastleProvider());
commandData=commandData.replace(',','\n');
CertificateFactory cf=CertificateFactory.getInstance(“X509”、“BC”);
//读取私钥
KeyStore ks=KeyStore.getInstance(“PKCS12”、“BC”);
load(新文件输入流(keystrepath),keystrepassword.tocharray());
字符串keyalis=null;
枚举别名=ks.alias();
while(别名.hasMoreElements()){
keyAlias=(字符串)别名。nextElement();
}
PrivateKey PrivateKey=(PrivateKey)ks.getKey(keyalis,keystrepassword.toCharArray());
//阅读证书
X509Certificate=(X509Certificate)cf.generateCertificate(ApplicationProxyService.class
.getResourceAsStream(“/myCompanyPublicCert.pem.cer”);
//阅读贝宝证书
X509Certificate payPalCert=(X509Certificate)cf.generateCertificate(ApplicationProxyService.class
.getResourceAsStream(“/paypalPublicert”+(sandbox?”-sandbox:“)+”.pem.cer”);
//创建数据
//System.out.println(commandData);
byte[]data=commandData.getBytes();
//使用我的仅签名密钥对对数据进行签名
CMSSignedDataGenerator signedGenerator=新的CMSSignedDataGenerator();
List certList=new ArrayList();
证书列表。添加(证书);
//不推荐使用:Store certStore=certStore.getInstance(“Collection”,新的CollectionCertStoreParameters(certList));
Store certStore=新的JcaCertStore(certList);
//不推荐使用:signedGenerator.addCertificatesAndCRLs(certStore);
signedGenerator.addCertificates(certStore);
//不推荐使用:signedGenerator.addSigner(私钥、证书、CMSSignedDataGenerator.DIGEST_SHA1);
ContentSigner sha1Signer=new JcaContentSignerBuilder(“SHA1withRSA”).setProvider(“BC”).build(privateKey);
signedGenerator.addSignerInfoGenerator(新JcaSignerInfoGeneratorBuilder(
新的JcaDigestCalculatorProviderBuilder().setProvider(“BC”).build()).build(sha1Signer,certificate));
CMSProcessableByteArray cmsByteArray=新的CMSProcessableByteArray(数据);
ByteArrayOutputStream bas=新的ByteArrayOutputStream();
cmsbyteraray.write(baos);
LOGGER.debug(“CMSProcessableByteArray包含[“+baos.toString()+”]”);
//不推荐使用:CMSSignedData signedData=signedGenerator.generate(cmsbyterarray,true,“BC”);
CMSSignedData signedData=signedGenerator.generate(cmsByteArray,true);
byte[]signed=signedData.getEncoded();
CMSEnDevelopedDataGenerator envGenerator=新的CMSEnDevelopedDataGenerator();
//不推荐使用:envGenerator.addKeyTransRecipient(payPalCert);
addRecipientInfoGenerator(新的JceKeyTransRecipientInfoGenerator(payPalCert).setProvider(“BC”);
//不推荐使用:CMSEnDevelopedData envData=envGenerator.generate(新CMSProcessableByteArray(已签名),
//CMSEnDevelopedDataGenerator.DES_EDE3_CBC,“BC”);
CMSEnDevelopedData envData=envGenerator.generate(新CMSProcessableByteArray(已签名),
新JceCMSContentEncrypt
package palmb.servlets.paypal;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertStore;
import java.security.cert.CertStoreException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.CollectionCertStoreParameters;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Enumeration;

import org.bouncycastle.cms.CMSEnvelopedData;
import org.bouncycastle.cms.CMSEnvelopedDataGenerator;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.openssl.PEMReader;
import org.bouncycastle.util.encoders.Base64;

/**
 */
public class ClientSide 
{
    private String  keyPath;
    private String  certPath;
    private String  paypalCertPath;
    private String  keyPass;

    public ClientSide( String keyPath, String certPath, String paypalCertPath, String keyPass )
    {
        this.keyPath = keyPath;
        this.certPath = certPath;
        this.paypalCertPath = paypalCertPath;
        this.keyPass = keyPass;
    }   

    public String getButtonEncryptionValue(String _data, String _privateKeyPath, String _certPath, String _payPalCertPath,
                                            String _keyPass) throws IOException,CertificateException,KeyStoreException,
                                            UnrecoverableKeyException,InvalidAlgorithmParameterException,NoSuchAlgorithmException,
                                            NoSuchProviderException,CertStoreException,CMSException {
        _data = _data.replace(',', '\n');
        CertificateFactory cf = CertificateFactory.getInstance("X509", "BC");

        // Read the Private Key
        KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
        ks.load( new FileInputStream(_privateKeyPath), _keyPass.toCharArray() );

        String keyAlias = null;
        Enumeration aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            keyAlias = (String) aliases.nextElement();
        }

        PrivateKey privateKey = (PrivateKey) ks.getKey( keyAlias, _keyPass.toCharArray() );

        // Read the Certificate
        X509Certificate certificate = (X509Certificate) cf.generateCertificate( new FileInputStream(_certPath) );

        // Read the PayPal Cert
        X509Certificate payPalCert = (X509Certificate) cf.generateCertificate( new FileInputStream(_payPalCertPath) );

        // Create the Data
        byte[] data = _data.getBytes();

        // Sign the Data with my signing only key pair
        CMSSignedDataGenerator signedGenerator = new CMSSignedDataGenerator();

        signedGenerator.addSigner( privateKey, certificate, CMSSignedDataGenerator.DIGEST_SHA1 );

        ArrayList certList = new ArrayList();
        certList.add(certificate);
        CertStore certStore = CertStore.getInstance( "Collection", new CollectionCertStoreParameters(certList) );
        signedGenerator.addCertificatesAndCRLs(certStore);

        CMSProcessableByteArray cmsByteArray = new CMSProcessableByteArray(data);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        cmsByteArray.write(baos);
        System.out.println( "CMSProcessableByteArray contains [" + baos.toString() + "]" );

        CMSSignedData signedData = signedGenerator.generate(cmsByteArray, true, "BC");

        byte[] signed = signedData.getEncoded();

        CMSEnvelopedDataGenerator envGenerator = new CMSEnvelopedDataGenerator();
        envGenerator.addKeyTransRecipient(payPalCert);
        CMSEnvelopedData envData = envGenerator.generate( new CMSProcessableByteArray(signed),
                CMSEnvelopedDataGenerator.DES_EDE3_CBC, "BC" );

        byte[] pkcs7Bytes = envData.getEncoded();


        return new String( DERtoPEM(pkcs7Bytes, "PKCS7") );

    }

    public static byte[] DERtoPEM(byte[] bytes, String headfoot) 
    {
        ByteArrayOutputStream pemStream = new ByteArrayOutputStream();
        PrintWriter writer = new PrintWriter(pemStream);

        byte[] stringBytes = Base64.encode(bytes);

        System.out.println("Converting " + stringBytes.length + " bytes");

        String encoded = new String(stringBytes);

        if (headfoot != null) {
            writer.print("-----BEGIN " + headfoot + "-----\n");
        }

        // write 64 chars per line till done
        int i = 0;
        while ((i + 1) * 64 < encoded.length()) {
            writer.print(encoded.substring(i * 64, (i + 1) * 64));
            writer.print("\n");
            i++;
        }
        if (encoded.length() % 64 != 0) {
            writer.print(encoded.substring(i * 64)); // write remainder
            writer.print("\n");
        }
        if (headfoot != null) {
            writer.print("-----END " + headfoot + "-----\n");
        }
        writer.flush();
        return pemStream.toByteArray();
    }

}
package palmb.servlets.paypal;

//import com.paypal.crypto.sample.*;

import palmb.servlets.paypal.ClientSide;

import java.io.*;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertStoreException;
import java.security.cert.CertificateException;
import org.bouncycastle.cms.CMSException;

/**
 */
public class ButtonEncryption {


    //path to public cert
    private static String certPath = "C:/jakarta-tomcat/webapps/PlanB/Certs/public-cert.pem";

    //path to private key in PKCS12 format
    private static String keyPath = "C:/jakarta-tomcat/webapps/PlanB/Certs/my_pkcs12.p12";

    //path to Paypal's public cert
    private static String paypalCertPath = "C:/jakarta-tomcat/webapps/PlanB/Certs/paypal_cert_pem.txt";

    //private key password
    private static String keyPass = "password"; //will be replaced with actual password when compiled and executed

    //the button command, properties/parameters
    private static String cmdText = "cmd=_xclick\nbusiness=buyer@hotmail.com\nitem_name=vase\nitemprice=25.00";  //cmd=_xclick,business=sample@paypal.com,amount=1.00,currency_code=USD

    //output file for form code
    private static String output = "test.html";


    public static void main(String[] args) 
    {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); 


        String stage = "sandbox";

        try 
        {
            ClientSide client_side = new ClientSide( keyPath, certPath, paypalCertPath, keyPass );

            String result = client_side.getButtonEncryptionValue( cmdText, keyPath, certPath, paypalCertPath, keyPass );

            File outputFile = new File( output );
            if ( outputFile.exists() )
                outputFile.delete();

            if ( result != null && result != "")
            {
                try {        
                    OutputStream fout= new FileOutputStream( output );
                    OutputStream bout= new BufferedOutputStream(fout);
                    OutputStreamWriter out = new OutputStreamWriter(bout, "US-ASCII");

                    out.write( "<form action=\"https://www." );
                    out.write( stage );
                    out.write( "paypal.com/cgi-bin/webscr\" method=\"post\">" );  
                    out.write( "<input type=\"hidden\" name=\"cmd\" value=\"_s-xclick\">" );  ;
                    out.write( "<input type=\"image\" src=\"https://www." );
                    out.write( stage );
                    out.write( "paypal.com/en_US/i/btn/x-click-but23.gif\" border=\"0\" name=\"submit\" " );
                    out.write( "alt=\"Make payments with PayPal - it's fast, free and secure!\">" );
                    out.write( "<input type=\"hidden\" name=\"encrypted\" value=\"" );
                    out.write( result );
                    out.write( "\">" );
                    out.write( "</form>");

                    out.flush();  // Don't forget to flush!
                    out.close();
                  }
                  catch (UnsupportedEncodingException e) {
                    System.out.println(
                     "This VM does not support the ASCII character set."
                    );
                  }
                  catch (IOException e) {
                    System.out.println(e.getMessage());        
                  }
            }
        } 
        catch (NoSuchAlgorithmException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (NoSuchProviderException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (CMSException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (CertificateException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (KeyStoreException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (UnrecoverableKeyException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (InvalidAlgorithmParameterException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (CertStoreException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
C:\jakarta-tomcat\webapps\PlanB\WEB-INF\classes>java palmb.servlets.paypal.ButtonEncryption
java.io.IOException: exception decrypting data - java.security.InvalidKeyException: Illegal key size
        at org.bouncycastle.jce.provider.JDKPKCS12KeyStore.cryptData(Unknown Source)
        at org.bouncycastle.jce.provider.JDKPKCS12KeyStore.engineLoad(Unknown Source)
        at java.security.KeyStore.load(Unknown Source)
        at palmb.servlets.paypal.ClientSide.getButtonEncryptionValue(ClientSide.
java:63)
        at palmb.servlets.paypal.ButtonEncryption.main(ButtonEncryption.java:81)
private final static String getButtonEncryptionValue(String commandData, String keystorePath,
        String keystorePassword, boolean sandbox) throws IOException, CertificateException, KeyStoreException,
        UnrecoverableKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
        NoSuchProviderException, CertStoreException, CMSException, OperatorCreationException {

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    commandData = commandData.replace(',', '\n');
    CertificateFactory cf = CertificateFactory.getInstance("X509", "BC");

    // Read the Private Key
    KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
    ks.load(new FileInputStream(keystorePath), keystorePassword.toCharArray());

    String keyAlias = null;
    Enumeration<String> aliases = ks.aliases();
    while (aliases.hasMoreElements()) {
        keyAlias = (String) aliases.nextElement();
    }

    PrivateKey privateKey = (PrivateKey) ks.getKey(keyAlias, keystorePassword.toCharArray());

    // Read the Certificate
    X509Certificate certificate = (X509Certificate) cf.generateCertificate(ApplicationProxyService.class
            .getResourceAsStream("/myCompanyPublicCert.pem.cer"));

    // Read the PayPal Cert
    X509Certificate payPalCert = (X509Certificate) cf.generateCertificate(ApplicationProxyService.class
            .getResourceAsStream("/paypalPublicCert" + (sandbox ? "-sandbox" : "") + ".pem.cer"));

    // Create the Data
    // System.out.println(commandData);
    byte[] data = commandData.getBytes();

    // Sign the Data with my signing only key pair
    CMSSignedDataGenerator signedGenerator = new CMSSignedDataGenerator();

    List<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(certificate);

    //deprecated: Store certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList));
    Store certStore = new JcaCertStore(certList);

    // deprecated: signedGenerator.addCertificatesAndCRLs(certStore);
    signedGenerator.addCertificates(certStore);

    // deprecated: signedGenerator.addSigner(privateKey, certificate, CMSSignedDataGenerator.DIGEST_SHA1);

    ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(privateKey);
    signedGenerator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, certificate));

    CMSProcessableByteArray cmsByteArray = new CMSProcessableByteArray(data);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    cmsByteArray.write(baos);
    LOGGER.debug("CMSProcessableByteArray contains [" + baos.toString() + "]");

    // deprecated: CMSSignedData signedData = signedGenerator.generate(cmsByteArray, true, "BC");
    CMSSignedData signedData = signedGenerator.generate(cmsByteArray, true);

    byte[] signed = signedData.getEncoded();

    CMSEnvelopedDataGenerator envGenerator = new CMSEnvelopedDataGenerator();

    // deprecated: envGenerator.addKeyTransRecipient(payPalCert);
    envGenerator.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(payPalCert).setProvider("BC"));

    // deprecated: CMSEnvelopedData envData = envGenerator.generate(new CMSProcessableByteArray(signed),
    // CMSEnvelopedDataGenerator.DES_EDE3_CBC, "BC");
    CMSEnvelopedData envData = envGenerator.generate(new CMSProcessableByteArray(signed),
            new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider("BC").build());

    byte[] pkcs7Bytes = envData.getEncoded();

    return new String(DERtoPEM(pkcs7Bytes, "PKCS7"));

}
private static final byte[] DERtoPEM(byte[] bytes, String headfoot) {

    byte[] stringBytes = Base64.encode(bytes);

    // System.out.println("Converting " + stringBytes.length + " bytes");
    StringBuilder sb = new StringBuilder();
    sb.append("-----BEGIN " + headfoot + "-----\n");
    String encoded = new String(stringBytes);
    // write 64 chars per line till done
    int i = 0;
    while ((i + 1) * 64 < encoded.length()) {
        sb.append(encoded.substring(i * 64, (i + 1) * 64));
        sb.append("\n");
        i++;
    }
    // if (encoded.length() % 64 != 0) { //FIXME (fixed via next line): this is a BUG that drops remaining data if data.length==64!
    String remainder = encoded.substring(i * 64);
    if (StringUtils.isNotEmpty(remainder)) {
        sb.append(remainder); // write remainder
        sb.append("\n");
    }
    sb.append("-----END " + headfoot + "-----\n");
    return sb.toString().getBytes();

}