Example usage for java.security KeyPair getPrivate

List of usage examples for java.security KeyPair getPrivate

Introduction

In this page you can find the example usage for java.security KeyPair getPrivate.

Prototype

public PrivateKey getPrivate() 

Source Link

Document

Returns a reference to the private key component of this key pair.

Usage

From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java

@Test
public void test07ExpiredRACert()
        throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException,
        EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception {
    log.info(">test07ExpiredRACert()");

    //------------------- Creating Certificate Request ---------------
    //PKIMessage crmfMsg = createEESignedCrmfReq(this.subjectDN);
    byte[] senderNonce = CmpMessageHelper.createSenderNonce();
    byte[] transactionID = CmpMessageHelper.createSenderNonce();
    Date nb = new Date((new Date()).getTime() - 31536000000L); // not before a year ago
    Date na = new Date((new Date()).getTime() + 31536000000L); // not afer a yeat from now
    assertNotNull(nb);/*from   ww  w. java2  s.  c  o m*/
    assertNotNull(na);

    KeyPair keys = null;
    keys = KeyTools.genKeys("1024", "RSA");
    PKIMessage crmfMsg = genCertReq(this.issuerDN, SUBJECT_DN, keys, this.cacert, senderNonce, transactionID,
            false, null, nb, na, null, null, null);
    assertNotNull("Failed to create crmfMsg.", crmfMsg);

    // ---------------- Creating the NestedMessageContent ----------------------

    final X500Name reqSubjectDN = new X500Name("CN=bogusSubjectNested");
    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(reqSubjectDN),
            new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName())));
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setRecipNonce(new DEROctetString(nonce));

    PKIBody myPKIBody = new PKIBody(20, crmfMsg); // NestedMessageContent
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    KeyPair raKeys = KeyTools.genKeys("1024", "RSA");

    long nbTime = (new Date()).getTime() - 1000000L;
    createRACertificate("raExpiredSignerTest07", "foo123", this.raCertsPath, cmpAlias, raKeys, new Date(nbTime),
            new Date(), CMPTESTPROFILE, this.caid);
    Thread.sleep(5000);
    myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(), null,
            "BC");

    assertNotNull("Failed to create myPKIHeader", myPKIHeader);
    assertNotNull("myPKIBody is null", myPKIBody);
    assertNotNull("myPKIMessage is null", myPKIMessage);

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(myPKIMessage);
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
    //final byte[] resp = sendCmpHttp(myPKIMessage.toASN1Primitive().toASN1Object().getEncoded(), 200);
    // do not check signing if we expect a failure (sFailMessage==null)

    checkCmpResponseGeneral(resp, this.issuerDN, reqSubjectDN, this.cacert,
            myPKIMessage.getHeader().getSenderNonce().getOctets(),
            myPKIMessage.getHeader().getTransactionID().getOctets(), false, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    PKIBody body = respObject.getBody();
    assertEquals(23, body.getType());
    ErrorMsgContent err = (ErrorMsgContent) body.getContent();
    String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    assertEquals("Wrong error message",
            "Could not verify the RA, signature verification on NestedMessageContent failed.", errMsg);
    log.info("<test07ExpiredRACert()");
}

From source file:com.google.examples.JOSEToolBase.java

public static PrivateKey decodePrivateKey(String privateKeyString, String password) throws KeyParseException {
    try {//from ww  w  .  j ava 2s .  co  m
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
        privateKeyString = reformIndents(privateKeyString);
        PEMParser pemParser = new PEMParser(new StringReader(privateKeyString));
        Object object = pemParser.readObject();
        if (object == null) {
            throw new KeyParseException("unable to read anything when decoding private key");
        }

        KeyPair kp = null;

        //LOGGER.info(String.format("decodePrivateKey, %s", object.getClass().getName()));
        if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
            // produced by "openssl genpkey" or  the series of commands reqd to sign an ec key
            //LOGGER.info("decodePrivateKey, encrypted PrivateKeyInfo");
            PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
            JceOpenSSLPKCS8DecryptorProviderBuilder decryptorProviderBuilder = new JceOpenSSLPKCS8DecryptorProviderBuilder();
            InputDecryptorProvider decryptorProvider = decryptorProviderBuilder.build(password.toCharArray());
            PrivateKeyInfo privateKeyInfo = pkcs8EncryptedPrivateKeyInfo
                    .decryptPrivateKeyInfo(decryptorProvider);
            return (PrivateKey) converter.getPrivateKey(privateKeyInfo);
        }

        if (object instanceof PrivateKeyInfo) {
            // produced by openssl genpkey without encryption
            return (PrivateKey) converter.getPrivateKey((PrivateKeyInfo) object);
        }

        if (object instanceof PEMEncryptedKeyPair) {
            // produced by "openssl genrsa" or "openssl ec -genkey"
            // LOGGER.info("decodePrivateKey, encrypted keypair");
            PEMEncryptedKeyPair encryptedKeyPair = (PEMEncryptedKeyPair) object;
            PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder()
                    .build(password.toCharArray());
            kp = converter.getKeyPair(encryptedKeyPair.decryptKeyPair(decryptorProvider));
        } else if (object instanceof PEMKeyPair) {
            //LOGGER.info("decodePrivateKey, un-encrypted keypair");
            PEMKeyPair unencryptedKeyPair = (PEMKeyPair) object;
            kp = converter.getKeyPair(unencryptedKeyPair);
        } else {
            //LOGGER.error("decodePrivateKey, unknown object type {}", object.getClass().getName());
            throw new KeyParseException("unknown object type when decoding private key");
        }

        return (PrivateKey) kp.getPrivate();
    } catch (KeyParseException exc0) {
        throw exc0;
    } catch (Exception exc1) {
        throw new KeyParseException("cannot instantiate private key", exc1);
    }
}

From source file:com.trsst.Command.java

private static final X509Certificate createCertificate(KeyPair keyPair, String algorithm) {
    org.bouncycastle.x509.X509V3CertificateGenerator certGen = new org.bouncycastle.x509.X509V3CertificateGenerator();

    long now = System.currentTimeMillis();
    certGen.setSerialNumber(java.math.BigInteger.valueOf(now));

    org.bouncycastle.jce.X509Principal subject = new org.bouncycastle.jce.X509Principal(
            "CN=Trsst Keystore,DC=trsst,DC=com");
    certGen.setIssuerDN(subject);//from w  ww.ja  v a2  s .c om
    certGen.setSubjectDN(subject);

    Date fromDate = new java.util.Date(now);
    certGen.setNotBefore(fromDate);
    Calendar cal = new java.util.GregorianCalendar();
    cal.setTime(fromDate);
    cal.add(java.util.Calendar.YEAR, 100);
    Date toDate = cal.getTime();
    certGen.setNotAfter(toDate);

    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm(algorithm);
    certGen.addExtension(org.bouncycastle.asn1.x509.X509Extensions.BasicConstraints, true,
            new org.bouncycastle.asn1.x509.BasicConstraints(false));
    certGen.addExtension(org.bouncycastle.asn1.x509.X509Extensions.KeyUsage, true,
            new org.bouncycastle.asn1.x509.KeyUsage(org.bouncycastle.asn1.x509.KeyUsage.digitalSignature
                    | org.bouncycastle.asn1.x509.KeyUsage.keyEncipherment
                    | org.bouncycastle.asn1.x509.KeyUsage.keyCertSign
                    | org.bouncycastle.asn1.x509.KeyUsage.cRLSign));
    X509Certificate x509 = null;
    try {
        x509 = certGen.generateX509Certificate(keyPair.getPrivate());
    } catch (InvalidKeyException e) {
        log.error("Error generating certificate: invalid key", e);
    } catch (SecurityException e) {
        log.error("Unexpected error generating certificate", e);
    } catch (SignatureException e) {
        log.error("Error generating generating certificate signature", e);
    }
    return x509;
}

From source file:ai.susi.server.api.aaa.PublicKeyRegistrationService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization,
        final JsonObjectWithDefault permissions) throws APIException {

    if (post.get("register", null) == null && !post.get("create", false) && !post.get("getParameters", false)) {
        throw new APIException(400, "Accepted parameters: 'register', 'create' or 'getParameters'");
    }//w ww. ja v  a  2s  .  com

    JSONObject result = new JSONObject();

    // return algorithm parameters and users for whom we are allowed to register a key
    if (post.get("getParameters", false)) {
        result.put("self", permissions.getBoolean("self", false));
        result.put("users", permissions.getJSONObject("users"));
        result.put("userRoles", permissions.getJSONObject("userRoles"));

        JSONObject algorithms = new JSONObject();

        JSONObject rsa = new JSONObject();
        JSONArray keySizes = new JSONArray();
        for (int i : allowedKeySizesRSA) {
            keySizes.put(i);
        }
        rsa.put("sizes", keySizes);
        rsa.put("defaultSize", defaultKeySizeRSA);
        algorithms.put("RSA", rsa);
        result.put("algorithms", algorithms);

        JSONArray formats = new JSONArray();
        for (String format : allowedFormats) {
            formats.put(format);
        }
        result.put("formats", formats);

        return result;
    }

    // for which id?
    String id;
    if (post.get("id", null) != null)
        id = post.get("id", null);
    else
        id = authorization.getIdentity().getName();

    // check if we are allowed register a key
    if (!id.equals(authorization.getIdentity().getName())) { // if we don't want to register the key for the current user

        // create Authentication to check if the user id is a registered user
        ClientCredential credential = new ClientCredential(ClientCredential.Type.passwd_login, id);
        Authentication authentication = new Authentication(credential, DAO.authentication);

        if (authentication.getIdentity() == null) { // check if identity is valid
            authentication.delete();
            throw new APIException(400, "Bad request"); // do not leak if user exists or not
        }

        // check if the current user is allowed to create a key for the user in question
        boolean allowed = false;
        // check if the user in question is in 'users'
        if (permissions.getJSONObject("users", null).has(id)
                && permissions.getJSONObjectWithDefault("users", null).getBoolean(id, false)) {
            allowed = true;
        } else { // check if the user role of the user in question is in 'userRoles'
            Authorization auth = new Authorization(authentication.getIdentity(), DAO.authorization,
                    DAO.userRoles);
            for (String key : permissions.getJSONObject("userRoles").keySet()) {
                if (key.equals(auth.getUserRole().getName())
                        && permissions.getJSONObject("userRoles").getBoolean(key)) {
                    allowed = true;
                }
            }
        }
        if (!allowed)
            throw new APIException(400, "Bad request"); // do not leak if user exists or not
    } else { // if we want to register a key for this user, bad are not allowed to (for example anonymous users)
        if (!permissions.getBoolean("self", false))
            throw new APIException(403, "You are not allowed to register a public key");
    }

    // set algorithm. later, we maybe want to support other algorithms as well
    String algorithm = "RSA";
    if (post.get("algorithm", null) != null) {
        algorithm = post.get("algorithm", null);
    }

    if (post.get("create", false)) { // create a new key pair on the server

        if (algorithm.equals("RSA")) {
            int keySize = 2048;
            if (post.get("key-size", null) != null) {
                int finalKeyLength = post.get("key-size", 0);
                if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == finalKeyLength)) {
                    throw new APIException(400, "Invalid key size.");
                }
                keySize = finalKeyLength;
            }

            KeyPairGenerator keyGen;
            KeyPair keyPair;
            try {
                keyGen = KeyPairGenerator.getInstance(algorithm);
                keyGen.initialize(keySize);
                keyPair = keyGen.genKeyPair();
            } catch (NoSuchAlgorithmException e) {
                throw new APIException(500, "Server error");
            }

            registerKey(authorization.getIdentity(), keyPair.getPublic());

            String pubkey_pem = null, privkey_pem = null;
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                pubkey_pem = writer.toString();
            } catch (IOException e) {
            }
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PRIVATE KEY", keyPair.getPrivate().getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                privkey_pem = writer.toString();
            } catch (IOException e) {
            }

            result.put("publickey_DER_BASE64",
                    Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()));
            result.put("privatekey_DER_BASE64",
                    Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()));
            result.put("publickey_PEM", pubkey_pem);
            result.put("privatekey_PEM", privkey_pem);
            result.put("keyhash", IO.getKeyHash(keyPair.getPublic()));
            try {
                result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(keyPair.getPublic()), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            }
            result.put("key-size", keySize);
            result.put("message",
                    "Successfully created and registered key. Make sure to copy the private key, it won't be saved on the server");

            return result;
        }
        throw new APIException(400, "Unsupported algorithm");
    } else if (post.get("register", null) != null) {

        if (algorithm.equals("RSA")) {
            String type = post.get("type", null);
            if (type == null)
                type = "DER";

            RSAPublicKey pub;
            String encodedKey;
            try {
                encodedKey = URLDecoder.decode(post.get("register", null), "UTF-8");
            } catch (Throwable e) {
                throw new APIException(500, "Server error");
            }
            Log.getLog().info("Key (" + type + "): " + encodedKey);

            if (type.equals("DER")) {
                try {
                    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(encodedKey));
                    pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec);
                } catch (Throwable e) {
                    throw new APIException(400, "Public key not readable (DER)");
                }
            } else if (type.equals("PEM")) {
                try {
                    PemReader pemReader = new PemReader(new StringReader(encodedKey));
                    PemObject pem = pemReader.readPemObject();
                    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pem.getContent());
                    pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec);
                } catch (Exception e) {
                    throw new APIException(400, "Public key not readable (PEM)");
                }
            } else {
                throw new APIException(400, "Invalid value for 'type'.");
            }

            // check key size (not really perfect yet)
            int keySize;
            int bitLength = pub.getModulus().bitLength();
            if (bitLength <= 512) {
                keySize = 512;
            } else if (bitLength <= 1024) {
                keySize = 1024;
            } else if (bitLength <= 2048) {
                keySize = 2048;
            } else if (bitLength <= 4096) {
                keySize = 4096;
            } else {
                keySize = 8192;
            }
            if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == keySize)) {
                throw new APIException(400, "Invalid key length.");
            }

            registerKey(authorization.getIdentity(), pub);

            String pubkey_pem = null;
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PUBLIC KEY", pub.getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                pubkey_pem = writer.toString();
            } catch (IOException e) {
            }

            result.put("publickey_DER_BASE64", Base64.getEncoder().encodeToString(pub.getEncoded()));
            result.put("publickey_PEM", pubkey_pem);
            result.put("keyhash", IO.getKeyHash(pub));
            try {
                result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(pub), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            }
            result.put("message", "Successfully registered key.");

            return result;
        }
        throw new APIException(400, "Unsupported algorithm");
    }

    throw new APIException(400, "Invalid parameter");
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.MockX509SecurityHandler.java

@Override
public X509SecurityManagerMaterial generateMaterial(X509MaterialParameter materialParameter) throws Exception {
    ApplicationId appId = materialParameter.getApplicationId();
    String appUser = materialParameter.getAppUser();
    Integer cryptoMaterialVersion = materialParameter.getCryptoMaterialVersion();

    KeyPair keyPair = generateKeyPair();
    PKCS10CertificationRequest csr = generateCSR(appId, appUser, keyPair, cryptoMaterialVersion);
    assertEquals(appUser, HopsUtil.extractCNFromSubject(csr.getSubject().toString()));
    assertEquals(appId.toString(), HopsUtil.extractOFromSubject(csr.getSubject().toString()));
    assertEquals(String.valueOf(cryptoMaterialVersion),
            HopsUtil.extractOUFromSubject(csr.getSubject().toString()));

    // Sign CSR//from   w w  w  .ja  va 2 s.  c o m
    CertificateBundle certificateBundle = sendCSRAndGetSigned(csr);
    certificateBundle.getCertificate().checkValidity();
    long expiration = certificateBundle.getCertificate().getNotAfter().getTime();
    long epochNow = DateUtils.localDateTime2UnixEpoch(DateUtils.getNow());
    assertTrue(expiration >= epochNow);
    assertNotNull(certificateBundle.getIssuer());
    RMAppSecurityActions actor = getRmAppSecurityActions();
    if (actor instanceof TestingRMAppSecurityActions) {
        X509Certificate caCert = ((TestingRMAppSecurityActions) actor).getCaCert();
        certificateBundle.getCertificate().verify(caCert.getPublicKey(), "BC");
    }
    certificateBundle.getCertificate().verify(certificateBundle.getIssuer().getPublicKey(), "BC");

    KeyStoresWrapper appKeystores = createApplicationStores(certificateBundle, keyPair.getPrivate(), appUser,
            appId);
    X509Certificate extractedCert = (X509Certificate) appKeystores.getKeystore().getCertificate(appUser);
    byte[] rawKeystore = appKeystores.getRawKeyStore(TYPE.KEYSTORE);
    assertNotNull(rawKeystore);
    assertNotEquals(0, rawKeystore.length);

    File keystoreFile = Paths.get(systemTMP, appUser + "-" + appId.toString() + "_kstore.jks").toFile();
    // Keystore should have been deleted
    assertFalse(keystoreFile.exists());
    char[] keyStorePassword = appKeystores.getKeyStorePassword();
    assertNotNull(keyStorePassword);
    assertNotEquals(0, keyStorePassword.length);

    byte[] rawTrustStore = appKeystores.getRawKeyStore(TYPE.TRUSTSTORE);
    File trustStoreFile = Paths.get(systemTMP, appUser + "-" + appId.toString() + "_tstore.jks").toFile();
    // Truststore should have been deleted
    assertFalse(trustStoreFile.exists());
    char[] trustStorePassword = appKeystores.getTrustStorePassword();
    assertNotNull(trustStorePassword);
    assertNotEquals(0, trustStorePassword.length);

    verifyContentOfAppTrustStore(rawTrustStore, trustStorePassword, appUser, appId);

    if (actor instanceof TestingRMAppSecurityActions) {
        X509Certificate caCert = ((TestingRMAppSecurityActions) actor).getCaCert();
        extractedCert.verify(caCert.getPublicKey(), "BC");
    }
    assertEquals(appUser, HopsUtil.extractCNFromSubject(extractedCert.getSubjectX500Principal().getName()));
    assertEquals(appId.toString(),
            HopsUtil.extractOFromSubject(extractedCert.getSubjectX500Principal().getName()));
    assertEquals(String.valueOf(cryptoMaterialVersion),
            HopsUtil.extractOUFromSubject(extractedCert.getSubjectX500Principal().getName()));
    return new X509SecurityManagerMaterial(appId, rawKeystore, appKeystores.getKeyStorePassword(),
            rawTrustStore, appKeystores.getTrustStorePassword(), expiration);
}

From source file:org.ejbca.core.model.ca.caadmin.extendedcaservices.CmsCAService.java

@Override
public void init(final CryptoToken cryptoToken, final CA ca,
        final AvailableCustomCertificateExtensionsConfiguration cceConfig) throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">init");
    }// w  ww . ja  v a2s.c o m
    if (info.getStatus() != ExtendedCAServiceInfo.STATUS_ACTIVE) {
        if (log.isDebugEnabled()) {
            log.debug("Not generating certificates for inactive service");
        }
    } else {
        // lookup keystore passwords      
        final String keystorepass = StringTools.passwordDecryption(EjbcaConfiguration.getCaCmsKeyStorePass(),
                "ca.cmskeystorepass");
        // Currently only RSA keys are supported
        final CmsCAServiceInfo info = (CmsCAServiceInfo) getExtendedCAServiceInfo();
        // Create KeyStore       
        final KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
        keystore.load(null, null);
        final KeyPair cmskeys = KeyTools.genKeys(info.getKeySpec(), info.getKeyAlgorithm());
        // A simple hard coded certificate profile that works for the CMS CA service
        final CertificateProfile certProfile = new CertificateProfile(
                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        certProfile.setUseKeyUsage(true);
        certProfile.setKeyUsage(new boolean[9]);
        certProfile.setKeyUsage(CertificateConstants.DIGITALSIGNATURE, true);
        certProfile.setKeyUsage(CertificateConstants.KEYENCIPHERMENT, true);
        certProfile.setKeyUsage(CertificateConstants.DATAENCIPHERMENT, true);
        certProfile.setKeyUsageCritical(true);
        final EndEntityInformation eeInformation = new EndEntityInformation("NOUSERNAME", info.getSubjectDN(),
                0, info.getSubjectAltName(), "NOEMAIL", 0, new EndEntityType(), 0, 0, null, null, 0, 0, null);
        final Certificate certificate = ca.generateCertificate(cryptoToken, eeInformation, cmskeys.getPublic(),
                -1, null, ca.getEncodedValidity(), certProfile, null, cceConfig);
        certificatechain = new ArrayList<Certificate>();
        certificatechain.add(certificate);
        certificatechain.addAll(ca.getCertificateChain());
        privKey = cmskeys.getPrivate();
        keystore.setKeyEntry(PRIVATESIGNKEYALIAS, cmskeys.getPrivate(), null,
                (Certificate[]) certificatechain.toArray(new Certificate[certificatechain.size()]));
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        keystore.store(baos, keystorepass.toCharArray());
        data.put(KEYSTORE, new String(Base64.encode(baos.toByteArray())));
    }
    setStatus(info.getStatus());
    this.info = new CmsCAServiceInfo(info.getStatus(), getSubjectDN(), getSubjectAltName(),
            (String) data.get(KEYSPEC), (String) data.get(KEYALGORITHM), certificatechain);
    if (log.isTraceEnabled()) {
        log.trace("<init");
    }
}

From source file:org.ejbca.core.protocol.ws.EjbcaWSTest.java

/**
 * Tests that the provided cardnumber is stored in the EndEntityInformation 
 * and that when querying for EndEntityInformation the cardnumber is 
 * returned.//from w  ww .  j  a  v a2s .  c  o  m
 * @throws Exception in case of error
 */
@Test
public void test48CertificateRequestWithCardNumber() throws Exception {
    String userName = "wsRequestCardNumber" + new SecureRandom().nextLong();

    // Generate a CSR
    KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);
    PKCS10CertificationRequest pkcs10 = CertTools.genPKCS10CertificationRequest("SHA256WithRSA",
            CertTools.stringToBcX500Name("CN=NOUSED"), keys.getPublic(), new DERSet(), keys.getPrivate(), null);
    final String csr = new String(Base64.encode(pkcs10.toASN1Structure().getEncoded()));

    // Set some user data
    final UserDataVOWS userData = new UserDataVOWS();
    userData.setUsername(userName);
    userData.setPassword(PASSWORD);
    userData.setClearPwd(true);
    userData.setSubjectDN("CN=test" + secureRandom.nextLong() + ", UID=" + userName + ", O=Test, C=SE");
    userData.setCaName(getAdminCAName());
    userData.setEmail(null);
    userData.setSubjectAltName(null);
    userData.setStatus(UserDataVOWS.STATUS_NEW);
    userData.setTokenType(UserDataVOWS.TOKEN_TYPE_P12);
    userData.setEndEntityProfileName("EMPTY");
    userData.setCertificateProfileName("ENDUSER");

    // Set the card number
    userData.setCardNumber("1234fa");

    // Issue a certificate
    CertificateResponse response = ejbcaraws.certificateRequest(userData, csr,
            CertificateHelper.CERT_REQ_TYPE_PKCS10, null, CertificateHelper.RESPONSETYPE_CERTIFICATE);
    assertNotNull("null response", response);

    // Check that the cardnumber was stored in the EndEntityInformation
    EndEntityInformation endEntity = endEntityAccessSession.findUser(intAdmin, userName);
    assertEquals("stored cardnumber ejb", "1234fa", endEntity.getCardNumber());

    // Check that the cardnumber is also available when querying using WS
    UserMatch criteria = new UserMatch();
    criteria.setMatchtype(UserMatch.MATCH_TYPE_EQUALS);
    criteria.setMatchwith(UserMatch.MATCH_WITH_USERNAME);
    criteria.setMatchvalue(userName);
    UserDataVOWS user = ejbcaraws.findUser(criteria).get(0);
    assertEquals("stored cardnumber ws", "1234fa", user.getCardNumber());
}

From source file:org.ejbca.core.protocol.ws.EjbcaWSTest.java

/**
 * Creates a "hardtoken" with certficates.
 *//*from w  w  w.j a v  a2  s.  co m*/
private void createHardToken(String username, String caName, String serialNumber) throws Exception {
    GlobalConfiguration gc = (GlobalConfiguration) globalConfigurationSession
            .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID);
    boolean originalProfileSetting = gc.getEnableEndEntityProfileLimitations();
    gc.setEnableEndEntityProfileLimitations(false);
    globalConfigurationSession.saveConfiguration(intAdmin, gc);
    if (certificateProfileSession.getCertificateProfileId(WS_TEST_CERTIFICATE_PROFILE_NAME) != 0) {
        certificateProfileSession.removeCertificateProfile(intAdmin, WS_TEST_CERTIFICATE_PROFILE_NAME);
    }
    CertificateProfile profile = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    profile.setAllowValidityOverride(true);
    certificateProfileSession.addCertificateProfile(intAdmin, WS_TEST_CERTIFICATE_PROFILE_NAME, profile);
    UserDataVOWS tokenUser1 = new UserDataVOWS();
    tokenUser1.setUsername(username);
    tokenUser1.setPassword(PASSWORD);
    tokenUser1.setClearPwd(true);
    tokenUser1.setSubjectDN("CN=" + username);
    tokenUser1.setCaName(caName);
    tokenUser1.setEmail(null);
    tokenUser1.setSubjectAltName(null);
    tokenUser1.setStatus(UserDataVOWS.STATUS_NEW);
    tokenUser1.setTokenType(UserDataVOWS.TOKEN_TYPE_USERGENERATED);
    tokenUser1.setEndEntityProfileName("EMPTY");
    tokenUser1.setCertificateProfileName("ENDUSER");
    KeyPair basickeys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);
    PKCS10CertificationRequest basicpkcs10 = CertTools.genPKCS10CertificationRequest("SHA256WithRSA",
            CertTools.stringToBcX500Name("CN=NOTUSED"), basickeys.getPublic(), new DERSet(),
            basickeys.getPrivate(), null);
    ArrayList<TokenCertificateRequestWS> requests = new ArrayList<TokenCertificateRequestWS>();
    TokenCertificateRequestWS tokenCertReqWS = new TokenCertificateRequestWS();
    tokenCertReqWS.setCAName(caName);
    tokenCertReqWS.setCertificateProfileName(WS_TEST_CERTIFICATE_PROFILE_NAME);
    tokenCertReqWS.setValidityIdDays("1");
    tokenCertReqWS.setPkcs10Data(basicpkcs10.getEncoded());
    tokenCertReqWS.setType(HardTokenConstants.REQUESTTYPE_PKCS10_REQUEST);
    requests.add(tokenCertReqWS);
    tokenCertReqWS = new TokenCertificateRequestWS();
    tokenCertReqWS.setCAName(caName);
    tokenCertReqWS.setCertificateProfileName("ENDUSER");
    tokenCertReqWS.setKeyalg("RSA");
    tokenCertReqWS.setKeyspec("1024");
    tokenCertReqWS.setType(HardTokenConstants.REQUESTTYPE_KEYSTORE_REQUEST);
    requests.add(tokenCertReqWS);
    HardTokenDataWS hardTokenDataWS = new HardTokenDataWS();
    hardTokenDataWS.setLabel(HardTokenConstants.LABEL_PROJECTCARD);
    hardTokenDataWS.setTokenType(HardTokenConstants.TOKENTYPE_SWEDISHEID);
    hardTokenDataWS.setHardTokenSN(serialNumber);
    PinDataWS basicPinDataWS = new PinDataWS();
    basicPinDataWS.setType(HardTokenConstants.PINTYPE_BASIC);
    basicPinDataWS.setInitialPIN("1234");
    basicPinDataWS.setPUK("12345678");
    PinDataWS signaturePinDataWS = new PinDataWS();
    signaturePinDataWS.setType(HardTokenConstants.PINTYPE_SIGNATURE);
    signaturePinDataWS.setInitialPIN("5678");
    signaturePinDataWS.setPUK("23456789");
    hardTokenDataWS.getPinDatas().add(basicPinDataWS);
    hardTokenDataWS.getPinDatas().add(signaturePinDataWS);
    List<TokenCertificateResponseWS> responses = ejbcaraws.genTokenCertificates(tokenUser1, requests,
            hardTokenDataWS, true, false);
    assertTrue(responses.size() == 2);
    certificateProfileSession.removeCertificateProfile(intAdmin, WS_TEST_CERTIFICATE_PROFILE_NAME);
    gc.setEnableEndEntityProfileLimitations(originalProfileSetting);
    globalConfigurationSession.saveConfiguration(intAdmin, gc);
}

From source file:net.nicholaswilliams.java.licensing.encryption.TestRSAKeyPairGenerator.java

@Test
public void testSaveKeyPairToFiles01() throws IOException {
    KeyPair keyPair = this.generator.generateKeyPair();

    File file1 = new File("testSaveKeyPairToFiles01.private");
    File file2 = new File("testSaveKeyPairToFiles01.public");

    if (file1.exists())
        FileUtils.forceDelete(file1);/*from www  .  ja va  2 s.c  o  m*/

    if (file2.exists())
        FileUtils.forceDelete(file2);

    assertFalse("File 1 should not exist.", file1.exists());
    assertFalse("File 2 should not exist.", file2.exists());

    this.generator.saveKeyPairToFiles(keyPair, "testSaveKeyPairToFiles01.private",
            "testSaveKeyPairToFiles01.public", "testMyPassword01".toCharArray());

    assertTrue("File 1 should exist.", file1.exists());
    assertTrue("File 2 should exist.", file2.exists());

    PrivateKey privateKey = KeyFileUtilities.readEncryptedPrivateKey(file1, "testMyPassword01".toCharArray());
    PublicKey publicKey = KeyFileUtilities.readEncryptedPublicKey(file2, "testMyPassword01".toCharArray());

    assertNotNull("The private key should not be null.", privateKey);
    assertEquals("The private key is not correct.", keyPair.getPrivate(), privateKey);

    assertNotNull("The public key should not be null.", publicKey);
    assertEquals("The public key is not correct.", keyPair.getPublic(), publicKey);

    FileUtils.forceDelete(file1);
    FileUtils.forceDelete(file2);
}

From source file:org.ejbca.core.protocol.ws.EjbcaWSTest.java

private void testCertificateRequestWithEeiDnOverride(boolean allowDNOverrideByEndEntityInformation,
        boolean useCsr, String requestedSubjectDN, String expectedSubjectDN) throws Exception {
    if (certificateProfileSession.getCertificateProfileId(WS_TEST_CERTIFICATE_PROFILE_NAME) != 0) {
        certificateProfileSession.removeCertificateProfile(intAdmin, WS_TEST_CERTIFICATE_PROFILE_NAME);
    }// w w w  .j  a v a2 s.c o m
    CertificateProfile profile = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    profile.setAllowDNOverrideByEndEntityInformation(allowDNOverrideByEndEntityInformation);
    certificateProfileSession.addCertificateProfile(intAdmin, WS_TEST_CERTIFICATE_PROFILE_NAME, profile);
    //This test will fail if EEP limitations are enabled
    GlobalConfiguration originalConfiguration = (GlobalConfiguration) globalConfigurationSession
            .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID);
    GlobalConfiguration globalConfiguration = (GlobalConfiguration) globalConfigurationSession
            .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID);
    globalConfiguration.setEnableEndEntityProfileLimitations(false);
    globalConfigurationSession.saveConfiguration(intAdmin, globalConfiguration);
    try {
        String userName = "eeiDnOverride" + secureRandom.nextLong();
        final UserDataVOWS userData = new UserDataVOWS();
        userData.setUsername(userName);
        userData.setPassword(PASSWORD);
        userData.setClearPwd(true);
        userData.setSubjectDN(requestedSubjectDN);
        userData.setCaName(getAdminCAName());
        userData.setEmail(null);
        userData.setSubjectAltName(null);
        userData.setStatus(UserDataVOWS.STATUS_NEW);
        userData.setTokenType(UserDataVOWS.TOKEN_TYPE_P12);
        userData.setEndEntityProfileName("EMPTY");
        userData.setCertificateProfileName(WS_TEST_CERTIFICATE_PROFILE_NAME);
        final X509Certificate cert;
        if (useCsr) {
            KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);
            PKCS10CertificationRequest pkcs10 = CertTools.genPKCS10CertificationRequest("SHA256WithRSA",
                    CertTools.stringToBcX500Name("CN=NOUSED"), keys.getPublic(), new DERSet(),
                    keys.getPrivate(), null);
            final String csr = new String(Base64.encode(pkcs10.toASN1Structure().getEncoded()));
            CertificateResponse response = ejbcaraws.certificateRequest(userData, csr,
                    CertificateHelper.CERT_REQ_TYPE_PKCS10, null, CertificateHelper.RESPONSETYPE_CERTIFICATE);
            cert = response.getCertificate();
        } else {
            KeyStore ksenv = ejbcaraws.softTokenRequest(userData, null, "1024",
                    AlgorithmConstants.KEYALGORITHM_RSA);
            java.security.KeyStore keyStore = KeyStoreHelper.getKeyStore(ksenv.getKeystoreData(), "PKCS12",
                    PASSWORD);
            assertNotNull(keyStore);
            Enumeration<String> en = keyStore.aliases();
            String alias = en.nextElement();
            if (!keyStore.isKeyEntry(alias)) {
                alias = en.nextElement();
            }
            cert = (X509Certificate) keyStore.getCertificate(alias);
        }
        final List<Certificate> certificates = Arrays.asList(new Certificate[] { cert });
        log.info(certificates.size() + " certs.\n"
                + new String(CertTools.getPemFromCertificateChain(certificates)));
        X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
        String resultingSubjectDN = CeSecoreNameStyle.INSTANCE.toString(x500name);
        log.debug("x500name:           " + resultingSubjectDN);
        assertEquals("Unexpected transformation.", expectedSubjectDN, resultingSubjectDN);
        try {
            endEntityManagementSession.deleteUser(intAdmin, userName);
        } catch (NotFoundException e) {
            // Ignore
        }
    } finally {
        if (certificateProfileSession.getCertificateProfileId(WS_TEST_CERTIFICATE_PROFILE_NAME) != 0) {
            certificateProfileSession.removeCertificateProfile(intAdmin, WS_TEST_CERTIFICATE_PROFILE_NAME);
        }
        globalConfigurationSession.saveConfiguration(intAdmin, originalConfiguration);
    }
}