List of usage examples for java.security KeyPair getPrivate
public PrivateKey getPrivate()
From source file:org.candlepin.CRLWriteBenchmark.java
@Setup(Level.Trial) public void buildMassiveCRL() throws Exception { issuer = new X500Name("CN=Test Issuer"); KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048);/*from ww w.j ava 2 s . co m*/ KeyPair keyPair = generator.generateKeyPair(); bc = new BouncyCastleProvider(); signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(bc).build(keyPair.getPrivate()); X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, new Date()); crlBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(keyPair.getPublic())); /* With a CRL number of 127, incrementing it should cause the number of bytes in the length * portion of the TLV to increase by one.*/ crlBuilder.addExtension(X509Extension.cRLNumber, false, new CRLNumber(new BigInteger("127"))); for (int i = 0; i < 2000000; i++) { crlBuilder.addCRLEntry(new BigInteger(String.valueOf(i)), new Date(), CRLReason.unspecified); } X509CRLHolder holder = crlBuilder.build(signer); X509CRL crl = new JcaX509CRLConverter().setProvider(bc).getCRL(holder); crlFile = File.createTempFile("crl", ".der"); System.out.println("\nWrote test crl to " + crlFile.getAbsolutePath()); FileUtils.writeByteArrayToFile(crlFile, crl.getEncoded()); }
From source file:ie.peternagy.jcrypto.algo.EllipticCurveWrapper.java
/** * Generate a set of Elliptic Curve keys */// w w w.j a va 2 s. c o m public void generateKeys() { tryLoadKeys(); if (isInitialized(true) && isInitialized(false)) { return; } try { ECGenParameterSpec ecGenSpec = new ECGenParameterSpec(EC_CURVE); KeyPairGenerator g = KeyPairGenerator.getInstance(ALGORITHM_NAME); g.initialize(ecGenSpec, CryptoSecurityUtil.getSecureRandom()); KeyPair pair = g.generateKeyPair(); privateKey = pair.getPrivate(); publicKey = pair.getPublic(); writeKeys(); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException ex) { Logger.getLogger(EllipticCurveWrapper.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.titilink.common.app.EncryptDecryptUtil.java
public void testRSA() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, SignatureException { ///*from www.jav a 2 s . c o m*/ KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair keyPair = keyPairGenerator.generateKeyPair(); //? PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); //?? Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, privateKey, new SecureRandom()); byte[] cipherData = cipher .doFinal("this is a security text from server".getBytes(Charset.forName("UTF-8"))); // Cipher cipher1 = Cipher.getInstance("RSA"); cipher1.init(Cipher.DECRYPT_MODE, publicKey, new SecureRandom()); byte[] plainData = cipher1.doFinal(cipherData); System.out.println(new String(plainData, Charset.forName("UTF-8"))); //??????? Signature signature = Signature.getInstance("MD5withRSA"); signature.initSign(privateKey); signature.update(cipherData); byte[] signData = signature.sign(); //????? Signature signature1 = Signature.getInstance("MD5withRSA"); signature1.initVerify(publicKey); signature1.update(cipherData); System.out.println(signature1.verify(signData)); }
From source file:org.apache.xml.security.test.signature.XmlSecTest.java
private void checkXmlSignatureSoftwareStack(boolean cert) throws Exception { Init.init();//w w w.ja va2 s . c o m DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document testDocument = documentBuilder.newDocument(); Element rootElement = testDocument.createElementNS("urn:namespace", "tns:document"); rootElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "urn:namespace"); testDocument.appendChild(rootElement); Element childElement = testDocument.createElementNS("urn:childnamespace", "t:child"); childElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:t", "urn:childnamespace"); childElement.appendChild(testDocument.createTextNode("hello world")); rootElement.appendChild(childElement); PrivateKey privateKey = null; PublicKey publicKey = null; X509Certificate signingCert = null; if (cert) { // get key & self-signed certificate from keystore String fs = System.getProperty("file.separator"); FileInputStream fis = new FileInputStream(BASEDIR + fs + "data" + fs + "test.jks"); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(fis, "changeit".toCharArray()); signingCert = (X509Certificate) ks.getCertificate("mullan"); publicKey = signingCert.getPublicKey(); privateKey = (PrivateKey) ks.getKey("mullan", "changeit".toCharArray()); } else { KeyPair keyPair = KeyPairGenerator.getInstance("DSA").generateKeyPair(); publicKey = keyPair.getPublic(); privateKey = keyPair.getPrivate(); } XMLSignature signature = new XMLSignature(testDocument, "", XMLSignature.ALGO_ID_SIGNATURE_DSA, Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS); Element signatureElement = signature.getElement(); rootElement.appendChild(signatureElement); Transforms transforms = new Transforms(testDocument); XPathContainer xpath = new XPathContainer(testDocument); xpath.setXPathNamespaceContext("ds", Constants.SignatureSpecNS); xpath.setXPath("not(ancestor-or-self::ds:Signature)"); transforms.addTransform(Transforms.TRANSFORM_XPATH, xpath.getElementPlusReturns()); transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS); signature.addDocument("", transforms, MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1); if (cert) { signature.addKeyInfo(signingCert); } else { signature.addKeyInfo(publicKey); } Element nsElement = testDocument.createElementNS(null, "nsElement"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS); signature.sign(privateKey); // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer t = tf.newTransformer(); // t.transform(new DOMSource(testDocument), new StreamResult(System.out)); NodeList signatureElems = XPathAPI.selectNodeList(testDocument, "//ds:Signature", nsElement); signatureElement = (Element) signatureElems.item(0); XMLSignature signatureToVerify = new XMLSignature(signatureElement, ""); boolean signResult = signatureToVerify.checkSignatureValue(publicKey); assertTrue(signResult); }
From source file:cherry.foundation.crypto.RSASignatureSupportTest.java
private RSASignatureSupport createCrypto() throws Exception { KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA"); keygen.initialize(2048);/*w w w. ja v a2s .com*/ KeyPair key = keygen.generateKeyPair(); RSASignatureSupport crypto = new RSASignatureSupport(); crypto.setAlgorithm("SHA256withRSA"); crypto.setPublicKeyResource(new InMemoryResource(key.getPublic().getEncoded())); crypto.setPrivateKeyResource(new InMemoryResource(key.getPrivate().getEncoded())); crypto.afterPropertiesSet(); return crypto; }
From source file:org.apache.directory.server.core.security.CoreKeyStoreSpi.java
@Override public Key engineGetKey(String alias, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException { LOG.debug("engineGetKey({}, {}) called.", alias, password); try {//w w w .j a va 2s. c o m Entry entry = getTlsEntry(); KeyPair keyPair = TlsKeyGenerator.getKeyPair(entry); return keyPair.getPrivate(); } catch (Exception e) { LOG.error(I18n.err(I18n.ERR_68), e); } return null; }
From source file:cherry.foundation.crypto.RSACryptoSupportTest.java
private RSACryptoSupport createCrypto() throws Exception { KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA"); keygen.initialize(2048);//from www.j a va 2 s. c o m KeyPair key = keygen.generateKeyPair(); RSACryptoSupport crypto = new RSACryptoSupport(); crypto.setAlgorithm("RSA/ECB/PKCS1Padding"); crypto.setPublicKeyResource(new InMemoryResource(key.getPublic().getEncoded())); crypto.setPrivateKeyResource(new InMemoryResource(key.getPrivate().getEncoded())); crypto.afterPropertiesSet(); return crypto; }
From source file:com.peterphi.std.crypto.keygen.CaHelper.java
/** * @param kp//from ww w . j av a 2 s . co m * @param issuer * @param subject * * @return */ public static X509Certificate generateCaCertificate(final String friendlyName, final KeyPair kp, final BigInteger serial, final X509Name issuer, final X509Name subject) throws Exception { X509Certificate cert = null; X509V3CertificateGenerator gen = new X509V3CertificateGenerator(); gen.setIssuerDN(issuer); setNotBeforeNotAfter(gen, 20); // The CA certificate is valid for 20 years gen.setSubjectDN(subject); gen.setPublicKey(kp.getPublic()); gen.setSignatureAlgorithm(getSignatureAlgorithm()); if (serial != null) gen.setSerialNumber(serial); else gen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); gen = addCaExtensions(gen, kp.getPublic()); // gen.addExtension(X509Extensions.SubjectKeyIdentifier, false, // new SubjectKeyIdentifierStructure(kp.getPublic())); cert = gen.generate(kp.getPrivate(), "BC"); cert.checkValidity(); cert.verify(kp.getPublic(), "BC"); if (friendlyName != null) { PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert; bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName)); } return cert; }
From source file:edu.vt.middleware.crypt.asymmetric.AsymmetricAlgorithmTest.java
/** * @param asymmetric A symmetric crypt algorithm to test. * @param keys Key pair used for encryption/decryption. * * @throws Exception On test failure./*from ww w. j a va 2 s. co m*/ */ @Test(groups = { "functest", "asymmetric" }, dataProvider = "testdata") public void testAsymmetricAlgorithm(final AsymmetricAlgorithm asymmetric, final KeyPair keys) throws Exception { logger.info("Testing symmetric algorithm " + asymmetric); asymmetric.setKey(keys.getPublic()); asymmetric.initEncrypt(); final byte[] ciphertext = asymmetric.encrypt(CLEARTEXT.getBytes()); asymmetric.setKey(keys.getPrivate()); asymmetric.initDecrypt(); AssertJUnit.assertEquals(CLEARTEXT.getBytes(), asymmetric.decrypt(ciphertext)); }
From source file:cherry.goods.crypto.VersionedSignatureTest.java
private RSASignature createRSASignature() throws Exception { KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA"); keygen.initialize(2048);// www.j ava 2 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; }