Java的bouncycastle密码库的RSA的加密,解密,类

import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.crypto.generators.*;
import org.bouncycastle.crypto.params.*;
import org.bouncycastle.crypto.*;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.crypto.util.PrivateKeyInfoFactory;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory;
import org.bouncycastle.crypto.engines.*;
import org.bouncycastle.math.*;
import org.bouncycastle.asn1.x509.*;
import org.bouncycastle.x509.*;
import org.bouncycastle.util.*;
import org.bouncycastle.asn1.pkcs.*;
import org.bouncycastle.asn1.*;

import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.*;

/**
 * Created by Administrator on 2018/8/1 0001.
 */
public class b {
    public static void main(String[] args) throws Exception {
        //生成密钥对
        RSAKeyPairGenerator rsaKeyPairGenerator = new RSAKeyPairGenerator();
        RSAKeyGenerationParameters rsaKeyGenerationParameters = new RSAKeyGenerationParameters(BigInteger.valueOf(3), new SecureRandom(), 1024, 25);
        rsaKeyPairGenerator.init(rsaKeyGenerationParameters);//初始化参数
        AsymmetricCipherKeyPair keyPair = rsaKeyPairGenerator.generateKeyPair();

        AsymmetricKeyParameter publicKey = keyPair.getPublic();//公钥
        AsymmetricKeyParameter privateKey = keyPair.getPrivate();//私钥

        SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(publicKey);
        PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.createPrivateKeyInfo(privateKey);

        //变字符串
        ASN1Object asn1ObjectPublic = subjectPublicKeyInfo.toASN1Primitive();
        byte[] publicInfoByte = asn1ObjectPublic.getEncoded();
        ASN1Object asn1ObjectPrivate = privateKeyInfo.toASN1Primitive();
        byte[] privateInfoByte = asn1ObjectPrivate.getEncoded();

        //这里可以将密钥对保存到本地
        final Base64.Encoder encoder64 = Base64.getEncoder();
        System.out.println("PublicKey:\n" +  encoder64.encodeToString(publicInfoByte));
        System.out.println("PrivateKey:\n" + encoder64.encodeToString(privateInfoByte));

        //加密、解密
        ASN1Object pubKeyObj = subjectPublicKeyInfo.toASN1Primitive();//这里也可以从流中读取,从本地导入
        AsymmetricKeyParameter pubKey = PublicKeyFactory.createKey(SubjectPublicKeyInfo.getInstance(pubKeyObj));
        AsymmetricBlockCipher cipher = new RSAEngine();
        cipher.init(true, pubKey);//true表示加密


        final Base64.Decoder decoder64 = Base64.getDecoder();
        //加密
        String data = "成aa功324$$了。。。";
        System.out.println("\n明文:" + data);
        byte[] encryptData = cipher.processBlock(data.getBytes("utf-8")
                , 0, data.getBytes("utf-8").length);
        System.out.println("密文:" + encoder64.encodeToString(encryptData));

        //解密
        AsymmetricKeyParameter priKey = PrivateKeyFactory.createKey(privateInfoByte);
        cipher.init(false, priKey);//false表示解密
        byte[] decriyptData=cipher.processBlock(encryptData, 0, encryptData.length);
        String decryptData = new String(decriyptData,"utf-8");
        System.out.println("解密后数据:" + decryptData);
    }
}

封装未工具类:包含方法:生成密钥对,加密,解密

import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.crypto.generators.*;
import org.bouncycastle.crypto.params.*;
import org.bouncycastle.crypto.*;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.crypto.util.PrivateKeyInfoFactory;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory;
import org.bouncycastle.crypto.engines.*;
import org.bouncycastle.math.*;
import org.bouncycastle.asn1.x509.*;
import org.bouncycastle.x509.*;
import org.bouncycastle.util.*;
import org.bouncycastle.asn1.pkcs.*;
import org.bouncycastle.asn1.*;

import java.io.IOException;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.*;

public class  RSAUtil
{
    public  static  void GenerateKeyPair() throws IOException {
        //生成密钥对
        RSAKeyPairGenerator rsaKeyPairGenerator = new RSAKeyPairGenerator();
        RSAKeyGenerationParameters rsaKeyGenerationParameters = new RSAKeyGenerationParameters(BigInteger.valueOf(3), new SecureRandom(), 1024, 25);
        rsaKeyPairGenerator.init(rsaKeyGenerationParameters);//初始化参数
        AsymmetricCipherKeyPair keyPair = rsaKeyPairGenerator.generateKeyPair();

        AsymmetricKeyParameter publicKey = keyPair.getPublic();//公钥
        AsymmetricKeyParameter privateKey = keyPair.getPrivate();//私钥

        SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(publicKey);
        PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.createPrivateKeyInfo(privateKey);

        //变字符串
        ASN1Object asn1ObjectPublic = subjectPublicKeyInfo.toASN1Primitive();
        byte[] publicInfoByte = asn1ObjectPublic.getEncoded();
        ASN1Object asn1ObjectPrivate = privateKeyInfo.toASN1Primitive();
        byte[] privateInfoByte = asn1ObjectPrivate.getEncoded();

        //这里可以将密钥对保存到本地
        final Base64.Encoder encoder64 = Base64.getEncoder();
        System.out.println("PublicKey:\n" +  encoder64.encodeToString(publicInfoByte));
        System.out.println("PrivateKey:\n" + encoder64.encodeToString(privateInfoByte));
    }

    //加密
    public  static String encryptData(String data) throws IOException, InvalidCipherTextException {
        data=String.valueOf(System.currentTimeMillis())+"::"+data;
        final Base64.Decoder decoder64 = Base64.getDecoder();
        final Base64.Encoder encoder64 = Base64.getEncoder();

        AsymmetricBlockCipher cipher = new RSAEngine();

        //加密
        String publicInfoStr="MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQDNgn9X76T8t0gba+JMe686ynress+0Pd3LH9qqft8ZNC+d6BG3trc3rrn83W+q12pH+YfWiDsTB9jpeTg0EixQX4s9WrPnhOG289nzzwDrmuWMRS9KUSOwq4o3ymKlKnOIz2ncOzOsfLAPnnF7FZAJRZTkyitoYywk5RyIqvLhUwIBAw==";
        byte[] publicInfoBytes=decoder64.decode(publicInfoStr);

        ASN1Object pubKeyObj =ASN1Primitive.fromByteArray(publicInfoBytes); //这里也可以从流中读取,从本地导入
        AsymmetricKeyParameter pubKey = PublicKeyFactory.createKey(SubjectPublicKeyInfo.getInstance(pubKeyObj));

        cipher.init(true, pubKey);//true表示加密
        byte[] encryptDataBytes = cipher.processBlock(data.getBytes("utf-8")
                , 0, data.getBytes("utf-8").length);
        String encryptData=encoder64.encodeToString(encryptDataBytes);
        return  encryptData;
    }
    //解密
    public static String decryptData(String data) throws IOException, InvalidCipherTextException {
        final Base64.Decoder decoder64 = Base64.getDecoder();

        AsymmetricBlockCipher cipher = new RSAEngine();
        byte[] encryptDataBytes=decoder64.decode(data);

        //解密
        String privateInfoStr="MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAM2Cf1fvpPy3SBtr4kx7rzrKet6yz7Q93csf2qp+3xk0L53oEbe2tzeuufzdb6rXakf5h9aIOxMH2Ol5ODQSLFBfiz1as+eE4bbz2fPPAOua5YxFL0pRI7CrijfKYqUqc4jPadw7M6x8sA++k9y/5xxUlLt4H76atnp5z3p0e/3o9RyPnC/7r+Ra0gyv5fD7es1hct8MF6ITu9JEmMOW0ETzx7eXuCUt4O6DqA1vHacRId1EsTUUemcHrNba/PudtxriuzfNA6aMZ4UtaFbf0nFyn4nLAkEA/3dsusv0Xd70cwBa5wM69GgsLZWvYxevZCZ552b1LpjYsAk5iy95SspJbM6S10k6gbTazY5+KucoItiDekxQqwJBAM3wXYJON8AdnR6hMXpSHULpKFLINSiP7SC3Q0lI5BTQ4ICpCCSA8OlqTMUQP+ot+xBakCoBonQoenKIWwS3QfkCQQCqT53R3U2T6fhMqudErNH4RXLJDnTsunTtbvvvmfjJuzsgBiZcylDchtud3wyPhicBIzyJCalx73AXOwJRiDXHAkEAiUrpAYl6gBO+FGt2UYwTgfDFjIV4xbVIwHos24XtYzXrAHCwGFX18PGIg2AqnB6nYDxgHAEW+Br8TFrnWHor+wJBAMMkThUMH16vOYbSHaKMh518UX/pJ3Y4uSHjIe0DDRtKiYy5Z9QtoA/nae5jBfDsp2o5wuzfto0p3BH0i9D+AVQ=";
        byte[] privateInfoByte=decoder64.decode(privateInfoStr);
        AsymmetricKeyParameter priKey = PrivateKeyFactory.createKey(privateInfoByte);
        cipher.init(false, priKey);//false表示解密

        byte[] decryptDataBytes=cipher.processBlock(encryptDataBytes, 0, encryptDataBytes.length);
        String decryptData = new String(decryptDataBytes,"utf-8");
        return decryptData;
    }
}

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
BouncyCastleJava 平台上的一个加解密,支持多种加密算法,包括 PGP 加解密。以下是使用 BouncyCastle 实现 PGP 加密解密文件的示例代码: 1. 加载 BouncyCastle Provider: ``` Security.addProvider(new BouncyCastleProvider()); ``` 2. 生成 PGP 密钥对: ``` PGPKeyPairGenerator kpg = new JcaPGPKeyPairGenerator().setProvider("BC").setAlgorithm(AsymmetricAlgorithmTags.RSA_GENERAL).setKeySize(2048); PGPKeyPair kp = kpg.generate(); ``` 3. 导出公钥和私钥: ``` PGPPublicKeyRing publicKeyRing = new PGPPublicKeyRing(kp.getPublicKey().getEncoded(), new JcaKeyFingerprintCalculator()); PGPPublicKey publicKey = publicKeyRing.getPublicKey(); PGPPrivateKey privateKey = kp.getPrivateKey(); ``` 4. 加密文件: ``` // 创建加密器 PGPEncryptorBuilder builder = new JcePGPEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_256).setSecureRandom(new SecureRandom()); builder.setProvider("BC"); PGPEncryptor encryptor = builder.build(publicKey); // 创建输出流 File outputFile = new File("encrypted.pgp"); OutputStream outputStream = new FileOutputStream(outputFile); // 创建压缩器 PGPCompressedDataGenerator compressor = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP); OutputStream compressedOutputStream = compressor.open(outputStream); // 创建签名器 PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(PublicKeyAlgorithmTags.RSA_GENERAL, HashAlgorithmTags.SHA256).setProvider("BC")); signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, privateKey); signatureGenerator.generateOnePassVersion(false).encode(compressedOutputStream); // 创建字节流加密器 PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator(); OutputStream literalOutputStream = literalDataGenerator.open(compressedOutputStream, PGPLiteralData.BINARY, "filename", new Date(), new byte[1024]); // 加密文件内容 File inputFile = new File("input.txt"); InputStream inputStream = new FileInputStream(inputFile); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) != -1) { literalOutputStream.write(buffer, 0, length); } inputStream.close(); // 关闭流 literalDataGenerator.close(); signatureGenerator.generate().encode(compressedOutputStream); compressor.close(); encryptor.close(); outputStream.close(); ``` 5. 解密文件: ``` // 创建解密器 PGPObjectFactory factory = new JcaPGPObjectFactory(new FileInputStream("encrypted.pgp")); PGPEncryptedDataList encryptedDataList = (PGPEncryptedDataList) factory.nextObject(); PGPPBEEncryptedData pbeEncryptedData = (PGPPBEEncryptedData) encryptedDataList.get(0); PGPPrivateKey privateKey = findPrivateKey("userid", "password".toCharArray()); InputStream decryptedInputStream = pbeEncryptedData.getDataStream(new JcePBEDataDecryptorFactoryBuilder(new JcaPGPDigestCalculatorProviderBuilder().setProvider("BC").build()).setProvider("BC").build(privateKey)); // 创建签名校验器 PGPObjectFactory plainFactory = new JcaPGPObjectFactory(decryptedInputStream); PGPOnePassSignatureList signatureList = (PGPOnePassSignatureList) plainFactory.nextObject(); PGPOnePassSignature signature = signatureList.get(0); PGPPublicKey publicKey = findPublicKey(signature.getKeyID()); signature.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey); PGPLiteralData literalData = (PGPLiteralData) plainFactory.nextObject(); InputStream literalInputStream = literalData.getInputStream(); // 校验签名 byte[] buffer = new byte[1024]; int length; while ((length = literalInputStream.read(buffer)) != -1) { signature.update(buffer, 0, length); } if (signature.verify(((PGPSignatureList) plainFactory.nextObject()).get(0))) { System.out.println("Signature verified"); } else { System.out.println("Signature not verified"); } // 读取文件内容 while ((length = literalInputStream.read(buffer)) != -1) { // 处理文件内容 } literalInputStream.close(); decryptedInputStream.close(); ``` 其中,`findPrivateKey` 和 `findPublicKey` 方法根据指定的用户 ID 查找对应的私钥和公钥。在实际使用时,需要将用户 ID 和密钥信息存储在合适的位置,例如文件或数据中,然后在程序中进行读取。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值