Search in sources :

Example 1 with DHPublicKeyParameters

use of com.github.zhenwei.core.crypto.params.DHPublicKeyParameters in project LinLong-Java by zhenwei1108.

the class IESCipher method engineDoFinal.

// Finalisation methods
public byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException {
    if (inputLen != 0) {
        buffer.write(input, inputOffset, inputLen);
    }
    byte[] in = buffer.toByteArray();
    buffer.reset();
    // Convert parameters for use in IESEngine
    CipherParameters params = new IESWithCipherParameters(engineSpec.getDerivationV(), engineSpec.getEncodingV(), engineSpec.getMacKeySize(), engineSpec.getCipherKeySize());
    if (engineSpec.getNonce() != null) {
        params = new ParametersWithIV(params, engineSpec.getNonce());
    }
    DHParameters dhParams = ((DHKeyParameters) key).getParameters();
    byte[] V;
    if (otherKeyParameter != null) {
        try {
            if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) {
                engine.init(true, otherKeyParameter, key, params);
            } else {
                engine.init(false, key, otherKeyParameter, params);
            }
            return engine.processBlock(in, 0, in.length);
        } catch (Exception e) {
            throw new BadBlockException("unable to process block", e);
        }
    }
    if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) {
        // Generate the ephemeral key pair
        DHKeyPairGenerator gen = new DHKeyPairGenerator();
        gen.init(new DHKeyGenerationParameters(random, dhParams));
        EphemeralKeyPairGenerator kGen = new EphemeralKeyPairGenerator(gen, new KeyEncoder() {

            public byte[] getEncoded(AsymmetricKeyParameter keyParameter) {
                byte[] Vloc = new byte[(((DHKeyParameters) keyParameter).getParameters().getP().bitLength() + 7) / 8];
                byte[] Vtmp = BigIntegers.asUnsignedByteArray(((DHPublicKeyParameters) keyParameter).getY());
                if (Vtmp.length > Vloc.length) {
                    throw new IllegalArgumentException("Senders's public key longer than expected.");
                } else {
                    System.arraycopy(Vtmp, 0, Vloc, Vloc.length - Vtmp.length, Vtmp.length);
                }
                return Vloc;
            }
        });
        // Encrypt the buffer
        try {
            engine.init(key, params, kGen);
            return engine.processBlock(in, 0, in.length);
        } catch (Exception e) {
            throw new BadBlockException("unable to process block", e);
        }
    } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) {
        // Decrypt the buffer
        try {
            engine.init(key, params, new DHIESPublicKeyParser(((DHKeyParameters) key).getParameters()));
            return engine.processBlock(in, 0, in.length);
        } catch (InvalidCipherTextException e) {
            throw new BadBlockException("unable to process block", e);
        }
    } else {
        throw new IllegalStateException("IESCipher not initialised");
    }
}
Also used : EphemeralKeyPairGenerator(com.github.zhenwei.core.crypto.generators.EphemeralKeyPairGenerator) DHKeyParameters(com.github.zhenwei.core.crypto.params.DHKeyParameters) BadBlockException(com.github.zhenwei.provider.jcajce.provider.util.BadBlockException) KeyEncoder(com.github.zhenwei.core.crypto.KeyEncoder) InvalidCipherTextException(com.github.zhenwei.core.crypto.InvalidCipherTextException) DHPublicKeyParameters(com.github.zhenwei.core.crypto.params.DHPublicKeyParameters) DHParameters(com.github.zhenwei.core.crypto.params.DHParameters) DHKeyPairGenerator(com.github.zhenwei.core.crypto.generators.DHKeyPairGenerator) DHKeyGenerationParameters(com.github.zhenwei.core.crypto.params.DHKeyGenerationParameters) BadBlockException(com.github.zhenwei.provider.jcajce.provider.util.BadBlockException) InvalidCipherTextException(com.github.zhenwei.core.crypto.InvalidCipherTextException) ShortBufferException(javax.crypto.ShortBufferException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) BadPaddingException(javax.crypto.BadPaddingException) IESWithCipherParameters(com.github.zhenwei.core.crypto.params.IESWithCipherParameters) CipherParameters(com.github.zhenwei.core.crypto.CipherParameters) ParametersWithIV(com.github.zhenwei.core.crypto.params.ParametersWithIV) AsymmetricKeyParameter(com.github.zhenwei.core.crypto.params.AsymmetricKeyParameter) DHIESPublicKeyParser(com.github.zhenwei.core.crypto.parsers.DHIESPublicKeyParser) IESWithCipherParameters(com.github.zhenwei.core.crypto.params.IESWithCipherParameters)

Example 2 with DHPublicKeyParameters

use of com.github.zhenwei.core.crypto.params.DHPublicKeyParameters in project LinLong-Java by zhenwei1108.

the class KeyAgreementSpi method engineDoPhase.

protected Key engineDoPhase(Key key, boolean lastPhase) throws InvalidKeyException, IllegalStateException {
    if (x == null) {
        throw new IllegalStateException("Diffie-Hellman not initialised.");
    }
    if (!(key instanceof DHPublicKey)) {
        throw new InvalidKeyException("DHKeyAgreement doPhase requires DHPublicKey");
    }
    DHPublicKey pubKey = (DHPublicKey) key;
    if (!pubKey.getParams().getG().equals(g) || !pubKey.getParams().getP().equals(p)) {
        throw new InvalidKeyException("DHPublicKey not for this KeyAgreement!");
    }
    BigInteger peerY = ((DHPublicKey) key).getY();
    if (peerY == null || peerY.compareTo(TWO) < 0 || peerY.compareTo(p.subtract(ONE)) >= 0) {
        throw new InvalidKeyException("Invalid DH PublicKey");
    }
    if (unifiedAgreement != null) {
        if (!lastPhase) {
            throw new IllegalStateException("unified Diffie-Hellman can use only two key pairs");
        }
        DHPublicKeyParameters staticKey = generatePublicKeyParameter((PublicKey) key);
        DHPublicKeyParameters ephemKey = generatePublicKeyParameter(dheParameters.getOtherPartyEphemeralKey());
        DHUPublicParameters pKey = new DHUPublicParameters(staticKey, ephemKey);
        result = unifiedAgreement.calculateAgreement(pKey);
        return null;
    } else if (mqvAgreement != null) {
        if (!lastPhase) {
            throw new IllegalStateException("MQV Diffie-Hellman can use only two key pairs");
        }
        DHPublicKeyParameters staticKey = generatePublicKeyParameter((PublicKey) key);
        DHPublicKeyParameters ephemKey = generatePublicKeyParameter(mqvParameters.getOtherPartyEphemeralKey());
        DHMQVPublicParameters pKey = new DHMQVPublicParameters(staticKey, ephemKey);
        result = bigIntToBytes(mqvAgreement.calculateAgreement(pKey));
        return null;
    } else {
        BigInteger res = peerY.modPow(x, p);
        if (res.compareTo(ONE) == 0) {
            throw new InvalidKeyException("Shared key can't be 1");
        }
        result = bigIntToBytes(res);
        if (lastPhase) {
            return null;
        }
        return new BCDHPublicKey(res, pubKey.getParams());
    }
}
Also used : DHMQVPublicParameters(com.github.zhenwei.core.crypto.params.DHMQVPublicParameters) DHPublicKeyParameters(com.github.zhenwei.core.crypto.params.DHPublicKeyParameters) DHPublicKey(javax.crypto.interfaces.DHPublicKey) DHUPublicParameters(com.github.zhenwei.core.crypto.params.DHUPublicParameters) PublicKey(java.security.PublicKey) DHPublicKey(javax.crypto.interfaces.DHPublicKey) BigInteger(java.math.BigInteger) InvalidKeyException(java.security.InvalidKeyException)

Example 3 with DHPublicKeyParameters

use of com.github.zhenwei.core.crypto.params.DHPublicKeyParameters in project LinLong-Java by zhenwei1108.

the class KeyPairGeneratorSpi method generateKeyPair.

public KeyPair generateKeyPair() {
    if (!initialised) {
        Integer paramStrength = Integers.valueOf(strength);
        if (params.containsKey(paramStrength)) {
            param = (DHKeyGenerationParameters) params.get(paramStrength);
        } else {
            DHParameterSpec dhParams = WeGooProvider.CONFIGURATION.getDHDefaultParameters(strength);
            if (dhParams != null) {
                param = convertParams(random, dhParams);
            } else {
                synchronized (lock) {
                    // our key size.
                    if (params.containsKey(paramStrength)) {
                        param = (DHKeyGenerationParameters) params.get(paramStrength);
                    } else {
                        DHParametersGenerator pGen = new DHParametersGenerator();
                        pGen.init(strength, PrimeCertaintyCalculator.getDefaultCertainty(strength), random);
                        param = new DHKeyGenerationParameters(random, pGen.generateParameters());
                        params.put(paramStrength, param);
                    }
                }
            }
        }
        engine.init(param);
        initialised = true;
    }
    AsymmetricCipherKeyPair pair = engine.generateKeyPair();
    DHPublicKeyParameters pub = (DHPublicKeyParameters) pair.getPublic();
    DHPrivateKeyParameters priv = (DHPrivateKeyParameters) pair.getPrivate();
    return new KeyPair(new BCDHPublicKey(pub), new BCDHPrivateKey(priv));
}
Also used : KeyPair(java.security.KeyPair) AsymmetricCipherKeyPair(com.github.zhenwei.core.crypto.AsymmetricCipherKeyPair) DHPublicKeyParameters(com.github.zhenwei.core.crypto.params.DHPublicKeyParameters) DHPrivateKeyParameters(com.github.zhenwei.core.crypto.params.DHPrivateKeyParameters) DHKeyGenerationParameters(com.github.zhenwei.core.crypto.params.DHKeyGenerationParameters) DHParameterSpec(javax.crypto.spec.DHParameterSpec) DHParametersGenerator(com.github.zhenwei.core.crypto.generators.DHParametersGenerator) AsymmetricCipherKeyPair(com.github.zhenwei.core.crypto.AsymmetricCipherKeyPair)

Example 4 with DHPublicKeyParameters

use of com.github.zhenwei.core.crypto.params.DHPublicKeyParameters in project LinLong-Java by zhenwei1108.

the class DHAgreement method calculateMessage.

/**
 * calculate our initial message.
 */
public BigInteger calculateMessage() {
    DHKeyPairGenerator dhGen = new DHKeyPairGenerator();
    dhGen.init(new DHKeyGenerationParameters(random, dhParams));
    AsymmetricCipherKeyPair dhPair = dhGen.generateKeyPair();
    this.privateValue = ((DHPrivateKeyParameters) dhPair.getPrivate()).getX();
    return ((DHPublicKeyParameters) dhPair.getPublic()).getY();
}
Also used : DHPublicKeyParameters(com.github.zhenwei.core.crypto.params.DHPublicKeyParameters) DHKeyPairGenerator(com.github.zhenwei.core.crypto.generators.DHKeyPairGenerator) DHKeyGenerationParameters(com.github.zhenwei.core.crypto.params.DHKeyGenerationParameters) AsymmetricCipherKeyPair(com.github.zhenwei.core.crypto.AsymmetricCipherKeyPair)

Example 5 with DHPublicKeyParameters

use of com.github.zhenwei.core.crypto.params.DHPublicKeyParameters in project LinLong-Java by zhenwei1108.

the class DHBasicAgreement method calculateAgreement.

/**
 * given a short term public key from a given party calculate the next message in the agreement
 * sequence.
 */
public BigInteger calculateAgreement(CipherParameters pubKey) {
    DHPublicKeyParameters pub = (DHPublicKeyParameters) pubKey;
    if (!pub.getParameters().equals(dhParams)) {
        throw new IllegalArgumentException("Diffie-Hellman public key has wrong parameters.");
    }
    BigInteger p = dhParams.getP();
    BigInteger peerY = pub.getY();
    if (peerY == null || peerY.compareTo(ONE) <= 0 || peerY.compareTo(p.subtract(ONE)) >= 0) {
        throw new IllegalArgumentException("Diffie-Hellman public key is weak");
    }
    BigInteger result = peerY.modPow(key.getX(), p);
    if (result.equals(ONE)) {
        throw new IllegalStateException("Shared key can't be 1");
    }
    return result;
}
Also used : DHPublicKeyParameters(com.github.zhenwei.core.crypto.params.DHPublicKeyParameters) BigInteger(java.math.BigInteger)

Aggregations

DHPublicKeyParameters (com.github.zhenwei.core.crypto.params.DHPublicKeyParameters)9 BigInteger (java.math.BigInteger)5 AsymmetricCipherKeyPair (com.github.zhenwei.core.crypto.AsymmetricCipherKeyPair)4 DHParameters (com.github.zhenwei.core.crypto.params.DHParameters)4 DHKeyGenerationParameters (com.github.zhenwei.core.crypto.params.DHKeyGenerationParameters)3 DHPrivateKeyParameters (com.github.zhenwei.core.crypto.params.DHPrivateKeyParameters)3 InvalidKeyException (java.security.InvalidKeyException)3 DHKeyPairGenerator (com.github.zhenwei.core.crypto.generators.DHKeyPairGenerator)2 DHPublicKey (javax.crypto.interfaces.DHPublicKey)2 DHParameterSpec (javax.crypto.spec.DHParameterSpec)2 CipherParameters (com.github.zhenwei.core.crypto.CipherParameters)1 InvalidCipherTextException (com.github.zhenwei.core.crypto.InvalidCipherTextException)1 KeyEncoder (com.github.zhenwei.core.crypto.KeyEncoder)1 DHParametersGenerator (com.github.zhenwei.core.crypto.generators.DHParametersGenerator)1 EphemeralKeyPairGenerator (com.github.zhenwei.core.crypto.generators.EphemeralKeyPairGenerator)1 AsymmetricKeyParameter (com.github.zhenwei.core.crypto.params.AsymmetricKeyParameter)1 DHKeyParameters (com.github.zhenwei.core.crypto.params.DHKeyParameters)1 DHMQVPublicParameters (com.github.zhenwei.core.crypto.params.DHMQVPublicParameters)1 DHUPublicParameters (com.github.zhenwei.core.crypto.params.DHUPublicParameters)1 IESWithCipherParameters (com.github.zhenwei.core.crypto.params.IESWithCipherParameters)1