SM2Engine可以加密,但如何在其上添加信封?

时间:2018-05-17 02:35:31

标签: java bouncycastle jce jca

我可以从证书文件中获取公钥,并使用下面的代码使用sm2engine加密消息。

public static String encrypt(String data, PublicKey publicKey)
    {

        ECPublicKeyParameters localECPublicKeyParameters = null;

        if (publicKey instanceof BCECPublicKey)
        {
            BCECPublicKey localECPublicKey = (BCECPublicKey)publicKey;
            ECParameterSpec localECParameterSpec = localECPublicKey.getParameters();
            ECDomainParameters localECDomainParameters = new ECDomainParameters(
                localECParameterSpec.getCurve(), localECParameterSpec.getG(),
                localECParameterSpec.getN());
            localECPublicKeyParameters = new ECPublicKeyParameters(localECPublicKey.getQ(),
                localECDomainParameters);
        }
        SM2Engine localSM2Engine = new SM2Engine();
        localSM2Engine.init(true, new ParametersWithRandom(localECPublicKeyParameters,
            new SecureRandom()));
        byte[] arrayOfByte2;
        try
        {
            arrayOfByte2 = localSM2Engine.processBlock(data.getBytes(), 0, data.getBytes().length);
            return new String(Base64.encode(arrayOfByte2));
        }
        catch (InvalidCipherTextException e)
        {

            e.printStackTrace();
            return null;
        }

但它没有被包围,我不知道如何添加信封,但我知道如何在没有sm2egine的情况下添加信封:

public static String encryptMessage(String message, X509Certificate cert) throws Exception {

    CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();
    gen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(cert));

    OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME).build();
    CMSTypedData content = new CMSProcessableByteArray(message.getBytes("UTF-8"));
    CMSEnvelopedData data = gen.generate(content, encryptor);
    String encryptedMessage = new String(Base64.encode(data.getEncoded()));

    return encryptedMessage;
}

但是现在我必须使用名为sm4的特殊算法作为对称算法来加密内容,而不是aes.And然后使用sm2来加密sm4的密钥,所有这些都在pkcs7中定义。所以如何加入这两个代码片段? 所有特殊算法似乎都可以通过BouncyCastle方法实现,但CMSAlgorithm类中没有sm4,但我找到了GMObjectIndenrifier.sms4_cbc,并将其作为参数传递,但得到了一个异常:

no such algorithm.

更多信息:从文件解析证书后,调用certificate.getSigAlgName(),其名称为SM3WITHSM2

0 个答案:

没有答案