List of usage examples for java.security.cert X509Certificate getPublicKey
public abstract PublicKey getPublicKey();
From source file:org.tolven.connectors.passwordstore.PasswordStoreImpl.java
/** * Set password to have this alias// ww w . j ava2s. c om */ public String setPassword(String alias, char[] password) { String encryptedPassword; try { String keyStoreAlias = getKeyStore().aliases().nextElement(); X509Certificate x509Certificate = (X509Certificate) getKeyStore().getCertificate(keyStoreAlias); PublicKey publicKey = x509Certificate.getPublicKey(); Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encryptedBytes = cipher.doFinal(getBytes(password)); encryptedPassword = new String(Base64.encodeBase64(encryptedBytes), Charset.forName("UTF-8")); getEncryptedPasswordStore().getEncryptedPasswords().put(alias, encryptedPassword); } catch (Exception ex) { throw new RuntimeException("Could not set password for alias: " + alias, ex); } return encryptedPassword; }
From source file:org.tolven.key.bean.UserKeyBean.java
@Override public PublicKey getUserPublicKey(String uid, String realm) { X509Certificate x509Certificate = getUserX509Certificate(uid, realm); if (x509Certificate == null) { return null; } else {//from ww w . ja v a 2s . co m return x509Certificate.getPublicKey(); } }
From source file:org.tolven.restful.AccountResourcesV0.java
/** * Add a user to a Tolven account//from w w w.jav a 2 s.c om * The logged-in user must be a user on the account * Properties may also be added to the accountUser */ @Path("user/add") @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response addUser(@FormParam("user") String invitedUser, @FormParam("userX509Certificate") String invitedUserCertificate, @FormParam("account") String accountIdString, @FormParam("property") String property, @Context SecurityContext sc, MultivaluedMap<String, String> formParams) { if (invitedUser == null) { return Response.status(Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity("Missing User").build(); } if (accountIdString == null) { return Response.status(Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity("Missing Account Id") .build(); } Long accountId = null; try { accountId = Long.parseLong(accountIdString); } catch (Exception e) { return Response.status(Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity("Error parsing Account Id") .build(); } Account account = null; try { account = accountBean.findAccount(accountId); } catch (Exception e) { return Response.status(Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity("Invalid Account").build(); } // Make sure that the new user is not already an active member of the account AccountUser newAccountUser = accountBean.findAccountUser(invitedUser, accountId); if (newAccountUser != null) { return Response.status(Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN) .entity("User already a member of this account").build(); } Principal principal = request.getUserPrincipal(); AccountUser inviterAccountUser = accountBean.findAccountUser(principal.getName(), account.getId()); if (inviterAccountUser == null) { return Response.status(Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN) .entity("Inviting user must a member of this account").build(); } try { Date now = (Date) request.getAttribute("tolvenNow"); TolvenUser invitedTolvenUser = activationBean.findUser(invitedUser); if (invitedTolvenUser == null) { TolvenPerson tp = new TolvenPerson(); tp.setUid(invitedUser); invitedTolvenUser = loginBean.activate(tp, now); } String keyAlgorithm = propertyBean.getProperty(UserPrivateKey.USER_PRIVATE_KEY_ALGORITHM_PROP); TolvenSessionWrapper sessionWrapper = TolvenSessionWrapperFactory.getInstance(); PrivateKey inviterUserPrivateKey = sessionWrapper.getUserPrivateKey(keyAlgorithm); PublicKey invitedUserPublicKey = null; if (invitedUserCertificate != null) { byte[] userCertificateBytes = Base64 .decodeBase64(URLDecoder.decode(invitedUserCertificate, "UTF-8").getBytes("UTF-8")); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate x509Certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(userCertificateBytes)); invitedUserPublicKey = x509Certificate.getPublicKey(); } /* * A userPublicKey is required for the added user, in order to protect the AccountPrivateKey, which will be associated with them * A null key means their data will not be encrypted in the account */ newAccountUser = accountBean.inviteAccountUser(account, inviterAccountUser, invitedTolvenUser, "tolven", inviterUserPrivateKey, now, false); //, invitedUserPublicKey } catch (Exception ex) { return Response.status(Status.INTERNAL_SERVER_ERROR).type(MediaType.TEXT_PLAIN) .entity("Adding a user to an Account must be done by a user with a UserPublicKey").build(); } URI uri = null; try { uri = new URI(URLEncoder.encode(Long.toString(newAccountUser.getId()), "UTF-8")); } catch (Exception e) { return Response.status(Status.INTERNAL_SERVER_ERROR).type(MediaType.TEXT_PLAIN) .entity(ExceptionFormatter.toSimpleString(e, "\\n")).build(); } return Response.created(uri).type(MediaType.TEXT_PLAIN).entity(String.valueOf(newAccountUser.getId())) .build(); }
From source file:org.tolven.security.bean.DocProtectionBean.java
/** * Verify the document signature belongs to aPublicKey using aDecryptionKey * to decrypt the document/* w w w. j av a 2s . c om*/ * @param aPublicKey * @param aDecryptionKey * @return */ public boolean verify(DocumentSignature documentSignature, X509Certificate x509Certificate, AccountUser activeAccountUser, PrivateKey userPrivateKey) { try { Signature signature = Signature.getInstance(documentSignature.getSignatureAlgorithm()); signature.initVerify(x509Certificate.getPublicKey()); byte[] document = getDecryptedContent(documentSignature.getDocBase(), activeAccountUser, userPrivateKey); signature.update(document); return signature.verify(documentSignature.getSignature()); } catch (Exception ex) { throw new RuntimeException("Could not verify the signature", ex); } }
From source file:org.tolven.session.OpenAMSessionWrapper.java
@Override public PublicKey getUserPublicKey() { X509Certificate x509Certificate = getUserX509Certificate(); if (x509Certificate == null) { return null; } else {/*from ww w .jav a 2s .c om*/ return x509Certificate.getPublicKey(); } }
From source file:org.viafirma.util.XmlSignUtil.java
/** * Genera un XMLSignature de tipo Enveloped firmado por el alias indicado. * // w ww.j av a 2 s . co m * @parm documeto Documento a firmar * @param alias * Alias del certificado utilizado. * @throws ExcepcionErrorInterno * No se ha podido generar la firma del documento * @throws ExcepcionCertificadoNoEncontrado * No existe el alias */ public Document signDocument(Documento documento, String alias, String password) throws ExcepcionErrorInterno, ExcepcionCertificadoNoEncontrado { // Recuperamos el certificado que vamos a utilizar PrivateKey privateKey; try { if (alias == null) { throw new ExcepcionCertificadoNoEncontrado("Alias indicado incorrecto"); } privateKey = KeyStoreLoader.getPrivateKey(alias, password); if (privateKey == null) { throw new ExcepcionCertificadoNoEncontrado( "No existe una clave privada para el alias '" + alias + "'"); } log.info("Firmando el documento con el certificado " + alias); // Creamos el documento que se convertira en un XMLSignature javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.newDocument(); // Preparamos la estructura para la firma XML Signature XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_RSA); doc.appendChild(sig.getElement()); // Aadimos los datos a firmar al documento String idAttachment = "attachment-0"; ObjectContainer obj2 = new ObjectContainer(doc); obj2.setEncoding("base64"); obj2.setId(idAttachment); obj2.setMimeType(documento.getTipo().getMimetype()); obj2.addBase64Text(documento.getDatos()); sig.appendObject(obj2); // Creamos el tansformador a XMlSignature Transforms transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS); sig.addDocument("#" + idAttachment, transforms, Constants.ALGO_ID_DIGEST_SHA1); // Aadimos la informacin del certificado usado X509Certificate certificado = KeyStoreLoader.getCertificate(alias); // Aadimos la informacin del firmante sig.addKeyInfo(certificado); sig.addKeyInfo(certificado.getPublicKey()); // Firmamos el documento sig.sign(privateKey); log.debug("Firma completada."); return sig.getDocument(); } catch (ExcepcionErrorInterno e) { throw e; } catch (ParserConfigurationException e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_MANEJO_CERTIFICADO, "No se puede genera el XMLSignature.", e); } catch (XMLSecurityException e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_MANEJO_CERTIFICADO, "No se puede genera el XMLSignature.", e); } }
From source file:org.warlock.itk.distributionenvelope.Payload.java
/** * Carries out the cryptographic part of signature verification on a parsed * "Signature" element./*from w ww .j ava2 s .c o m*/ * @param signature * @throws Exception */ private void verifySignature(Element signature) throws Exception { X509Certificate x509 = getCertificate(signature); SimpleKeySelector sks = new SimpleKeySelector(); sks.setFixedKey(x509.getPublicKey()); DOMStructure sig = new DOMStructure(signature); XMLSignatureFactory xsf = XMLSignatureFactory.getInstance("DOM"); DOMValidateContext dvc = new DOMValidateContext(sks, signature); dvc.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE); XMLSignature xmlsig = xsf.unmarshalXMLSignature(sig); boolean isvalid = xmlsig.validate(dvc); if (!isvalid) { throw new Exception("Signature invalid"); } }
From source file:org.wildfly.security.x500.cert.acme.AcmeClientSpiTest.java
private void obtainCertificateChain(String keyAlgorithmName, int keySize, AcmeAccount account, String domainName) throws Exception { X509CertificateChainAndSigningKey certificateChainAndSigningKey = acmeClient.obtainCertificateChain(account, false, keyAlgorithmName, keySize, domainName); PrivateKey privateKey = certificateChainAndSigningKey.getSigningKey(); X509Certificate[] replyCertificates = certificateChainAndSigningKey.getCertificateChain(); assertTrue(replyCertificates.length == 2); X509Certificate signedCert = replyCertificates[0]; X509Certificate caCert = replyCertificates[1]; assertTrue(signedCert.getSubjectDN().getName().contains(domainName)); assertEquals(caCert.getSubjectDN(), signedCert.getIssuerDN()); assertEquals("CN=cackling cryptographer fake ROOT", caCert.getIssuerDN().getName()); if (keyAlgorithmName != null && keySize != -1) { assertEquals(keyAlgorithmName, privateKey.getAlgorithm()); assertEquals(keyAlgorithmName, signedCert.getPublicKey().getAlgorithm()); if (keyAlgorithmName.equals("EC")) { assertEquals(keySize,//from ww w. ja va 2 s .c o m ((ECPublicKey) signedCert.getPublicKey()).getParams().getCurve().getField().getFieldSize()); } else if (keyAlgorithmName.equals("RSA")) { assertEquals(keySize, ((RSAPublicKey) signedCert.getPublicKey()).getModulus().bitLength()); } } else { if (signedCert.getPublicKey().getAlgorithm().equals("RSA")) { assertEquals(AcmeClientSpi.DEFAULT_KEY_SIZE, ((RSAPublicKey) signedCert.getPublicKey()).getModulus().bitLength()); assertEquals("RSA", privateKey.getAlgorithm()); } else if (signedCert.getPublicKey().getAlgorithm().equals("EC")) { assertEquals(AcmeClientSpi.DEFAULT_EC_KEY_SIZE, ((RSAPublicKey) signedCert.getPublicKey()).getModulus().bitLength()); assertEquals("EC", privateKey.getAlgorithm()); } } }
From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java
public X509Certificate generateX509Certificate() throws KeystoreException { CommonUtil commonUtil = new CommonUtil(); Date validityBeginDate = commonUtil.getValidityStartDate(); Date validityEndDate = commonUtil.getValidityEndDate(); Security.addProvider(new BouncyCastleProvider()); try {/* w w w. j a va 2 s . c om*/ KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(CertificateManagementConstants.RSA, CertificateManagementConstants.PROVIDER); keyPairGenerator.initialize(CertificateManagementConstants.RSA_KEY_LENGTH, new SecureRandom()); KeyPair pair = keyPairGenerator.generateKeyPair(); X500Principal principal = new X500Principal(CertificateManagementConstants.DEFAULT_PRINCIPAL); X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(principal, CommonUtil.generateSerialNumber(), validityBeginDate, validityEndDate, principal, pair.getPublic()); ContentSigner contentSigner = new JcaContentSignerBuilder(CertificateManagementConstants.SHA256_RSA) .setProvider(CertificateManagementConstants.PROVIDER).build(pair.getPrivate()); X509Certificate certificate = new JcaX509CertificateConverter() .setProvider(CertificateManagementConstants.PROVIDER) .getCertificate(certificateBuilder.build(contentSigner)); // cert.checkValidity(); certificate.verify(certificate.getPublicKey()); List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> certificates = new ArrayList<>(); org.wso2.carbon.certificate.mgt.core.bean.Certificate certificateToStore = new org.wso2.carbon.certificate.mgt.core.bean.Certificate(); certificateToStore.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); certificateToStore.setCertificate(certificate); certificates.add(certificateToStore); saveCertInKeyStore(certificates); return certificate; } catch (NoSuchAlgorithmException e) { String errorMsg = "No such algorithm found when generating certificate"; throw new KeystoreException(errorMsg, e); } catch (NoSuchProviderException e) { String errorMsg = "No such provider found when generating certificate"; throw new KeystoreException(errorMsg, e); } catch (OperatorCreationException e) { String errorMsg = "Issue in operator creation when generating certificate"; throw new KeystoreException(errorMsg, e); } catch (CertificateExpiredException e) { String errorMsg = "Certificate expired after generating certificate"; throw new KeystoreException(errorMsg, e); } catch (CertificateNotYetValidException e) { String errorMsg = "Certificate not yet valid when generating certificate"; throw new KeystoreException(errorMsg, e); } catch (CertificateException e) { String errorMsg = "Certificate issue occurred when generating certificate"; throw new KeystoreException(errorMsg, e); } catch (InvalidKeyException e) { String errorMsg = "Invalid key used when generating certificate"; throw new KeystoreException(errorMsg, e); } catch (SignatureException e) { String errorMsg = "Signature related issue occurred when generating certificate"; throw new KeystoreException(errorMsg, e); } }
From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.enrollment.EnrollmentManager.java
/** * Method to control the entire enrollment flow. This method calls the method to create the Private-Public Key * Pair, calls the specific method to generate the Certificate-Sign-Request, creates a one time self signed * certificate to present to the SCEP server with the initial CSR, calls the specific method to connect to the * SCEP Server and to get the SCEP Certificate and also calls the method that requests the SCEP Server for its * PublicKey for future payload encryption. * * @throws AgentCoreOperationException if the private method generateCertSignRequest() fails with an error or if * there is an error creating a self-sign certificate to present to the * server (whilst trying to get the CSR signed) *//*from w w w.j a va2s. c o m*/ public void beginEnrollmentFlow() throws AgentCoreOperationException { Security.addProvider(new BouncyCastleProvider()); KeyPair keyPair = generateKeyPair(); this.privateKey = keyPair.getPrivate(); this.publicKey = keyPair.getPublic(); if (log.isDebugEnabled()) { log.info(AgentConstants.LOG_APPENDER + "DevicePrivateKey:\n[\n" + privateKey + "\n]\n"); log.info(AgentConstants.LOG_APPENDER + "DevicePublicKey:\n[\n" + publicKey + "\n]\n"); } PKCS10CertificationRequest certSignRequest = generateCertSignRequest(); /** * ----------------------------------------------------------------------------------------------- * Generate an ephemeral self-signed certificate. This is needed to present to the CA in the SCEP request. * In the future, add proper EKU and attributes in the request. The CA does NOT have to honour any of this. * ----------------------------------------------------------------------------------------------- */ X500Name issuer = new X500Name("CN=Temporary Issuer"); BigInteger serial = new BigInteger(32, new SecureRandom()); Date fromDate = new Date(); Date toDate = new Date(System.currentTimeMillis() + (CERT_VALIDITY * 86400000L)); // Build the self-signed cert using BC, sign it with our private key (self-signed) X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serial, fromDate, toDate, certSignRequest.getSubject(), certSignRequest.getSubjectPublicKeyInfo()); ContentSigner sigGen; X509Certificate tmpCert; try { sigGen = new JcaContentSignerBuilder(SIGNATURE_ALG).setProvider(PROVIDER).build(keyPair.getPrivate()); tmpCert = new JcaX509CertificateConverter().setProvider(PROVIDER) .getCertificate(certBuilder.build(sigGen)); } catch (OperatorCreationException e) { String errorMsg = "Error occurred whilst creating a ContentSigner for the Temp-Self-Signed Certificate."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } catch (CertificateException e) { String errorMsg = "Error occurred whilst trying to create Temp-Self-Signed Certificate."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } /** * ----------------------------------------------------------------------------------------------- */ this.SCEPCertificate = getSignedCertificateFromServer(tmpCert, certSignRequest); this.serverPublicKey = initPublicKeyOfServer(); if (log.isDebugEnabled()) { log.info(AgentConstants.LOG_APPENDER + "TemporaryCertPublicKey:\n[\n" + tmpCert.getPublicKey() + "\n]\n"); log.info(AgentConstants.LOG_APPENDER + "ServerPublicKey:\n[\n" + serverPublicKey + "\n]\n"); } }