List of usage examples for java.security KeyPair getPrivate
public PrivateKey getPrivate()
From source file:cherry.goods.crypto.RSASignatureTest.java
private RSASignature create1() throws Exception { KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA"); keygen.initialize(2048);//from ww w .j av a2 s .c o m KeyPair key = keygen.generateKeyPair(); RSASignature impl = new RSASignature(); impl.setAlgorithm("SHA256withRSA"); impl.setPublicKeyBytes(key.getPublic().getEncoded()); impl.setPrivateKeyBytes(key.getPrivate().getEncoded()); return impl; }
From source file:com.ligadata.EncryptUtils.EncryptionUtil.java
/** * Generate key which contains a pair of private and public key using 1024 * bytes. Store the set of keys in given files publicKeyFile,privateKeyFile * @param algorithm/* w w w . j ava 2 s.co m*/ * : algorithm used * @param publicKeyFile * :The file containing public key * @param privateKeyFile * :The file containing private key */ public static void generateSampleKeys(String algorithm, String publicKeyFile, String privateKeyFile) { try { if (areKeysPresent(publicKeyFile, privateKeyFile)) { return; } final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm); keyGen.initialize(1024); final KeyPair key = keyGen.generateKeyPair(); File privateKeyFD = new File(privateKeyFile); File publicKeyFD = new File(publicKeyFile); // Create files to store public and private key if (privateKeyFD.getParentFile() != null) { privateKeyFD.getParentFile().mkdirs(); } privateKeyFD.createNewFile(); if (publicKeyFD.getParentFile() != null) { publicKeyFD.getParentFile().mkdirs(); } publicKeyFD.createNewFile(); // Saving the Public key in a file ObjectOutputStream publicKeyOS = new ObjectOutputStream(new FileOutputStream(publicKeyFD)); publicKeyOS.writeObject(key.getPublic()); publicKeyOS.close(); // Saving the Private key in a file ObjectOutputStream privateKeyOS = new ObjectOutputStream(new FileOutputStream(privateKeyFD)); privateKeyOS.writeObject(key.getPrivate()); privateKeyOS.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:craterdog.security.RsaAesMessageCryptexTest.java
/** * This test method performs a round-trip session key generation, encryption, signing, * encoding, decoding, signature verification, and decryption tests using the MessageCryptex * class./* w ww. jav a 2 s . c o m*/ * * @throws IOException */ @Test public void testMessageRoundTrip() throws IOException { logger.info("Testing round trip message encryption..."); logger.info(" Generating the public/private key pairs..."); RsaCertificateManager manager = new RsaCertificateManager(); KeyPair senderPair = manager.generateKeyPair(); PrivateKey senderPrivateKey = senderPair.getPrivate(); PublicKey senderPublicKey = senderPair.getPublic(); KeyPair receiverPair = manager.generateKeyPair(); PrivateKey receiverPrivateKey = receiverPair.getPrivate(); PublicKey receiverPublicKey = receiverPair.getPublic(); logger.info(" Sender generating shared session key..."); SecretKey sessionKey = cryptex.generateSharedKey(); logger.info(" Sender encrypting session key..."); byte[] encryptedSessionKey = cryptex.encryptSharedKey(receiverPublicKey, sessionKey); logger.info(" Sender signing the encrypted session key..."); byte[] signature = cryptex.signBytes(senderPrivateKey, encryptedSessionKey); logger.info(" Sender base 64 encoding the encrypted key and signature..."); String encodedSessionKey = cryptex.encodeBytes(encryptedSessionKey); logger.info(" EncodedSessionKey: " + encodedSessionKey); String encodedSignature = cryptex.encodeBytes(signature); logger.info(" EncodedSignature: " + encodedSignature); logger.info(" Sender encrypting the request using session key..."); String request = "This is a request..."; InputStream clearInput = new ByteArrayInputStream(request.getBytes("UTF-8")); ByteArrayOutputStream encryptedOutput = new ByteArrayOutputStream(); cryptex.encryptStream(sessionKey, clearInput, encryptedOutput); logger.info(" Sender sending the encrypted request to the receiver..."); InputStream encryptedInput = new ByteArrayInputStream(encryptedOutput.toByteArray()); logger.info(" Receiver decoding the encrypted session key and its signature..."); signature = cryptex.decodeString(encodedSignature); encryptedSessionKey = cryptex.decodeString(encodedSessionKey); logger.info(" Receiver validating the signature of the encrypted session key..."); if (!cryptex.bytesAreValid(senderPublicKey, encryptedSessionKey, signature)) { fail("The session key signature was invalid."); } logger.info(" Receiver decrypting the session key..."); sessionKey = cryptex.decryptSharedKey(receiverPrivateKey, encryptedSessionKey); logger.info(" Receiver decrypting the request using the session key..."); ByteArrayOutputStream decryptedOutput = new ByteArrayOutputStream(); cryptex.decryptStream(sessionKey, encryptedInput, decryptedOutput); assertEquals("The decrypted request was different from the original request", request, new String(decryptedOutput.toByteArray())); logger.info(" Receiver handling the request and preparing the response..."); String response = "This is the response..."; logger.info(" Receiver encrypting the response using the session key..."); clearInput = new ByteArrayInputStream(response.getBytes("UTF-8")); encryptedOutput = new ByteArrayOutputStream(); cryptex.encryptStream(sessionKey, clearInput, encryptedOutput); logger.info(" Receiver sending the encrypted response to the sender..."); encryptedInput = new ByteArrayInputStream(encryptedOutput.toByteArray()); logger.info(" Sender decrypting the response using the session key..."); decryptedOutput = new ByteArrayOutputStream(); cryptex.decryptStream(sessionKey, encryptedInput, decryptedOutput); assertEquals("The decrypted response was different from the original response", response, new String(decryptedOutput.toByteArray())); logger.info("Round trip message encryption test completed.\n"); }
From source file:cherry.goods.crypto.RSACryptoTest.java
private RSACrypto create1() throws Exception { KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA"); keygen.initialize(2048);//from ww w . j a v a 2 s.c o m KeyPair key = keygen.generateKeyPair(); RSACrypto impl = new RSACrypto(); impl.setAlgorithm("RSA/ECB/PKCS1Padding"); impl.setPublicKeyBytes(key.getPublic().getEncoded()); impl.setPrivateKeyBytes(key.getPrivate().getEncoded()); return impl; }
From source file:com.hyeb.back.login.LoginController.java
/** * /*from w ww . j a va 2 s. c om*/ */ @RequestMapping(value = "/login") public String login(ModelMap model, RedirectAttributes redirectAttributes, HttpServletRequest request) { /** "?"??? */ final String PRIVATE_KEY_ATTRIBUTE_NAME = "privateKey"; //HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); Setting setting = SettingUtils.get(); KeyPair keyPair = RSAUtils.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); request.getSession().setAttribute(PRIVATE_KEY_ATTRIBUTE_NAME, privateKey); String modulus = Base64.encodeBase64String(publicKey.getModulus().toByteArray());//N String exponent = Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray());//e String captchaId = UUID.randomUUID().toString(); boolean isBackCaptcha = ArrayUtils.contains(setting.getCaptchaTypes(), CaptchaType.adminLogin); model.addAttribute("modulus", modulus); model.addAttribute("exponent", exponent); model.addAttribute("captchaId", captchaId); model.addAttribute("isBackCaptcha", isBackCaptcha); String messageStr = null; String loginFailure = (String) request .getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME); if (loginFailure != null) { if (loginFailure.equals("org.apache.shiro.authc.pam.UnsupportedTokenException")) {//?? messageStr = "admin.captcha.invalid"; } else if (loginFailure.equals("org.apache.shiro.authc.UnknownAccountException")) {// messageStr = "admin.login.unknownAccount"; } else if (loginFailure.equals("org.apache.shiro.authc.DisabledAccountException")) {//? messageStr = "admin.login.disabledAccount";// } else if (loginFailure.equals("org.apache.shiro.authc.LockedAccountException")) {//? messageStr = "admin.login.lockedAccount"; } else if (loginFailure.equals("org.apache.shiro.authc.IncorrectCredentialsException")) {//?? if (ArrayUtils.contains(setting.getAccountLockTypes(), AccountLockType.admin)) { messageStr = "admin.login.accountLockCount";//?{0}??? } else { messageStr = "admin.login.incorrectCredentials";//??? } } else if (loginFailure.equals("org.apache.shiro.authc.AuthenticationException")) {// messageStr = "admin.login.authentication";//?? } if (messageStr != null) { Message message = Message.warn(messageStr); addFlashMessage(redirectAttributes, message); } } Subject subject = SecurityUtils.getSubject(); if (subject.isAuthenticated()) { return "redirect:/back/main/main"; } else { return "/back/login/login"; } }
From source file:org.apache.sshd.common.config.keys.loader.pem.PKCS8PEMResourceKeyPairParserTest.java
@Test // see SSHD-760 public void testPkcs8() throws IOException, GeneralSecurityException { KeyPairGenerator generator = SecurityUtils.getKeyPairGenerator(algorithm); if (keySize > 0) { generator.initialize(keySize);//from w w w . j a va2 s.c o m } KeyPair kp = generator.generateKeyPair(); try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { Collection<Object> items = new ArrayList<>(); PrivateKey prv1 = kp.getPrivate(); items.add(new PEMItem(prv1.getEncoded(), "PRIVATE KEY")); byte[] bytes = PEMUtil.encode(items); os.write(bytes); os.close(); try (ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { KeyPair kp2 = SecurityUtils.loadKeyPairIdentity(getCurrentTestName(), bais, null); assertEquals("Mismatched public key", kp.getPublic(), kp2.getPublic()); assertEquals("Mismatched private key", prv1, kp2.getPrivate()); } } }
From source file:org.apache.nifi.toolkit.tls.util.TlsHelper.java
public static JcaPKCS10CertificationRequest generateCertificationRequest(String requestedDn, String domainAlternativeNames, KeyPair keyPair, String signingAlgorithm) throws OperatorCreationException { JcaPKCS10CertificationRequestBuilder jcaPKCS10CertificationRequestBuilder = new JcaPKCS10CertificationRequestBuilder( new X500Name(requestedDn), keyPair.getPublic()); // add Subject Alternative Name(s) if (StringUtils.isNotBlank(domainAlternativeNames)) { try {//from w w w. j a v a 2 s. c o m jcaPKCS10CertificationRequestBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, createDomainAlternativeNamesExtensions(domainAlternativeNames)); } catch (IOException e) { throw new OperatorCreationException( "Error while adding " + domainAlternativeNames + " as Subject Alternative Name.", e); } } JcaContentSignerBuilder jcaContentSignerBuilder = new JcaContentSignerBuilder(signingAlgorithm); return new JcaPKCS10CertificationRequest( jcaPKCS10CertificationRequestBuilder.build(jcaContentSignerBuilder.build(keyPair.getPrivate()))); }
From source file:com.zxy.commons.codec.rsa.AbstractRSAUtils.java
/** * ??/*from ww w. j a v a 2 s .com*/ * * @param pubFile public file * @param priFile private file * @throws IOException IOException */ @SuppressWarnings("PMD.PrematureDeclaration") protected void generater(File pubFile, File priFile) throws IOException { try { KeyPairGenerator keygen = KeyPairGenerator.getInstance(ALGORITHM); SecureRandom secrand = new SecureRandom(); keygen.initialize(KEY_SIZE, secrand); KeyPair keys = keygen.genKeyPair(); PublicKey pubkey = keys.getPublic(); PrivateKey prikey = keys.getPrivate(); byte[] priKey = Base64.encodeBase64(prikey.getEncoded()); byte[] pubKey = Base64.encodeBase64(pubkey.getEncoded()); if (pubFile.exists()) { throw new IOException(pubFile.getPath() + " is exist!"); } if (priFile.exists()) { throw new IOException(priFile.getPath() + " is exist!"); } OutputStream pubOutput = new FileOutputStream(pubFile); try { IOUtils.write(pubKey, pubOutput); } finally { IOUtils.closeQuietly(pubOutput); } OutputStream priOutput = new FileOutputStream(priFile); try { IOUtils.write(priKey, priOutput); } finally { IOUtils.closeQuietly(priOutput); } } catch (NoSuchAlgorithmException e) { log.error("?", e); } }
From source file:io.getlime.security.powerauth.app.server.service.behavior.ApplicationServiceBehavior.java
/** * Create a new application with given name. * * @param name Application name * @param keyConversionUtilities Utility class for the key conversion * @return Response with new application information *///from w ww . ja v a 2 s . c o m public CreateApplicationResponse createApplication(String name, CryptoProviderUtil keyConversionUtilities) { ApplicationEntity application = new ApplicationEntity(); application.setName(name); application = applicationRepository.save(application); KeyGenerator keyGen = new KeyGenerator(); KeyPair kp = keyGen.generateKeyPair(); PrivateKey privateKey = kp.getPrivate(); PublicKey publicKey = kp.getPublic(); // Generate the default master key pair MasterKeyPairEntity keyPair = new MasterKeyPairEntity(); keyPair.setApplication(application); keyPair.setMasterKeyPrivateBase64( BaseEncoding.base64().encode(keyConversionUtilities.convertPrivateKeyToBytes(privateKey))); keyPair.setMasterKeyPublicBase64( BaseEncoding.base64().encode(keyConversionUtilities.convertPublicKeyToBytes(publicKey))); keyPair.setTimestampCreated(new Date()); keyPair.setName(name + " Default Keypair"); masterKeyPairRepository.save(keyPair); // Create the default application version byte[] applicationKeyBytes = keyGen.generateRandomBytes(16); byte[] applicationSecretBytes = keyGen.generateRandomBytes(16); ApplicationVersionEntity version = new ApplicationVersionEntity(); version.setApplication(application); version.setName("default"); version.setSupported(true); version.setApplicationKey(BaseEncoding.base64().encode(applicationKeyBytes)); version.setApplicationSecret(BaseEncoding.base64().encode(applicationSecretBytes)); applicationVersionRepository.save(version); CreateApplicationResponse response = new CreateApplicationResponse(); response.setApplicationId(application.getId()); response.setApplicationName(application.getName()); return response; }
From source file:hudson.plugins.ec2.EC2PrivateKey.java
/** * Obtains the fingerprint of the key in the "ab:cd:ef:...:12" format. *//* w w w .j a va2s. c om*/ public String getFingerprint() throws IOException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); Reader r = new BufferedReader(new StringReader(privateKey.toString())); PEMReader pem = new PEMReader(r, new PasswordFinder() { public char[] getPassword() { throw PRIVATE_KEY_WITH_PASSWORD; } }); try { KeyPair pair = (KeyPair) pem.readObject(); if (pair == null) return null; PrivateKey key = pair.getPrivate(); return digest(key); } catch (RuntimeException e) { if (e == PRIVATE_KEY_WITH_PASSWORD) throw new IOException("This private key is password protected, which isn't supported yet"); throw e; } }