Example usage for org.bouncycastle.crypto.params RSAKeyParameters getModulus

List of usage examples for org.bouncycastle.crypto.params RSAKeyParameters getModulus

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.params RSAKeyParameters getModulus.

Prototype

public BigInteger getModulus() 

Source Link

Usage

From source file:be.neutrinet.ispng.vpn.api.VPNClientCertificate.java

@Put
public Representation storeCSR(Representation csrstream) {
    if (!getRequestAttributes().containsKey("client")) {
        return clientError("MALFORMED_REQUEST", Status.CLIENT_ERROR_BAD_REQUEST);
    }//from ww  w  . j a  v  a  2s .c om

    StreamRepresentation sr = (StreamRepresentation) csrstream;

    // Do all kinds of security checks
    try {
        Client client = Clients.dao.queryForId(getAttribute("client").toString());
        PEMParser parser = new PEMParser(sr.getReader());
        PKCS10CertificationRequest csr = (PKCS10CertificationRequest) parser.readObject();

        SubjectPublicKeyInfo pkInfo = csr.getSubjectPublicKeyInfo();
        RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkInfo);

        // This makes the NSA work harder on their quantum computer
        // Require 4096 bit key
        // http://stackoverflow.com/a/20622933
        if (!(rsa.getModulus().bitLength() > 2048)) {
            ClientError err = new ClientError("ILLEGAL_KEY_SIZE");
            return new JacksonRepresentation(err);
        }

        X500Name subject = X500Name.getInstance(csr.getSubject());
        RDN[] rdns = subject.getRDNs(BCStyle.CN);
        if (rdns == null || rdns.length == 0) {
            return clientError("NO_CSR_CN", Status.CLIENT_ERROR_BAD_REQUEST);
        }

        String CN = IETFUtils.valueToString(rdns[0].getFirst().getValue());
        if (CN == null || CN.isEmpty()) {
            return clientError("INVALID_CSR_CN", Status.CLIENT_ERROR_BAD_REQUEST);
        }

        if (getQueryValue("rekey") != null && Boolean.parseBoolean(getQueryValue("rekey"))) {
            if (!getRequestAttributes().containsKey("cert")) {
                return clientError("MALFORMED_REQUEST", Status.CLIENT_ERROR_BAD_REQUEST);
            }

            Certificate old = Certificates.dao.queryForId(getAttribute("cert"));

            if (old == null)
                return clientError("MALFORMED_REQUEST", Status.CLIENT_ERROR_BAD_REQUEST);

            old.revocationDate = new Date();

            if (old.get() == null) {
                // this can happen when the old certificate is no longer present on the system
                // in which case the rekey has to go through
            } else if (pkInfo.getPublicKeyData().getString()
                    .equals(old.get().getSubjectPublicKeyInfo().getPublicKeyData().getString())) {
                return clientError("REKEY_USING_SAME_KEY", Status.CLIENT_ERROR_NOT_ACCEPTABLE);
            }

            Certificates.dao.update(old);
        }

        for (Certificate existingCert : Certificates.dao.queryForEq("client_id", client)) {
            if (existingCert.revocationDate.getTime() > System.currentTimeMillis()) {
                return clientError("ANOTHER_CLIENT_CERT_ACTIVE", Status.CLIENT_ERROR_NOT_ACCEPTABLE);
            }
        }

        // couple CN to client
        client.commonName = CN;
        Clients.dao.update(client);

        String caStorePath = VPN.cfg.getProperty("ca.storeDir", "ca");
        File dir = new File(caStorePath);
        if (!dir.isDirectory()) {
            dir.mkdirs();
        }

        Certificate cert = new Certificate();
        cert.client = client;
        Certificates.dao.create(cert);

        FileWriter fw = new FileWriter(caStorePath + "/" + cert.id + ".csr");
        PEMWriter pw = new PEMWriter(fw);
        pw.writeObject(csr);
        pw.flush();

        return new JacksonRepresentation<>(cert);
    } catch (Exception ex) {
        Logger.getLogger(getClass()).error("Failed to validate CSR and/or sign CSR", ex);
    }

    return DEFAULT_ERROR;
}

From source file:co.lqnt.lockbox.key.KeyFactory.java

License:Open Source License

/**
 * Create a public key from a PEM formatted public key.
 *
 * @param input The PEM data to read.//from   w  ww.  j av a  2s .  c om
 *
 * @return The public key
 * @throws PublicKeyReadException If reading of the public key fails.
 */
public PublicKey createPublicKey(final InputStream input) throws PublicKeyReadException {
    Object pemObject;
    try {
        pemObject = this.parsePemObject(input);
    } catch (PEMException e) {
        throw new PublicKeyReadException(e);
    }

    SubjectPublicKeyInfo publicKeyInfo;
    if (pemObject instanceof SubjectPublicKeyInfo) {
        publicKeyInfo = (SubjectPublicKeyInfo) pemObject;
    } else {
        throw new PublicKeyReadException();
    }

    AsymmetricKeyParameter keyParameter;
    try {
        keyParameter = this.bcKeyParametersFactory().createPublicKeyParameters(publicKeyInfo);
    } catch (IOException e) {
        throw new PublicKeyReadException(e);
    }

    RSAKeyParameters publicKeyParameters;
    if (keyParameter instanceof RSAKeyParameters) {
        publicKeyParameters = (RSAKeyParameters) keyParameter;
    } else {
        throw new PublicKeyReadException();
    }

    return new PublicKey(publicKeyParameters.getModulus(), publicKeyParameters.getExponent());
}

From source file:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java

License:Open Source License

public X509Certificate signCert(PKCS10CertificationRequest pkcs10CSR, X500Name issuer, KeyPair pKeyPair)
        throws Exception {
    SubjectPublicKeyInfo pkInfo = pkcs10CSR.getSubjectPublicKeyInfo();
    RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkInfo);
    RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());
    KeyFactory kf = KeyFactory.getInstance(ALG_RSA);
    PublicKey publicKey = kf.generatePublic(rsaSpec);

    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publicKey.getEncoded()));
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer,
            BigInteger.valueOf(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() - DateConstant.ONE_DAY),
            new Date(System.currentTimeMillis() + DateConstant.ONE_YEAR), pkcs10CSR.getSubject(), keyInfo);

    ContentSigner signer = new JcaContentSignerBuilder(ALG_SIG_SHA256_RSA).setProvider(JCE_PROVIDER)
            .build(pKeyPair.getPrivate());
    X509Certificate signedCert = new JcaX509CertificateConverter().setProvider(JCE_PROVIDER)
            .getCertificate(certBuilder.build(signer));
    signedCert.verify(pKeyPair.getPublic());

    return signedCert;
}

From source file:com.foilen.smalltools.crypt.asymmetric.RSACrypt.java

License:Open Source License

@Override
public RSAKeyDetails retrieveKeyDetails(AsymmetricKeys keyPair) {
    BigInteger modulus = null;//from   w  ww  . j  a v  a2 s  .co m
    BigInteger publicExponent = null;
    BigInteger privateExponent = null;

    try {
        // Public key
        if (keyPair.getPublicKey() != null) {
            AsymmetricKeyParameter key = keyPair.getPublicKey();

            if (!(key instanceof RSAKeyParameters)) {
                throw new SmallToolsException(
                        "The public key is not of type RSAKeyParameters. Type is " + key.getClass().getName());
            }

            RSAKeyParameters rsaKey = (RSAKeyParameters) key;
            modulus = rsaKey.getModulus();
            publicExponent = rsaKey.getExponent();
        }

        // Private key
        if (keyPair.getPrivateKey() != null) {
            AsymmetricKeyParameter key = keyPair.getPrivateKey();

            if (!(key instanceof RSAKeyParameters)) {
                throw new SmallToolsException(
                        "The private key is not of type RSAKeyParameters. Type is " + key.getClass().getName());
            }

            RSAKeyParameters rsaKey = (RSAKeyParameters) key;
            modulus = rsaKey.getModulus();
            privateExponent = rsaKey.getExponent();
        }

        return new RSAKeyDetails(modulus, publicExponent, privateExponent);

    } catch (SmallToolsException e) {
        throw e;
    } catch (Exception e) {
        throw new SmallToolsException("Could not retrieve the details", e);
    }

}

From source file:com.foilen.smalltools.crypt.bouncycastle.asymmetric.RSACrypt.java

License:Open Source License

@Override
public RSAKeyDetails retrieveKeyDetails(AsymmetricKeys keyPair) {

    RSAKeyDetails rsaKeyDetails = new RSAKeyDetails();

    try {//from   w ww  . j av a2  s  .c o  m
        // Public key
        if (keyPair.getPublicKey() != null) {
            AsymmetricKeyParameter key = keyPair.getPublicKey();

            if (!(key instanceof RSAKeyParameters)) {
                throw new SmallToolsException(
                        "The public key is not of type RSAKeyParameters. Type is " + key.getClass().getName());
            }

            RSAKeyParameters rsaKey = (RSAKeyParameters) key;
            rsaKeyDetails.setModulus(rsaKey.getModulus());
            rsaKeyDetails.setPublicExponent(rsaKey.getExponent());
        }

        // Private key
        if (keyPair.getPrivateKey() != null) {
            AsymmetricKeyParameter key = keyPair.getPrivateKey();
            if (!(key instanceof RSAKeyParameters)) {
                throw new SmallToolsException(
                        "The private key is not of type RSAKeyParameters. Type is " + key.getClass().getName());
            }

            RSAKeyParameters rsaKeyParameters = (RSAKeyParameters) key;
            rsaKeyDetails.setModulus(rsaKeyParameters.getModulus());
            rsaKeyDetails.setPrivateExponent(rsaKeyParameters.getExponent());

            // CRT parameters
            if (key instanceof RSAPrivateCrtKeyParameters) {
                RSAPrivateCrtKeyParameters rsaPrivateCrtKeyParameters = (RSAPrivateCrtKeyParameters) key;
                rsaKeyDetails.setCrt(true);
                rsaKeyDetails.setPrimeP(rsaPrivateCrtKeyParameters.getP());
                rsaKeyDetails.setPrimeQ(rsaPrivateCrtKeyParameters.getQ());
                rsaKeyDetails.setPrimeExponentP(rsaPrivateCrtKeyParameters.getDP());
                rsaKeyDetails.setPrimeExponentQ(rsaPrivateCrtKeyParameters.getDQ());
                rsaKeyDetails.setCrtCoefficient(rsaPrivateCrtKeyParameters.getQInv());
            }
        }

        return rsaKeyDetails;

    } catch (SmallToolsException e) {
        throw e;
    } catch (Exception e) {
        throw new SmallToolsException("Could not retrieve the details", e);
    }

}

From source file:com.foilen.smalltools.crypt.bouncycastle.cert.RSATools.java

License:Open Source License

/**
 * Create a {@link Key} from the public {@link AsymmetricKeys}.
 *
 * @param asymmetricKeys/* www  .  ja  v a  2  s  .  c  om*/
 *            the asymmetric keys
 * @return the Java key
 */
public static PublicKey createPublicKey(AsymmetricKeys asymmetricKeys) {
    try {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        RSAKeyParameters publicKeyParameters = (RSAKeyParameters) asymmetricKeys.getPublicKey();
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(publicKeyParameters.getModulus(),
                publicKeyParameters.getExponent());
        return keyFactory.generatePublic(keySpec);
    } catch (Exception e) {
        throw new SmallToolsException("Problem generating the key", e);
    }
}

From source file:com.geoxp.oss.CryptoHelperTest.java

License:Apache License

@Test
public void testSSHSignatureBlobSign_RSA() throws Exception {
    RSAKeyPairGenerator rsakpg = new RSAKeyPairGenerator();
    RSAKeyGenerationParameters params = new RSAKeyGenerationParameters(new BigInteger("35"), new SecureRandom(),
            2048, 8);//from  ww w  . j a v a  2  s  .  c  o m
    rsakpg.init(params);

    AsymmetricCipherKeyPair kp = rsakpg.generateKeyPair();

    RSAPrivateCrtKeyParameters privParams = (RSAPrivateCrtKeyParameters) kp.getPrivate();
    RSAKeyParameters pubParams = (RSAKeyParameters) kp.getPublic();

    KeySpec ks = new RSAPrivateKeySpec(privParams.getModulus(), privParams.getExponent());
    PrivateKey priv = KeyFactory.getInstance("RSA").generatePrivate(ks);

    ks = new RSAPublicKeySpec(pubParams.getModulus(), pubParams.getExponent());
    PublicKey pub = KeyFactory.getInstance("RSA").generatePublic(ks);

    byte[] data = PLAINTEXT.getBytes();
    byte[] sig = CryptoHelper.sshSignatureBlobSign(data, priv);

    Assert.assertTrue(CryptoHelper.sshSignatureBlobVerify(data, sig, pub));
}

From source file:com.licel.jcardsim.crypto.RSAKeyImpl.java

License:Apache License

/**
 * Construct and initialize rsa key with RSAKeyParameters. Use in
 * KeyPairImpl/*  ww w . j av  a2s  .  c om*/
 *
 * @see javacard.security.KeyPair
 * @see RSAKeyParameters
 * @param params key params from BouncyCastle API
 */
public RSAKeyImpl(RSAKeyParameters params) {
    this(params.isPrivate(), (short) params.getModulus().bitLength());
    setParameters(params);
}

From source file:com.raphfrk.craftproxyclient.net.protocol.p16x.P16xProtocol.java

License:Open Source License

public byte[] encodeRSAPublicKey(RSAKeyParameters key) {
    if (((RSAKeyParameters) key).isPrivate()) {
        return null;
    }//  www  . ja va 2s.com

    RSAKeyParameters rsaKey = (RSAKeyParameters) key;

    ASN1EncodableVector encodable = new ASN1EncodableVector();
    encodable.add(new ASN1Integer(rsaKey.getModulus()));
    encodable.add(new ASN1Integer(rsaKey.getExponent()));

    return KeyUtil.getEncodedSubjectPublicKeyInfo(
            new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE),
            new DERSequence(encodable));
}

From source file:com.sun.midp.crypto.BouncyCastleRSAPrivateKey.java

License:Open Source License

public BouncyCastleRSAPrivateKey(RSAKeyParameters keyParam) {
    rsaPrivateKey = new RSAPrivateKey(BigIntegers.asUnsignedByteArray(keyParam.getModulus()),
            BigIntegers.asUnsignedByteArray(keyParam.getExponent()));
}