证书加密解密

开始以为可以对文件进行加密,使用后发现不支持文件加密,其中证书类型是浏览器支持的XX.p12证书,现在正在研究Itext使用证书签名加密pdf文件,找了很多资料,这方面的资料实在是太少了。

/**
* 证书加密解密(不能对文件加密,这个只能对一小段字符加密解密)
* @param certPath 证书路径
* @param password 证书密码
*/
private static void encrypAndDecryption(String certPath,String certPassWord,String encryptData){
//此类表示密钥和证书的存储设施
KeyStore keyStore;
String alias = "";
//String testEncrypt = "certificate encrypt decryption";
System.out.println("加密前: " + encryptData);
try {
FileInputStream is = new FileInputStream(certPath);
//得到KeyStore实例
keyStore = KeyStore.getInstance("PKCS12");
//从指定的输入流中加载此 KeyStore。
keyStore.load(is, certPassWord.toCharArray());
is.close();
//获取keyStore别名
alias = (String)keyStore.aliases().nextElement();
Certificate cert = keyStore.getCertificate(alias);
//根据给定别名获取相关的私钥
PrivateKey priKey = (PrivateKey)keyStore.getKey(alias, certPassWord.toCharArray());
//获取证书的公钥
PublicKey pubKey = cert.getPublicKey();
//获取Cipher的实例 getInstance(算法/模式/填充)或getInstance("算法")
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
//公钥初始化Cipher 公钥加密
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
//加密
byte [] encodeEncryp = cipher.doFinal(encryptData.getBytes());
System.out.println("加密后: " + new String(encodeEncryp));
//encodeEncryp = cipher.doFinal(getFileContentToByte(encrypFile));
//私钥初始化Cipher 私钥解密
cipher.init(Cipher.DECRYPT_MODE, priKey);
//解密
byte [] encodeDecryption = cipher.doFinal(encodeEncryp);

String content = new String(encodeDecryption);
System.out.println("解密后: " + content + "length: " + content.length());
} catch (Exception e) {
e.printStackTrace();
}
}

下面有个测试用的certificate.
阅读更多

关于ibm-jdk下的证书加密解密问题

12-03

现在需要java实现使用.pfx证书对字符串进行加密,最后用base64编码形成密文。rn 在Sun-Jdk下即使用SUN提供的jsse.jar包,已经实现此功能。rn[code=Java]rnimport java.io.ByteArrayInputStream;rnimport java.io.ByteArrayOutputStream;rnimport java.io.FileInputStream;rnimport java.io.IOException;rnimport java.io.InputStream;rnimport java.security.GeneralSecurityException;rnimport java.security.InvalidKeyException;rnimport java.security.KeyStore;rnimport java.security.NoSuchAlgorithmException;rnimport java.security.NoSuchProviderException;rnimport java.security.PrivateKey;rnimport java.security.Signature;rnimport java.security.SignatureException;rnimport java.security.cert.Certificate;rnimport java.security.cert.CertificateException;rnimport java.security.cert.CertificateFactory;rnimport java.security.cert.X509Certificate;rnimport java.util.Enumeration;rnrnimport javax.security.auth.x500.X500Principal;rnrnimport sun.misc.BASE64Decoder;rnimport sun.security.pkcs.ContentInfo;rnimport sun.security.pkcs.PKCS7;rnimport sun.security.pkcs.SignerInfo;rnimport sun.security.x509.AlgorithmId;rnimport sun.security.x509.X500Name;rnrnimport com.sun.org.apache.xerces.internal.impl.dv.util.Base64;rnrn/**rn * PKCS7Tool.java pkcs7格式签名工具rn * rn * @version 1.0rn * @author SUNY Written Date: 2008-9-23rn */rnpublic class _PKCS7Tool rnrn /** 签名 */rn private static final int SIGNER = 1;rn /** 验证 */rn private static final int VERIFIER = 2;rn /** 用途 */rn private int mode = 0;rn /** 摘要算法 */rn private String digestAlgorithm = "SHA1";rn /** 签名算法 */rn private String signingAlgorithm = "SHA1withRSA";rn /** 签名证书链 */rn private X509Certificate[] certificates = null;rn /** 签名私钥 */rn private PrivateKey privateKey = null;rn /** 根证书 */rn private Certificate rootCertificate = null;rnrn /**rn * 私有构造方法rn */rn private _PKCS7Tool(int mode) rn this.mode = mode;rn rnrn /**rn * 取得签名工具 加载证书库, 取得签名证书链和私钥rn * rn * @param keyStorePathrn * 证书库路径rn * @param keyStorePasswordrn * 证书库口令rn * @throws GeneralSecurityExceptionrn * @throws IOExceptionrn */rn public static _PKCS7Tool getSigner(String keyStorePath,rn String keyStorePassword, String keyPassword)rn throws GeneralSecurityException, IOException rn // 加载证书库rn KeyStore keyStore = null;rn if (keyStorePath.toLowerCase().endsWith(".pfx"))rn keyStore = KeyStore.getInstance("PKCS12");rn elsern keyStore = KeyStore.getInstance("JKS");rn FileInputStream fis = null;rn try rn fis = new FileInputStream(keyStorePath);rn keyStore.load(fis, keyStorePassword.toCharArray());rn finally rn if (fis != null)rn fis.close();rn rn // 在证书库中找到签名私钥rn Enumeration aliases = keyStore.aliases();rn String keyAlias = null;rn if (aliases != null) rn while (aliases.hasMoreElements()) rn keyAlias = (String) aliases.nextElement();rn Certificate[] certs = keyStore.getCertificateChain(keyAlias);rn if (certs == null || certs.length == 0)rn continue;rn X509Certificate cert = (X509Certificate) certs[0];rn if (matchUsage(cert.getKeyUsage(), 1)) rn try rn cert.checkValidity();rn catch (CertificateException e) rn continue;rn rn break;rn rn rn rn // 没有找到可用签名私钥rn if (keyAlias == null)rn throw new GeneralSecurityException(rn "None certificate for sign in this keystore");rnrn X509Certificate[] certificates = null;rn if (keyStore.isKeyEntry(keyAlias)) rn // 检查证书链rn Certificate[] certs = keyStore.getCertificateChain(keyAlias);rn for (int i = 0; i < certs.length; i++) rn if (!(certs[i] instanceof X509Certificate))rn throw new GeneralSecurityException("Certificate[" + irn + "] in chain '" + keyAliasrn + "' is not a X509Certificate.");rn rn // 转换证书链rn certificates = new X509Certificate[certs.length];rn for (int i = 0; i < certs.length; i++)rn certificates[i] = (X509Certificate) certs[i];rn else if (keyStore.isCertificateEntry(keyAlias)) rn // 只有单张证书rn Certificate cert = keyStore.getCertificate(keyAlias);rn if (cert instanceof X509Certificate) rn certificates = new X509Certificate[] (X509Certificate) cert ;rn rn else rn throw new GeneralSecurityException(keyAliasrn + " is unknown to this keystore");rn rnrn PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias,rn keyPassword.toCharArray());rn // 没有私钥抛异常rn if (privateKey == null) rn throw new GeneralSecurityException(keyAliasrn + " could not be accessed");rn rnrn _PKCS7Tool tool = new _PKCS7Tool(SIGNER);rn tool.certificates = certificates;rn tool.privateKey = privateKey;rn return tool;rn rnrn[/code]rnrn[code=Java]rnrn/**rn * 签名rn * rn * @param datarn * 数据rn * @return signature 签名结果rn * @throws GeneralSecurityExceptionrn * @throws IOExceptionrn * @throws IllegalArgumentExceptionrn */rn public String sign(byte[] data) throws GeneralSecurityException,rn IOException rn if (mode != SIGNER)rn throw new IllegalStateException(rn "call a PKCS7Tool instance not for signature.");rnrn Signature signer = Signature.getInstance(signingAlgorithm);rn signer.initSign(privateKey);rn signer.update(data, 0, data.length);rn byte[] signedAttributes = signer.sign();rnrn ContentInfo contentInfo = null;rnrn contentInfo = new ContentInfo(ContentInfo.DATA_OID, null);rn // 根证书rn X509Certificate x509 = certificates[certificates.length - 1];rn rn // 如果jdk1.5则用以下语句rn java.math.BigInteger serial = x509.getSerialNumber();rn // 签名信息rn SignerInfo si = new SignerInfo(new X500Name(x509.getIssuerDN()rn .getName()), // X500Name, issuerName,rn serial, // x509.getSerialNumber(), BigInteger serial,rn AlgorithmId.get(digestAlgorithm), // AlgorithmId,rn // digestAlgorithmId,rn null, // PKCS9Attributes, authenticatedAttributes,rn new AlgorithmId(AlgorithmId.RSAEncryption_oid), // AlgorithmId,rn // digestEncryptionAlgorithmId,rn signedAttributes, // byte[] encryptedDigest,rn null); // PKCS9Attributes unauthenticatedAttributes) rnrn SignerInfo[] signerInfos = si ;rnrn // 构造PKCS7数据rn AlgorithmId[] digestAlgorithmIds = AlgorithmId.get(digestAlgorithm) ;rn PKCS7 p7 = new PKCS7(digestAlgorithmIds, contentInfo, certificates,rn signerInfos);rnrn ByteArrayOutputStream baout = new ByteArrayOutputStream();rn p7.encodeSignedData(baout);rn // Base64编码rn return Base64.encode(baout.toByteArray());rn rn[/code]rnrn测试方法rn[code=Java]rn public static void main(String[] args) rn String keyStorePath = "D:\\淘宝网.pfx";rn String keyStorePassword = "11111111";rn String keyPassword = "11111111";rn _PKCS7Tool tool = null;rn try rn tool = getSigner(keyStorePath, keyStorePassword, keyPassword);rn catch (GeneralSecurityException e) rn e.printStackTrace();rn catch (IOException e) rn e.printStackTrace();rn rn String plaintext = "123456";rn try rn System.out.println(tool.sign(plaintext.getBytes()));rn catch (Exception e) rn e.printStackTrace();rn rn rnrn[/code]

没有更多推荐了,返回首页