List of usage examples for java.security PrivateKey equals
public boolean equals(Object obj)
From source file:Main.java
public static void main(String[] argv) throws Exception { String algorithm = "DSA"; // or RSA, DH, etc. // Generate a 1024-bit Digital Signature Algorithm (DSA) key pair KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm); keyGen.initialize(1024);/*from w ww. ja v a 2 s . c o m*/ KeyPair keypair = keyGen.genKeyPair(); PrivateKey privateKey = keypair.getPrivate(); PublicKey publicKey = keypair.getPublic(); byte[] privateKeyBytes = privateKey.getEncoded(); byte[] publicKeyBytes = publicKey.getEncoded(); KeyFactory keyFactory = KeyFactory.getInstance(algorithm); EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes); PrivateKey privateKey2 = keyFactory.generatePrivate(privateKeySpec); EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes); PublicKey publicKey2 = keyFactory.generatePublic(publicKeySpec); // The orginal and new keys are the same boolean same = privateKey.equals(privateKey2); same = publicKey.equals(publicKey2); }
From source file:net.nicholaswilliams.java.licensing.encryption.TestKeyFileUtilities.java
@Test public void testPrivateKeyEncryption04() throws Throwable { PrivateKey privateKey = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair() .getPrivate();//from w w w .j ava 2 s. co m PrivateKey otherKey = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair() .getPrivate(); assertFalse("The keys should not be equal (1).", otherKey.equals(privateKey)); byte[] privateKeyData = KeyFileUtilities.writeEncryptedPrivateKey(privateKey, "yourTestPassword02".toCharArray()); assertNotNull("The key data should not be null.", privateKeyData); assertTrue("The key data should have length.", privateKeyData.length > 0); PrivateKey privateKey2 = KeyFileUtilities.readEncryptedPrivateKey(privateKeyData, "yourTestPassword02".toCharArray()); assertNotNull("The key should not be null.", privateKey2); assertFalse("The objects should not be the same.", privateKey == privateKey2); assertEquals("The keys should be the same.", privateKey, privateKey2); assertFalse("The keys should not be equal (2).", otherKey.equals(privateKey2)); }
From source file:net.nicholaswilliams.java.licensing.encryption.TestKeyFileUtilities.java
@Test public void testPrivateKeyEncryption02() throws Throwable { File file = new File("testPrivateKeyEncryption02.key"); if (file.exists()) FileUtils.forceDelete(file);/*from w w w . j a va2 s . c om*/ PrivateKey privateKey = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair() .getPrivate(); PrivateKey otherKey = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair() .getPrivate(); assertFalse("The keys should not be equal (1).", otherKey.equals(privateKey)); KeyFileUtilities.writeEncryptedPrivateKey(privateKey, file, "yourTestPassword02".toCharArray()); PrivateKey privateKey2 = KeyFileUtilities.readEncryptedPrivateKey(file, "yourTestPassword02".toCharArray()); assertNotNull("The key should not be null.", privateKey2); assertFalse("The objects should not be the same.", privateKey == privateKey2); assertEquals("The keys should be the same.", privateKey, privateKey2); assertFalse("The keys should not be equal (2).", otherKey.equals(privateKey2)); FileUtils.forceDelete(file); }
From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java
@Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public byte[] exportCAKeyStore(AuthenticationToken admin, String caname, String keystorepass, String privkeypass, String privateSignatureKeyAlias, String privateEncryptionKeyAlias) { log.trace(">exportCAKeyStore"); try {//from w w w.ja v a 2 s. c om final CA thisCa = caSession.getCAForEdit(admin, caname); // Make sure we are not trying to export a hard or invalid token CAToken thisCAToken = thisCa.getCAToken(); final CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(thisCAToken.getCryptoTokenId()); if (!(cryptoToken instanceof SoftCryptoToken)) { throw new IllegalCryptoTokenException("Cannot export anything but a soft token."); } // Do not allow export without password protection if (StringUtils.isEmpty(keystorepass) || StringUtils.isEmpty(privkeypass)) { throw new IllegalArgumentException("Cannot export a token without password protection."); } // Check authorization if (!accessSession.isAuthorizedNoLogging(admin, StandardRules.ROLE_ROOT.resource())) { String msg = intres.getLocalizedMessage("caadmin.notauthorizedtoexportcatoken", caname); Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", msg); auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, admin.toString(), String.valueOf(thisCa.getCAId()), null, null, details); throw new AuthorizationDeniedException(msg); } // Fetch keys final char[] password = keystorepass.toCharArray(); ((SoftCryptoToken) cryptoToken).checkPasswordBeforeExport(password); cryptoToken.activate(password); PrivateKey p12PrivateEncryptionKey = cryptoToken .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT)); PublicKey p12PublicEncryptionKey = cryptoToken .getPublicKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT)); PrivateKey p12PrivateCertSignKey = cryptoToken .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); PrivateKey p12PrivateCRLSignKey = cryptoToken .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN)); if (!p12PrivateCertSignKey.equals(p12PrivateCRLSignKey)) { throw new Exception("Assertion of equal signature keys failed."); } // Proceed with the export byte[] ret = null; String format = null; if (thisCa.getCAType() == CAInfo.CATYPE_CVC) { log.debug("Exporting private key with algorithm: " + p12PrivateCertSignKey.getAlgorithm() + " of format: " + p12PrivateCertSignKey.getFormat()); format = p12PrivateCertSignKey.getFormat(); ret = p12PrivateCertSignKey.getEncoded(); } else { log.debug("Exporting PKCS12 keystore"); format = "PKCS12"; KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(null, keystorepass.toCharArray()); // Load keys into keystore Certificate[] certificateChainSignature = (Certificate[]) thisCa.getCertificateChain() .toArray(new Certificate[0]); Certificate[] certificateChainEncryption = new Certificate[1]; // certificateChainSignature[0].getSigAlgName(), // generate dummy certificate for encryption key. certificateChainEncryption[0] = CertTools.genSelfCertForPurpose("CN=dummy2", 36500, null, p12PrivateEncryptionKey, p12PublicEncryptionKey, thisCAToken.getEncryptionAlgorithm(), true, X509KeyUsage.keyEncipherment, true); log.debug("Exporting with sigAlgorithm " + AlgorithmTools.getSignatureAlgorithm(certificateChainSignature[0]) + "encAlgorithm=" + thisCAToken.getEncryptionAlgorithm()); if (keystore.isKeyEntry(privateSignatureKeyAlias)) { throw new Exception("Key \"" + privateSignatureKeyAlias + "\"already exists in keystore."); } if (keystore.isKeyEntry(privateEncryptionKeyAlias)) { throw new Exception("Key \"" + privateEncryptionKeyAlias + "\"already exists in keystore."); } keystore.setKeyEntry(privateSignatureKeyAlias, p12PrivateCertSignKey, privkeypass.toCharArray(), certificateChainSignature); keystore.setKeyEntry(privateEncryptionKeyAlias, p12PrivateEncryptionKey, privkeypass.toCharArray(), certificateChainEncryption); // Return KeyStore as byte array and clean up ByteArrayOutputStream baos = new ByteArrayOutputStream(); keystore.store(baos, keystorepass.toCharArray()); if (keystore.isKeyEntry(privateSignatureKeyAlias)) { keystore.deleteEntry(privateSignatureKeyAlias); } if (keystore.isKeyEntry(privateEncryptionKeyAlias)) { keystore.deleteEntry(privateEncryptionKeyAlias); } ret = baos.toByteArray(); } String msg = intres.getLocalizedMessage("caadmin.exportedca", caname, format); Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", msg); auditSession.log(EjbcaEventTypes.CA_EXPORTTOKEN, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE, admin.toString(), String.valueOf(thisCa.getCAId()), null, null, details); log.trace("<exportCAKeyStore"); return ret; } catch (Exception e) { String msg = intres.getLocalizedMessage("caadmin.errorexportca", caname, "PKCS12", e.getMessage()); Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", msg); auditSession.log(EjbcaEventTypes.CA_EXPORTTOKEN, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE, admin.toString(), null, null, null, details); throw new EJBException(e); } }