Search in sources :

Example 1 with Gost2814789EncryptedKey

use of com.github.zhenwei.core.asn1.cryptopro.Gost2814789EncryptedKey in project LinLong-Java by zhenwei1108.

the class JceKeyTransRecipient method extractSecretKey.

protected Key extractSecretKey(AlgorithmIdentifier keyEncryptionAlgorithm, AlgorithmIdentifier encryptedKeyAlgorithm, byte[] encryptedEncryptionKey) throws CMSException {
    if (CMSUtils.isGOST(keyEncryptionAlgorithm.getAlgorithm())) {
        try {
            GostR3410KeyTransport transport = GostR3410KeyTransport.getInstance(encryptedEncryptionKey);
            GostR3410TransportParameters transParams = transport.getTransportParameters();
            KeyFactory keyFactory = helper.createKeyFactory(keyEncryptionAlgorithm.getAlgorithm());
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(transParams.getEphemeralPublicKey().getEncoded()));
            KeyAgreement agreement = helper.createKeyAgreement(keyEncryptionAlgorithm.getAlgorithm());
            agreement.init(recipientKey, new UserKeyingMaterialSpec(transParams.getUkm()));
            agreement.doPhase(pubKey, true);
            SecretKey key = agreement.generateSecret(CryptoProObjectIdentifiers.id_Gost28147_89_CryptoPro_KeyWrap.getId());
            Cipher keyCipher = helper.createCipher(CryptoProObjectIdentifiers.id_Gost28147_89_CryptoPro_KeyWrap);
            keyCipher.init(Cipher.UNWRAP_MODE, key, new GOST28147WrapParameterSpec(transParams.getEncryptionParamSet(), transParams.getUkm()));
            Gost2814789EncryptedKey encKey = transport.getSessionEncryptedKey();
            return keyCipher.unwrap(Arrays.concatenate(encKey.getEncryptedKey(), encKey.getMacKey()), helper.getBaseCipherName(encryptedKeyAlgorithm.getAlgorithm()), Cipher.SECRET_KEY);
        } catch (Exception e) {
            throw new CMSException("exception unwrapping key: " + e.getMessage(), e);
        }
    } else {
        JceAsymmetricKeyUnwrapper unwrapper = helper.createAsymmetricUnwrapper(keyEncryptionAlgorithm, recipientKey).setMustProduceEncodableUnwrappedKey(unwrappedKeyMustBeEncodable);
        if (!extraMappings.isEmpty()) {
            for (Iterator it = extraMappings.keySet().iterator(); it.hasNext(); ) {
                ASN1ObjectIdentifier algorithm = (ASN1ObjectIdentifier) it.next();
                unwrapper.setAlgorithmMapping(algorithm, (String) extraMappings.get(algorithm));
            }
        }
        try {
            Key key = helper.getJceKey(encryptedKeyAlgorithm.getAlgorithm(), unwrapper.generateUnwrappedKey(encryptedKeyAlgorithm, encryptedEncryptionKey));
            if (validateKeySize) {
                helper.keySizeCheck(encryptedKeyAlgorithm, key);
            }
            return key;
        } catch (OperatorException e) {
            throw new CMSException("exception unwrapping key: " + e.getMessage(), e);
        }
    }
}
Also used : JceAsymmetricKeyUnwrapper(com.github.zhenwei.pkix.operator.jcajce.JceAsymmetricKeyUnwrapper) PublicKey(java.security.PublicKey) GOST28147WrapParameterSpec(com.github.zhenwei.provider.jcajce.spec.GOST28147WrapParameterSpec) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) UserKeyingMaterialSpec(com.github.zhenwei.provider.jcajce.spec.UserKeyingMaterialSpec) CMSException(com.github.zhenwei.pkix.cms.CMSException) OperatorException(com.github.zhenwei.pkix.operator.OperatorException) GostR3410KeyTransport(com.github.zhenwei.core.asn1.cryptopro.GostR3410KeyTransport) GostR3410TransportParameters(com.github.zhenwei.core.asn1.cryptopro.GostR3410TransportParameters) Gost2814789EncryptedKey(com.github.zhenwei.core.asn1.cryptopro.Gost2814789EncryptedKey) SecretKey(javax.crypto.SecretKey) Iterator(java.util.Iterator) Cipher(javax.crypto.Cipher) KeyAgreement(javax.crypto.KeyAgreement) KeyFactory(java.security.KeyFactory) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) Gost2814789EncryptedKey(com.github.zhenwei.core.asn1.cryptopro.Gost2814789EncryptedKey) SecretKey(javax.crypto.SecretKey) OperatorException(com.github.zhenwei.pkix.operator.OperatorException) CMSException(com.github.zhenwei.pkix.cms.CMSException)

Example 2 with Gost2814789EncryptedKey

use of com.github.zhenwei.core.asn1.cryptopro.Gost2814789EncryptedKey in project LinLong-Java by zhenwei1108.

the class JceKeyAgreeRecipient method extractSecretKey.

protected Key extractSecretKey(AlgorithmIdentifier keyEncryptionAlgorithm, AlgorithmIdentifier contentEncryptionAlgorithm, SubjectPublicKeyInfo senderKey, ASN1OctetString userKeyingMaterial, byte[] encryptedContentEncryptionKey) throws CMSException {
    try {
        AlgorithmIdentifier wrapAlg = AlgorithmIdentifier.getInstance(keyEncryptionAlgorithm.getParameters());
        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(senderKey.getEncoded());
        KeyFactory fact = helper.createKeyFactory(senderKey.getAlgorithm().getAlgorithm());
        PublicKey senderPublicKey = fact.generatePublic(pubSpec);
        try {
            SecretKey agreedWrapKey = calculateAgreedWrapKey(keyEncryptionAlgorithm, wrapAlg, senderPublicKey, userKeyingMaterial, recipientKey, ecc_cms_Generator);
            if (wrapAlg.getAlgorithm().equals(CryptoProObjectIdentifiers.id_Gost28147_89_None_KeyWrap) || wrapAlg.getAlgorithm().equals(CryptoProObjectIdentifiers.id_Gost28147_89_CryptoPro_KeyWrap)) {
                Gost2814789EncryptedKey encKey = Gost2814789EncryptedKey.getInstance(encryptedContentEncryptionKey);
                Gost2814789KeyWrapParameters wrapParams = Gost2814789KeyWrapParameters.getInstance(wrapAlg.getParameters());
                Cipher keyCipher = helper.createCipher(wrapAlg.getAlgorithm());
                keyCipher.init(Cipher.UNWRAP_MODE, agreedWrapKey, new GOST28147WrapParameterSpec(wrapParams.getEncryptionParamSet(), userKeyingMaterial.getOctets()));
                return keyCipher.unwrap(Arrays.concatenate(encKey.getEncryptedKey(), encKey.getMacKey()), helper.getBaseCipherName(contentEncryptionAlgorithm.getAlgorithm()), Cipher.SECRET_KEY);
            }
            return unwrapSessionKey(wrapAlg.getAlgorithm(), agreedWrapKey, contentEncryptionAlgorithm.getAlgorithm(), encryptedContentEncryptionKey);
        } catch (InvalidKeyException e) {
            // might be a pre-RFC 5753 message
            if (possibleOldMessages.contains(keyEncryptionAlgorithm.getAlgorithm())) {
                SecretKey agreedWrapKey = calculateAgreedWrapKey(keyEncryptionAlgorithm, wrapAlg, senderPublicKey, userKeyingMaterial, recipientKey, old_ecc_cms_Generator);
                return unwrapSessionKey(wrapAlg.getAlgorithm(), agreedWrapKey, contentEncryptionAlgorithm.getAlgorithm(), encryptedContentEncryptionKey);
            }
            // one last try - people do actually do this it turns out
            if (userKeyingMaterial != null) {
                try {
                    SecretKey agreedWrapKey = calculateAgreedWrapKey(keyEncryptionAlgorithm, wrapAlg, senderPublicKey, userKeyingMaterial, recipientKey, simple_ecc_cmsGenerator);
                    return unwrapSessionKey(wrapAlg.getAlgorithm(), agreedWrapKey, contentEncryptionAlgorithm.getAlgorithm(), encryptedContentEncryptionKey);
                } catch (InvalidKeyException ex) {
                    // we'll throw the original exception
                    throw e;
                }
            }
            throw e;
        }
    } catch (NoSuchAlgorithmException e) {
        throw new CMSException("can't find algorithm.", e);
    } catch (InvalidKeyException e) {
        throw new CMSException("key invalid in message.", e);
    } catch (InvalidKeySpecException e) {
        throw new CMSException("originator key spec invalid.", e);
    } catch (NoSuchPaddingException e) {
        throw new CMSException("required padding not supported.", e);
    } catch (Exception e) {
        throw new CMSException("originator key invalid.", e);
    }
}
Also used : PublicKey(java.security.PublicKey) GOST28147WrapParameterSpec(com.github.zhenwei.provider.jcajce.spec.GOST28147WrapParameterSpec) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) Gost2814789KeyWrapParameters(com.github.zhenwei.core.asn1.cryptopro.Gost2814789KeyWrapParameters) CMSException(com.github.zhenwei.pkix.cms.CMSException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) GeneralSecurityException(java.security.GeneralSecurityException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) Gost2814789EncryptedKey(com.github.zhenwei.core.asn1.cryptopro.Gost2814789EncryptedKey) SecretKey(javax.crypto.SecretKey) Cipher(javax.crypto.Cipher) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyFactory(java.security.KeyFactory) CMSException(com.github.zhenwei.pkix.cms.CMSException)

Example 3 with Gost2814789EncryptedKey

use of com.github.zhenwei.core.asn1.cryptopro.Gost2814789EncryptedKey in project LinLong-Java by zhenwei1108.

the class JceKeyAgreeRecipientInfoGenerator method generateRecipientEncryptedKeys.

public ASN1Sequence generateRecipientEncryptedKeys(AlgorithmIdentifier keyAgreeAlgorithm, AlgorithmIdentifier keyEncryptionAlgorithm, GenericKey contentEncryptionKey) throws CMSException {
    if (recipientIDs.isEmpty()) {
        throw new CMSException("No recipients associated with generator - use addRecipient()");
    }
    init(keyAgreeAlgorithm.getAlgorithm());
    PrivateKey senderPrivateKey = this.senderPrivateKey;
    ASN1ObjectIdentifier keyAgreementOID = keyAgreeAlgorithm.getAlgorithm();
    ASN1EncodableVector recipientEncryptedKeys = new ASN1EncodableVector();
    for (int i = 0; i != recipientIDs.size(); i++) {
        PublicKey recipientPublicKey = (PublicKey) recipientKeys.get(i);
        KeyAgreeRecipientIdentifier karId = (KeyAgreeRecipientIdentifier) recipientIDs.get(i);
        try {
            AlgorithmParameterSpec agreementParamSpec;
            ASN1ObjectIdentifier keyEncAlg = keyEncryptionAlgorithm.getAlgorithm();
            if (CMSUtils.isMQV(keyAgreementOID)) {
                agreementParamSpec = new MQVParameterSpec(ephemeralKP, recipientPublicKey, userKeyingMaterial);
            } else if (CMSUtils.isEC(keyAgreementOID)) {
                byte[] ukmKeyingMaterial = ecc_cms_Generator.generateKDFMaterial(keyEncryptionAlgorithm, keySizeProvider.getKeySize(keyEncAlg), userKeyingMaterial);
                agreementParamSpec = new UserKeyingMaterialSpec(ukmKeyingMaterial);
            } else if (CMSUtils.isRFC2631(keyAgreementOID)) {
                if (userKeyingMaterial != null) {
                    agreementParamSpec = new UserKeyingMaterialSpec(userKeyingMaterial);
                } else {
                    if (keyAgreementOID.equals(PKCSObjectIdentifiers.id_alg_SSDH)) {
                        throw new CMSException("User keying material must be set for static keys.");
                    }
                    agreementParamSpec = null;
                }
            } else if (CMSUtils.isGOST(keyAgreementOID)) {
                if (userKeyingMaterial != null) {
                    agreementParamSpec = new UserKeyingMaterialSpec(userKeyingMaterial);
                } else {
                    throw new CMSException("User keying material must be set for static keys.");
                }
            } else {
                throw new CMSException("Unknown key agreement algorithm: " + keyAgreementOID);
            }
            // Use key agreement to choose a wrap key for this recipient
            KeyAgreement keyAgreement = helper.createKeyAgreement(keyAgreementOID);
            keyAgreement.init(senderPrivateKey, agreementParamSpec, random);
            keyAgreement.doPhase(recipientPublicKey, true);
            SecretKey keyEncryptionKey = keyAgreement.generateSecret(keyEncAlg.getId());
            // Wrap the content encryption key with the agreement key
            Cipher keyEncryptionCipher = helper.createCipher(keyEncAlg);
            ASN1OctetString encryptedKey;
            if (keyEncAlg.equals(CryptoProObjectIdentifiers.id_Gost28147_89_None_KeyWrap) || keyEncAlg.equals(CryptoProObjectIdentifiers.id_Gost28147_89_CryptoPro_KeyWrap)) {
                keyEncryptionCipher.init(Cipher.WRAP_MODE, keyEncryptionKey, new GOST28147WrapParameterSpec(CryptoProObjectIdentifiers.id_Gost28147_89_CryptoPro_A_ParamSet, userKeyingMaterial));
                byte[] encKeyBytes = keyEncryptionCipher.wrap(helper.getJceKey(contentEncryptionKey));
                Gost2814789EncryptedKey encKey = new Gost2814789EncryptedKey(Arrays.copyOfRange(encKeyBytes, 0, encKeyBytes.length - 4), Arrays.copyOfRange(encKeyBytes, encKeyBytes.length - 4, encKeyBytes.length));
                encryptedKey = new DEROctetString(encKey.getEncoded(ASN1Encoding.DER));
            } else {
                keyEncryptionCipher.init(Cipher.WRAP_MODE, keyEncryptionKey, random);
                byte[] encryptedKeyBytes = keyEncryptionCipher.wrap(helper.getJceKey(contentEncryptionKey));
                encryptedKey = new DEROctetString(encryptedKeyBytes);
            }
            recipientEncryptedKeys.add(new RecipientEncryptedKey(karId, encryptedKey));
        } catch (GeneralSecurityException e) {
            throw new CMSException("cannot perform agreement step: " + e.getMessage(), e);
        } catch (IOException e) {
            throw new CMSException("unable to encode wrapped key: " + e.getMessage(), e);
        }
    }
    return new DERSequence(recipientEncryptedKeys);
}
Also used : ASN1OctetString(com.github.zhenwei.core.asn1.ASN1OctetString) PrivateKey(java.security.PrivateKey) OriginatorPublicKey(com.github.zhenwei.pkix.util.asn1.cms.OriginatorPublicKey) PublicKey(java.security.PublicKey) GOST28147WrapParameterSpec(com.github.zhenwei.provider.jcajce.spec.GOST28147WrapParameterSpec) RecipientEncryptedKey(com.github.zhenwei.pkix.util.asn1.cms.RecipientEncryptedKey) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) UserKeyingMaterialSpec(com.github.zhenwei.provider.jcajce.spec.UserKeyingMaterialSpec) DEROctetString(com.github.zhenwei.core.asn1.DEROctetString) Gost2814789EncryptedKey(com.github.zhenwei.core.asn1.cryptopro.Gost2814789EncryptedKey) SecretKey(javax.crypto.SecretKey) DERSequence(com.github.zhenwei.core.asn1.DERSequence) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector) Cipher(javax.crypto.Cipher) KeyAgreement(javax.crypto.KeyAgreement) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) MQVParameterSpec(com.github.zhenwei.provider.jcajce.spec.MQVParameterSpec) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier) CMSException(com.github.zhenwei.pkix.cms.CMSException) KeyAgreeRecipientIdentifier(com.github.zhenwei.pkix.util.asn1.cms.KeyAgreeRecipientIdentifier)

Example 4 with Gost2814789EncryptedKey

use of com.github.zhenwei.core.asn1.cryptopro.Gost2814789EncryptedKey in project LinLong-Java by zhenwei1108.

the class JceAsymmetricKeyWrapper method generateWrappedKey.

public byte[] generateWrappedKey(GenericKey encryptionKey) throws OperatorException {
    byte[] encryptedKeyBytes = null;
    if (isGOST(getAlgorithmIdentifier().getAlgorithm())) {
        try {
            random = CryptoServicesRegistrar.getSecureRandom(random);
            KeyPairGenerator kpGen = helper.createKeyPairGenerator(getAlgorithmIdentifier().getAlgorithm());
            kpGen.initialize(((ECPublicKey) publicKey).getParams(), random);
            KeyPair ephKp = kpGen.generateKeyPair();
            byte[] ukm = new byte[8];
            random.nextBytes(ukm);
            SubjectPublicKeyInfo ephKeyInfo = SubjectPublicKeyInfo.getInstance(ephKp.getPublic().getEncoded());
            GostR3410TransportParameters transParams;
            if (ephKeyInfo.getAlgorithm().getAlgorithm().on(RosstandartObjectIdentifiers.id_tc26)) {
                transParams = new GostR3410TransportParameters(RosstandartObjectIdentifiers.id_tc26_gost_28147_param_Z, ephKeyInfo, ukm);
            } else {
                transParams = new GostR3410TransportParameters(CryptoProObjectIdentifiers.id_Gost28147_89_CryptoPro_A_ParamSet, ephKeyInfo, ukm);
            }
            KeyAgreement agreement = helper.createKeyAgreement(getAlgorithmIdentifier().getAlgorithm());
            agreement.init(ephKp.getPrivate(), new UserKeyingMaterialSpec(transParams.getUkm()));
            agreement.doPhase(publicKey, true);
            SecretKey key = agreement.generateSecret(CryptoProObjectIdentifiers.id_Gost28147_89_CryptoPro_KeyWrap.getId());
            byte[] encKey = OperatorUtils.getJceKey(encryptionKey).getEncoded();
            Cipher keyCipher = helper.createCipher(CryptoProObjectIdentifiers.id_Gost28147_89_CryptoPro_KeyWrap);
            keyCipher.init(Cipher.WRAP_MODE, key, new GOST28147WrapParameterSpec(transParams.getEncryptionParamSet(), transParams.getUkm()));
            byte[] keyData = keyCipher.wrap(new SecretKeySpec(encKey, "GOST"));
            GostR3410KeyTransport transport = new GostR3410KeyTransport(new Gost2814789EncryptedKey(Arrays.copyOfRange(keyData, 0, 32), Arrays.copyOfRange(keyData, 32, 36)), transParams);
            return transport.getEncoded();
        } catch (Exception e) {
            throw new OperatorException("exception wrapping key: " + e.getMessage(), e);
        }
    } else {
        Cipher keyEncryptionCipher = helper.createAsymmetricWrapper(getAlgorithmIdentifier().getAlgorithm(), extraMappings);
        try {
            AlgorithmParameters algParams = helper.createAlgorithmParameters(this.getAlgorithmIdentifier());
            if (algParams != null) {
                keyEncryptionCipher.init(Cipher.WRAP_MODE, publicKey, algParams, random);
            } else {
                keyEncryptionCipher.init(Cipher.WRAP_MODE, publicKey, random);
            }
            encryptedKeyBytes = keyEncryptionCipher.wrap(OperatorUtils.getJceKey(encryptionKey));
        } catch (InvalidKeyException e) {
        } catch (GeneralSecurityException e) {
        } catch (IllegalStateException e) {
        } catch (UnsupportedOperationException e) {
        } catch (ProviderException e) {
        }
        // some providers do not support WRAP (this appears to be only for asymmetric algorithms)
        if (encryptedKeyBytes == null) {
            try {
                keyEncryptionCipher.init(Cipher.ENCRYPT_MODE, publicKey, random);
                encryptedKeyBytes = keyEncryptionCipher.doFinal(OperatorUtils.getJceKey(encryptionKey).getEncoded());
            } catch (InvalidKeyException e) {
                throw new OperatorException("unable to encrypt contents key", e);
            } catch (GeneralSecurityException e) {
                throw new OperatorException("unable to encrypt contents key", e);
            }
        }
    }
    return encryptedKeyBytes;
}
Also used : KeyPair(java.security.KeyPair) ProviderException(java.security.ProviderException) GOST28147WrapParameterSpec(com.github.zhenwei.provider.jcajce.spec.GOST28147WrapParameterSpec) GeneralSecurityException(java.security.GeneralSecurityException) KeyPairGenerator(java.security.KeyPairGenerator) InvalidKeyException(java.security.InvalidKeyException) SubjectPublicKeyInfo(com.github.zhenwei.core.asn1.x509.SubjectPublicKeyInfo) UserKeyingMaterialSpec(com.github.zhenwei.provider.jcajce.spec.UserKeyingMaterialSpec) GeneralSecurityException(java.security.GeneralSecurityException) InvalidParameterSpecException(java.security.spec.InvalidParameterSpecException) OperatorException(com.github.zhenwei.pkix.operator.OperatorException) ProviderException(java.security.ProviderException) InvalidKeyException(java.security.InvalidKeyException) GostR3410TransportParameters(com.github.zhenwei.core.asn1.cryptopro.GostR3410TransportParameters) GostR3410KeyTransport(com.github.zhenwei.core.asn1.cryptopro.GostR3410KeyTransport) Gost2814789EncryptedKey(com.github.zhenwei.core.asn1.cryptopro.Gost2814789EncryptedKey) SecretKey(javax.crypto.SecretKey) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Cipher(javax.crypto.Cipher) KeyAgreement(javax.crypto.KeyAgreement) OperatorException(com.github.zhenwei.pkix.operator.OperatorException) AlgorithmParameters(java.security.AlgorithmParameters)

Aggregations

Gost2814789EncryptedKey (com.github.zhenwei.core.asn1.cryptopro.Gost2814789EncryptedKey)4 GOST28147WrapParameterSpec (com.github.zhenwei.provider.jcajce.spec.GOST28147WrapParameterSpec)4 Cipher (javax.crypto.Cipher)4 SecretKey (javax.crypto.SecretKey)4 CMSException (com.github.zhenwei.pkix.cms.CMSException)3 UserKeyingMaterialSpec (com.github.zhenwei.provider.jcajce.spec.UserKeyingMaterialSpec)3 GeneralSecurityException (java.security.GeneralSecurityException)3 PublicKey (java.security.PublicKey)3 KeyAgreement (javax.crypto.KeyAgreement)3 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)2 GostR3410KeyTransport (com.github.zhenwei.core.asn1.cryptopro.GostR3410KeyTransport)2 GostR3410TransportParameters (com.github.zhenwei.core.asn1.cryptopro.GostR3410TransportParameters)2 OperatorException (com.github.zhenwei.pkix.operator.OperatorException)2 IOException (java.io.IOException)2 InvalidKeyException (java.security.InvalidKeyException)2 KeyFactory (java.security.KeyFactory)2 PrivateKey (java.security.PrivateKey)2 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)2 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)1 ASN1OctetString (com.github.zhenwei.core.asn1.ASN1OctetString)1