Search in sources :

Example 6 with RSAPrivateCrtKeyParameters

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

the class RSABlindedEngine method init.

/**
 * initialise the RSA engine.
 *
 * @param forEncryption true if we are encrypting, false otherwise.
 * @param param         the necessary RSA key parameters.
 */
public void init(boolean forEncryption, CipherParameters param) {
    core.init(forEncryption, param);
    if (param instanceof ParametersWithRandom) {
        ParametersWithRandom rParam = (ParametersWithRandom) param;
        this.key = (RSAKeyParameters) rParam.getParameters();
        if (key instanceof RSAPrivateCrtKeyParameters) {
            this.random = rParam.getRandom();
        } else {
            this.random = null;
        }
    } else {
        this.key = (RSAKeyParameters) param;
        if (key instanceof RSAPrivateCrtKeyParameters) {
            this.random = CryptoServicesRegistrar.getSecureRandom();
        } else {
            this.random = null;
        }
    }
}
Also used : ParametersWithRandom(com.github.zhenwei.core.crypto.params.ParametersWithRandom) RSAPrivateCrtKeyParameters(com.github.zhenwei.core.crypto.params.RSAPrivateCrtKeyParameters)

Example 7 with RSAPrivateCrtKeyParameters

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

the class RSABlindedEngine method processBlock.

/**
 * Process a single block using the basic RSA algorithm.
 *
 * @param in    the input array.
 * @param inOff the offset into the input buffer where the data starts.
 * @param inLen the length of the data to be processed.
 * @return the result of the RSA process.
 * @throws DataLengthException the input block is too large.
 */
public byte[] processBlock(byte[] in, int inOff, int inLen) {
    if (key == null) {
        throw new IllegalStateException("RSA engine not initialised");
    }
    BigInteger input = core.convertInput(in, inOff, inLen);
    BigInteger result;
    if (key instanceof RSAPrivateCrtKeyParameters) {
        RSAPrivateCrtKeyParameters k = (RSAPrivateCrtKeyParameters) key;
        BigInteger e = k.getPublicExponent();
        if (// can't do blinding without a public exponent
        e != null) {
            BigInteger m = k.getModulus();
            BigInteger r = BigIntegers.createRandomInRange(ONE, m.subtract(ONE), random);
            BigInteger blindedInput = r.modPow(e, m).multiply(input).mod(m);
            BigInteger blindedResult = core.processBlock(blindedInput);
            BigInteger rInv = BigIntegers.modOddInverse(m, r);
            result = blindedResult.multiply(rInv).mod(m);
            // defence against Arjen Lenstra’s CRT attack
            if (!input.equals(result.modPow(e, m))) {
                throw new IllegalStateException("RSA engine faulty decryption/signing detected");
            }
        } else {
            result = core.processBlock(input);
        }
    } else {
        result = core.processBlock(input);
    }
    return core.convertOutput(result);
}
Also used : BigInteger(java.math.BigInteger) RSAPrivateCrtKeyParameters(com.github.zhenwei.core.crypto.params.RSAPrivateCrtKeyParameters)

Example 8 with RSAPrivateCrtKeyParameters

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

the class RSACoreEngine method processBlock.

public BigInteger processBlock(BigInteger input) {
    if (key instanceof RSAPrivateCrtKeyParameters) {
        // 
        // we have the extra factors, use the Chinese Remainder Theorem - the author
        // wishes to express his thanks to Dirk Bonekaemper at rtsffm.com for
        // advice regarding the expression of this.
        // 
        RSAPrivateCrtKeyParameters crtKey = (RSAPrivateCrtKeyParameters) key;
        BigInteger p = crtKey.getP();
        BigInteger q = crtKey.getQ();
        BigInteger dP = crtKey.getDP();
        BigInteger dQ = crtKey.getDQ();
        BigInteger qInv = crtKey.getQInv();
        BigInteger mP, mQ, h, m;
        // mP = ((input mod p) ^ dP)) mod p
        mP = (input.remainder(p)).modPow(dP, p);
        // mQ = ((input mod q) ^ dQ)) mod q
        mQ = (input.remainder(q)).modPow(dQ, q);
        // h = qInv * (mP - mQ) mod p
        h = mP.subtract(mQ);
        h = h.multiply(qInv);
        // mod (in Java) returns the positive residual
        h = h.mod(p);
        // m = h * q + mQ
        m = h.multiply(q);
        m = m.add(mQ);
        return m;
    } else {
        return input.modPow(key.getExponent(), key.getModulus());
    }
}
Also used : BigInteger(java.math.BigInteger) RSAPrivateCrtKeyParameters(com.github.zhenwei.core.crypto.params.RSAPrivateCrtKeyParameters)

Example 9 with RSAPrivateCrtKeyParameters

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

the class PrivateKeyFactory method createKey.

/**
 * Create a private key parameter from the passed in PKCS8 PrivateKeyInfo object.
 *
 * @param keyInfo the PrivateKeyInfo object containing the key material
 * @return a suitable private key parameter
 * @throws IOException on an error decoding the key
 */
public static AsymmetricKeyParameter createKey(PrivateKeyInfo keyInfo) throws IOException {
    AlgorithmIdentifier algId = keyInfo.getPrivateKeyAlgorithm();
    ASN1ObjectIdentifier algOID = algId.getAlgorithm();
    if (algOID.equals(PKCSObjectIdentifiers.rsaEncryption) || algOID.equals(PKCSObjectIdentifiers.id_RSASSA_PSS) || algOID.equals(X509ObjectIdentifiers.id_ea_rsa)) {
        RSAPrivateKey keyStructure = RSAPrivateKey.getInstance(keyInfo.parsePrivateKey());
        return new RSAPrivateCrtKeyParameters(keyStructure.getModulus(), keyStructure.getPublicExponent(), keyStructure.getPrivateExponent(), keyStructure.getPrime1(), keyStructure.getPrime2(), keyStructure.getExponent1(), keyStructure.getExponent2(), keyStructure.getCoefficient());
    } else // else if (algOID.equals(X9ObjectIdentifiers.dhpublicnumber))
    if (algOID.equals(PKCSObjectIdentifiers.dhKeyAgreement)) {
        DHParameter params = DHParameter.getInstance(algId.getParameters());
        ASN1Integer derX = (ASN1Integer) keyInfo.parsePrivateKey();
        BigInteger lVal = params.getL();
        int l = lVal == null ? 0 : lVal.intValue();
        DHParameters dhParams = new DHParameters(params.getP(), params.getG(), null, l);
        return new DHPrivateKeyParameters(derX.getValue(), dhParams);
    } else if (algOID.equals(OIWObjectIdentifiers.elGamalAlgorithm)) {
        ElGamalParameter params = ElGamalParameter.getInstance(algId.getParameters());
        ASN1Integer derX = (ASN1Integer) keyInfo.parsePrivateKey();
        return new ElGamalPrivateKeyParameters(derX.getValue(), new ElGamalParameters(params.getP(), params.getG()));
    } else if (algOID.equals(X9ObjectIdentifiers.id_dsa)) {
        ASN1Integer derX = (ASN1Integer) keyInfo.parsePrivateKey();
        ASN1Encodable algParameters = algId.getParameters();
        DSAParameters parameters = null;
        if (algParameters != null) {
            DSAParameter params = DSAParameter.getInstance(algParameters.toASN1Primitive());
            parameters = new DSAParameters(params.getP(), params.getQ(), params.getG());
        }
        return new DSAPrivateKeyParameters(derX.getValue(), parameters);
    } else if (algOID.equals(X9ObjectIdentifiers.id_ecPublicKey)) {
        X962Parameters params = X962Parameters.getInstance(algId.getParameters());
        X9ECParameters x9;
        ECDomainParameters dParams;
        if (params.isNamedCurve()) {
            ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) params.getParameters();
            x9 = CustomNamedCurves.getByOID(oid);
            if (x9 == null) {
                x9 = ECNamedCurveTable.getByOID(oid);
            }
            dParams = new ECNamedDomainParameters(oid, x9);
        } else {
            x9 = X9ECParameters.getInstance(params.getParameters());
            dParams = new ECDomainParameters(x9.getCurve(), x9.getG(), x9.getN(), x9.getH(), x9.getSeed());
        }
        ECPrivateKey ec = ECPrivateKey.getInstance(keyInfo.parsePrivateKey());
        BigInteger d = ec.getKey();
        return new ECPrivateKeyParameters(d, dParams);
    } else if (algOID.equals(EdECObjectIdentifiers.id_X25519)) {
        return new X25519PrivateKeyParameters(getRawKey(keyInfo));
    } else if (algOID.equals(EdECObjectIdentifiers.id_X448)) {
        return new X448PrivateKeyParameters(getRawKey(keyInfo));
    } else if (algOID.equals(EdECObjectIdentifiers.id_Ed25519)) {
        return new Ed25519PrivateKeyParameters(getRawKey(keyInfo));
    } else if (algOID.equals(EdECObjectIdentifiers.id_Ed448)) {
        return new Ed448PrivateKeyParameters(getRawKey(keyInfo));
    } else if (algOID.equals(CryptoProObjectIdentifiers.gostR3410_2001) || algOID.equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512) || algOID.equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256)) {
        ASN1Encodable algParameters = algId.getParameters();
        GOST3410PublicKeyAlgParameters gostParams = GOST3410PublicKeyAlgParameters.getInstance(algParameters);
        ECGOST3410Parameters ecSpec = null;
        BigInteger d = null;
        ASN1Primitive p = algParameters.toASN1Primitive();
        if (p instanceof ASN1Sequence && (ASN1Sequence.getInstance(p).size() == 2 || ASN1Sequence.getInstance(p).size() == 3)) {
            X9ECParameters ecP = ECGOST3410NamedCurves.getByOIDX9(gostParams.getPublicKeyParamSet());
            ecSpec = new ECGOST3410Parameters(new ECNamedDomainParameters(gostParams.getPublicKeyParamSet(), ecP), gostParams.getPublicKeyParamSet(), gostParams.getDigestParamSet(), gostParams.getEncryptionParamSet());
            ASN1OctetString privEnc = keyInfo.getPrivateKey();
            if (privEnc.getOctets().length == 32 || privEnc.getOctets().length == 64) {
                d = new BigInteger(1, Arrays.reverse(privEnc.getOctets()));
            } else {
                ASN1Encodable privKey = keyInfo.parsePrivateKey();
                if (privKey instanceof ASN1Integer) {
                    d = ASN1Integer.getInstance(privKey).getPositiveValue();
                } else {
                    byte[] dVal = Arrays.reverse(ASN1OctetString.getInstance(privKey).getOctets());
                    d = new BigInteger(1, dVal);
                }
            }
        } else {
            X962Parameters params = X962Parameters.getInstance(algId.getParameters());
            if (params.isNamedCurve()) {
                ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(params.getParameters());
                X9ECParameters ecP = ECNamedCurveTable.getByOID(oid);
                ecSpec = new ECGOST3410Parameters(new ECNamedDomainParameters(oid, ecP), gostParams.getPublicKeyParamSet(), gostParams.getDigestParamSet(), gostParams.getEncryptionParamSet());
            } else if (params.isImplicitlyCA()) {
                ecSpec = null;
            } else {
                X9ECParameters ecP = X9ECParameters.getInstance(params.getParameters());
                ecSpec = new ECGOST3410Parameters(new ECNamedDomainParameters(algOID, ecP), gostParams.getPublicKeyParamSet(), gostParams.getDigestParamSet(), gostParams.getEncryptionParamSet());
            }
            ASN1Encodable privKey = keyInfo.parsePrivateKey();
            if (privKey instanceof ASN1Integer) {
                ASN1Integer derD = ASN1Integer.getInstance(privKey);
                d = derD.getValue();
            } else {
                ECPrivateKey ec = ECPrivateKey.getInstance(privKey);
                d = ec.getKey();
            }
        }
        return new ECPrivateKeyParameters(d, new ECGOST3410Parameters(ecSpec, gostParams.getPublicKeyParamSet(), gostParams.getDigestParamSet(), gostParams.getEncryptionParamSet()));
    } else {
        throw new RuntimeException("algorithm identifier in private key not recognised");
    }
}
Also used : ASN1OctetString(com.github.zhenwei.core.asn1.ASN1OctetString) ECDomainParameters(com.github.zhenwei.core.crypto.params.ECDomainParameters) DHPrivateKeyParameters(com.github.zhenwei.core.crypto.params.DHPrivateKeyParameters) X9ECParameters(com.github.zhenwei.core.asn1.x9.X9ECParameters) GOST3410PublicKeyAlgParameters(com.github.zhenwei.core.asn1.cryptopro.GOST3410PublicKeyAlgParameters) ECGOST3410Parameters(com.github.zhenwei.core.crypto.params.ECGOST3410Parameters) X25519PrivateKeyParameters(com.github.zhenwei.core.crypto.params.X25519PrivateKeyParameters) Ed448PrivateKeyParameters(com.github.zhenwei.core.crypto.params.Ed448PrivateKeyParameters) Ed25519PrivateKeyParameters(com.github.zhenwei.core.crypto.params.Ed25519PrivateKeyParameters) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) X962Parameters(com.github.zhenwei.core.asn1.x9.X962Parameters) ASN1Encodable(com.github.zhenwei.core.asn1.ASN1Encodable) DSAParameter(com.github.zhenwei.core.asn1.x509.DSAParameter) X448PrivateKeyParameters(com.github.zhenwei.core.crypto.params.X448PrivateKeyParameters) DHParameter(com.github.zhenwei.core.asn1.pkcs.DHParameter) ECPrivateKey(com.github.zhenwei.core.asn1.sec.ECPrivateKey) DHParameters(com.github.zhenwei.core.crypto.params.DHParameters) ElGamalPrivateKeyParameters(com.github.zhenwei.core.crypto.params.ElGamalPrivateKeyParameters) ECNamedDomainParameters(com.github.zhenwei.core.crypto.params.ECNamedDomainParameters) ASN1Integer(com.github.zhenwei.core.asn1.ASN1Integer) ECPrivateKeyParameters(com.github.zhenwei.core.crypto.params.ECPrivateKeyParameters) ElGamalParameter(com.github.zhenwei.core.asn1.oiw.ElGamalParameter) ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence) ElGamalParameters(com.github.zhenwei.core.crypto.params.ElGamalParameters) DSAPrivateKeyParameters(com.github.zhenwei.core.crypto.params.DSAPrivateKeyParameters) BigInteger(java.math.BigInteger) RSAPrivateKey(com.github.zhenwei.core.asn1.pkcs.RSAPrivateKey) DSAParameters(com.github.zhenwei.core.crypto.params.DSAParameters) ASN1Primitive(com.github.zhenwei.core.asn1.ASN1Primitive) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier) RSAPrivateCrtKeyParameters(com.github.zhenwei.core.crypto.params.RSAPrivateCrtKeyParameters)

Example 10 with RSAPrivateCrtKeyParameters

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

the class OpenSSHPrivateKeyUtil method parsePrivateKeyBlob.

/**
 * Parse a private key.
 * <p>
 * This method accepts the body of the OpenSSH private key. The easiest way to extract the body is
 * to use PemReader, for example:
 * <p>
 * byte[] blob = new PemReader([reader]).readPemObject().getContent(); CipherParameters params =
 * parsePrivateKeyBlob(blob);
 *
 * @param blob The key.
 * @return A cipher parameters instance.
 */
public static AsymmetricKeyParameter parsePrivateKeyBlob(byte[] blob) {
    AsymmetricKeyParameter result = null;
    if (blob[0] == 0x30) {
        ASN1Sequence sequence = ASN1Sequence.getInstance(blob);
        if (sequence.size() == 6) {
            if (allIntegers(sequence) && ((ASN1Integer) sequence.getObjectAt(0)).getPositiveValue().equals(BigIntegers.ZERO)) {
                // length of 6 and all Integers -- DSA
                result = new DSAPrivateKeyParameters(((ASN1Integer) sequence.getObjectAt(5)).getPositiveValue(), new DSAParameters(((ASN1Integer) sequence.getObjectAt(1)).getPositiveValue(), ((ASN1Integer) sequence.getObjectAt(2)).getPositiveValue(), ((ASN1Integer) sequence.getObjectAt(3)).getPositiveValue()));
            }
        } else if (sequence.size() == 9) {
            if (allIntegers(sequence) && ((ASN1Integer) sequence.getObjectAt(0)).getPositiveValue().equals(BigIntegers.ZERO)) {
                // length of 8 and all Integers -- RSA
                RSAPrivateKey rsaPrivateKey = RSAPrivateKey.getInstance(sequence);
                result = new RSAPrivateCrtKeyParameters(rsaPrivateKey.getModulus(), rsaPrivateKey.getPublicExponent(), rsaPrivateKey.getPrivateExponent(), rsaPrivateKey.getPrime1(), rsaPrivateKey.getPrime2(), rsaPrivateKey.getExponent1(), rsaPrivateKey.getExponent2(), rsaPrivateKey.getCoefficient());
            }
        } else if (sequence.size() == 4) {
            if (sequence.getObjectAt(3) instanceof ASN1TaggedObject && sequence.getObjectAt(2) instanceof ASN1TaggedObject) {
                ECPrivateKey ecPrivateKey = ECPrivateKey.getInstance(sequence);
                ASN1ObjectIdentifier curveOID = ASN1ObjectIdentifier.getInstance(ecPrivateKey.getParametersObject());
                X9ECParameters x9Params = ECNamedCurveTable.getByOID(curveOID);
                result = new ECPrivateKeyParameters(ecPrivateKey.getKey(), new ECNamedDomainParameters(curveOID, x9Params));
            }
        }
    } else {
        SSHBuffer kIn = new SSHBuffer(AUTH_MAGIC, blob);
        String cipherName = kIn.readString();
        if (!"none".equals(cipherName)) {
            throw new IllegalStateException("encrypted keys not supported");
        }
        // KDF name
        kIn.skipBlock();
        // KDF options
        kIn.skipBlock();
        int publicKeyCount = kIn.readU32();
        if (publicKeyCount != 1) {
            throw new IllegalStateException("multiple keys not supported");
        }
        // Burn off public key.
        OpenSSHPublicKeyUtil.parsePublicKey(kIn.readBlock());
        byte[] privateKeyBlock = kIn.readPaddedBlock();
        if (kIn.hasRemaining()) {
            throw new IllegalArgumentException("decoded key has trailing data");
        }
        SSHBuffer pkIn = new SSHBuffer(privateKeyBlock);
        int check1 = pkIn.readU32();
        int check2 = pkIn.readU32();
        if (check1 != check2) {
            throw new IllegalStateException("private key check values are not the same");
        }
        String keyType = pkIn.readString();
        if ("ssh-ed25519".equals(keyType)) {
            // Public key
            pkIn.readBlock();
            // Private key value..
            byte[] edPrivateKey = pkIn.readBlock();
            if (edPrivateKey.length != Ed25519PrivateKeyParameters.KEY_SIZE + Ed25519PublicKeyParameters.KEY_SIZE) {
                throw new IllegalStateException("private key value of wrong length");
            }
            result = new Ed25519PrivateKeyParameters(edPrivateKey, 0);
        } else if (keyType.startsWith("ecdsa")) {
            ASN1ObjectIdentifier oid = SSHNamedCurves.getByName(Strings.fromByteArray(pkIn.readBlock()));
            if (oid == null) {
                throw new IllegalStateException("OID not found for: " + keyType);
            }
            X9ECParameters curveParams = NISTNamedCurves.getByOID(oid);
            if (curveParams == null) {
                throw new IllegalStateException("Curve not found for: " + oid);
            }
            // Skip public key.
            pkIn.readBlock();
            byte[] privKey = pkIn.readBlock();
            result = new ECPrivateKeyParameters(new BigInteger(1, privKey), new ECNamedDomainParameters(oid, curveParams));
        }
        // Comment for private key
        pkIn.skipBlock();
        if (pkIn.hasRemaining()) {
            throw new IllegalArgumentException("private key block has trailing data");
        }
    }
    if (result == null) {
        throw new IllegalArgumentException("unable to parse key");
    }
    return result;
}
Also used : ECPrivateKey(com.github.zhenwei.core.asn1.sec.ECPrivateKey) X9ECParameters(com.github.zhenwei.core.asn1.x9.X9ECParameters) ASN1TaggedObject(com.github.zhenwei.core.asn1.ASN1TaggedObject) ECNamedDomainParameters(com.github.zhenwei.core.crypto.params.ECNamedDomainParameters) ASN1Integer(com.github.zhenwei.core.asn1.ASN1Integer) Ed25519PrivateKeyParameters(com.github.zhenwei.core.crypto.params.Ed25519PrivateKeyParameters) ECPrivateKeyParameters(com.github.zhenwei.core.crypto.params.ECPrivateKeyParameters) ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence) AsymmetricKeyParameter(com.github.zhenwei.core.crypto.params.AsymmetricKeyParameter) DSAPrivateKeyParameters(com.github.zhenwei.core.crypto.params.DSAPrivateKeyParameters) BigInteger(java.math.BigInteger) DSAParameters(com.github.zhenwei.core.crypto.params.DSAParameters) RSAPrivateKey(com.github.zhenwei.core.asn1.pkcs.RSAPrivateKey) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier) RSAPrivateCrtKeyParameters(com.github.zhenwei.core.crypto.params.RSAPrivateCrtKeyParameters)

Aggregations

RSAPrivateCrtKeyParameters (com.github.zhenwei.core.crypto.params.RSAPrivateCrtKeyParameters)11 BigInteger (java.math.BigInteger)6 ASN1Integer (com.github.zhenwei.core.asn1.ASN1Integer)4 DSAParameters (com.github.zhenwei.core.crypto.params.DSAParameters)4 DSAPrivateKeyParameters (com.github.zhenwei.core.crypto.params.DSAPrivateKeyParameters)4 ECPrivateKeyParameters (com.github.zhenwei.core.crypto.params.ECPrivateKeyParameters)4 Ed25519PrivateKeyParameters (com.github.zhenwei.core.crypto.params.Ed25519PrivateKeyParameters)4 ASN1ObjectIdentifier (com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)3 RSAPrivateKey (com.github.zhenwei.core.asn1.pkcs.RSAPrivateKey)3 ECPrivateKey (com.github.zhenwei.core.asn1.sec.ECPrivateKey)3 X9ECParameters (com.github.zhenwei.core.asn1.x9.X9ECParameters)3 ECNamedDomainParameters (com.github.zhenwei.core.crypto.params.ECNamedDomainParameters)3 RSAKeyParameters (com.github.zhenwei.core.crypto.params.RSAKeyParameters)3 ASN1Encodable (com.github.zhenwei.core.asn1.ASN1Encodable)2 ASN1Sequence (com.github.zhenwei.core.asn1.ASN1Sequence)2 GOST3410PublicKeyAlgParameters (com.github.zhenwei.core.asn1.cryptopro.GOST3410PublicKeyAlgParameters)2 PrivateKeyInfo (com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo)2 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)2 DSAParameter (com.github.zhenwei.core.asn1.x509.DSAParameter)2 X962Parameters (com.github.zhenwei.core.asn1.x9.X962Parameters)2