List of usage examples for java.security Key getAlgorithm
public String getAlgorithm();
From source file:org.lockss.util.KeyStoreUtil.java
private static void initializeKeyStore(KeyStore keyStore, String domainName, String password) throws IOException, CertificateException, InvalidKeyException, SignatureException, NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, UnrecoverableKeyException { String keyAlias = domainName + keySuffix; String certAlias = domainName + crtSuffix; String keyStorePassword = domainName; String keyStoreFileName = domainName + ".jceks"; File keyStoreFile = new File(keyStoreFileName); if (keyStoreFile.exists()) { log.debug("Key store file " + keyStoreFileName + " exists"); throw new IOException("Key store file " + keyStoreFileName + " exists"); }/*w w w. j a v a 2s. co m*/ String keyAlgName = "RSA"; String sigAlgName = "MD5WithRSA"; log.debug("About to create a CertAndKeyGen: " + keyAlgName + " " + sigAlgName); CertAndKeyGen keypair; try { keypair = new CertAndKeyGen(keyAlgName, sigAlgName); } catch (NoSuchAlgorithmException e) { log.debug("new CertAndKeyGen(" + keyAlgName + "," + sigAlgName + ") threw " + e); throw e; } log.debug("About to generate a key pair"); try { keypair.generate(1024); } catch (InvalidKeyException e) { log.debug("keypair.generate(1024) threw " + e); throw e; } log.debug("About to get a PrivateKey"); PrivateKey privKey = keypair.getPrivateKey(); log.debug("MyKey: " + privKey.getAlgorithm() + " " + privKey.getFormat()); log.debug("About to get a self-signed certificate"); X509Certificate[] chain = new X509Certificate[1]; X500Name x500Name = new X500Name( "CN=" + domainName + ", " + "OU=LOCKSS Team, O=Stanford, " + "L=Stanford, S=California, C=US"); chain[0] = keypair.getSelfCertificate(x500Name, 365 * 24 * 60 * 60); log.debug("Certificate: " + chain[0].toString()); log.debug("About to keyStore.load(null)"); try { keyStore.load(null, keyStorePassword.toCharArray()); } catch (IOException e) { log.debug("keyStore.load() threw " + e); throw e; } catch (CertificateException e) { log.debug("keyStore.load() threw " + e); throw e; } catch (NoSuchAlgorithmException e) { log.debug("keyStore.load() threw " + e); throw e; } log.debug("About to store " + certAlias + " in key store"); try { keyStore.setCertificateEntry(certAlias, chain[0]); } catch (KeyStoreException e) { log.debug("keyStore.setCertificateEntry() threw " + e); throw e; } log.debug("About to store " + keyAlias + " in key store"); try { keyStore.setKeyEntry(keyAlias, privKey, password.toCharArray(), chain); } catch (KeyStoreException e) { log.debug("keyStore.setKeyEntry() threw " + e); throw e; } log.debug("About to getKeyEntry()"); Key myKey = keyStore.getKey(keyAlias, password.toCharArray()); log.debug("MyKey: " + myKey.getAlgorithm() + " " + myKey.getFormat()); log.debug("Done storing"); }
From source file:org.lockss.util.KeyStoreUtil.java
private static void listKeyStore(String domainNames[], KeyStore kss[], String passwords[], int i) { log.debug("start of key store for " + domainNames[i]); try {// w ww .java2s . c om for (Enumeration en = kss[i].aliases(); en.hasMoreElements();) { String alias = (String) en.nextElement(); log.debug("Next alias " + alias); if (kss[i].isCertificateEntry(alias)) { log.debug("About to getCertificate"); java.security.cert.Certificate cert = kss[i].getCertificate(alias); if (cert == null) { log.debug(alias + " null cert chain"); } else { log.debug("Cert for " + alias + " is " + cert.toString()); } } else if (kss[i].isKeyEntry(alias)) { log.debug("About to getKey"); Key privateKey = kss[i].getKey(alias, passwords[i].toCharArray()); log.debug(alias + " key " + privateKey.getAlgorithm() + "/" + privateKey.getFormat()); } else { log.error(alias + " neither key nor cert"); } } log.debug("end of key store for " + domainNames[i]); } catch (Exception ex) { log.error("listKeyStore() threw " + ex); } }
From source file:org.lockss.util.TestKeyStoreUtil.java
void assertPrivateKs(File file, String pass, String alias) throws Exception { KeyStore ks = loadKeyStore("jceks", file, alias); List aliases = ListUtil.fromIterator(new EnumerationIterator(ks.aliases())); assertEquals(2, aliases.size());/*from www .jav a 2 s. c o m*/ Certificate cert = ks.getCertificate(alias + ".crt"); assertNotNull(cert); assertEquals("X.509", cert.getType()); assertTrue(ks.isKeyEntry(alias + ".key")); assertTrue(ks.isCertificateEntry(alias + ".crt")); Key key = ks.getKey(alias + ".key", pass.toCharArray()); assertNotNull(key); assertEquals("RSA", key.getAlgorithm()); }
From source file:org.opensaml.security.crypto.SigningUtil.java
/** * Compute the Message Authentication Code (MAC) value over the supplied input. * /*from ww w . ja v a2s. c om*/ * It is up to the caller to ensure that the specified algorithm ID is consistent with the type of signing key * supplied. * * @param signingKey the key with which to compute the MAC * @param jcaAlgorithmID the Java JCA algorithm ID to use * @param input the input over which to compute the MAC * @return the computed MAC value * @throws SecurityException thrown if the MAC computation results in an error */ @Nonnull public static byte[] signMAC(@Nonnull final Key signingKey, @Nonnull final String jcaAlgorithmID, @Nonnull final byte[] input) throws SecurityException { Constraint.isNotNull(signingKey, "Secret key cannot be null"); Constraint.isNotNull(jcaAlgorithmID, "JCA algorithm ID cannot be null"); Constraint.isNotNull(input, "Input data to sign cannot be null"); Logger log = getLogger(); log.debug("Computing MAC over input using key of type {} and JCA algorithm ID {}", signingKey.getAlgorithm(), jcaAlgorithmID); try { Mac mac = Mac.getInstance(jcaAlgorithmID); mac.init(signingKey); mac.update(input); byte[] rawMAC = mac.doFinal(); log.debug("Computed MAC: {}", Hex.encodeHexString(rawMAC)); return rawMAC; } catch (GeneralSecurityException e) { log.error("Error during MAC generation", e); throw new SecurityException("Error during MAC generation", e); } }
From source file:org.opensaml.security.crypto.SigningUtil.java
/** * Verify the Message Authentication Code (MAC) value computed over the supplied input against the supplied MAC * value.//from ww w. ja va 2 s. c o m * * It is up to the caller to ensure that the specified algorithm ID is consistent with the type of verification key * supplied. * * @param verificationKey the key with which to compute and verify the MAC * @param jcaAlgorithmID the Java JCA algorithm ID to use * @param signature the computed MAC value received from the signer * @param input the input over which the MAC is computed and verified * @return true iff the MAC value computed over the input using the supplied key and algorithm ID is identical to * the supplied MAC signature value * @throws SecurityException thrown if the MAC computation or verification process results in an error */ public static boolean verifyMAC(@Nonnull final Key verificationKey, @Nonnull final String jcaAlgorithmID, @Nonnull final byte[] signature, @Nonnull final byte[] input) throws SecurityException { Constraint.isNotNull(verificationKey, "Secret key cannot be null"); Constraint.isNotNull(jcaAlgorithmID, "JCA algorithm ID cannot be null"); Constraint.isNotNull(signature, "Signature data to verify cannot be null"); Constraint.isNotNull(input, "Input data to verify cannot be null"); Logger log = getLogger(); log.debug("Verifying MAC over input using key of type {} and JCA algorithm ID {}", verificationKey.getAlgorithm(), jcaAlgorithmID); // Java JCA/JCE Mac interface doesn't have a verification op, // so have to compute the Mac and compare the byte arrays manually. byte[] computed = signMAC(verificationKey, jcaAlgorithmID, input); return Arrays.equals(computed, signature); }
From source file:org.opensc.pkcs11.spi.PKCS11CipherSpi.java
@Override protected void engineInit(int opmode, Key key, SecureRandom random) throws InvalidKeyException { if (opmode == Cipher.ENCRYPT_MODE) { if (!(key instanceof PKCS11SessionChild)) throw new InvalidKeyException("PKCS11 signature engine expects a valid PKCS11 object."); if (!this.algorithm.startsWith(key.getAlgorithm())) throw new InvalidKeyException("PKCS11 key algorithm [" + key.getAlgorithm() + "] is incompatible with signature algorithm [" + this.algorithm + "]."); int pkcs11_alg = getPKCS11MechanismType(); this.worker = (PKCS11SessionChild) key; if (key instanceof PublicKey) { this.publicKey = (PublicKey) key; this.privateKey = null; } else if (key instanceof PrivateKey) { this.publicKey = null; this.privateKey = (PrivateKey) key; } else//from w w w . j a v a 2 s . co m throw new InvalidKeyException( "PKCS11 signature engine expects a public or private key for encryption mode."); this.mode = opmode; try { initEncryptNative(this.worker.getPvh(), this.worker.getSlotHandle(), this.worker.getSessionHandle(), this.worker.getHandle(), pkcs11_alg); } catch (PKCS11Exception e) { throw new InvalidKeyException("PKCS11 exception initializing encryption:", e); } } else if (opmode == Cipher.DECRYPT_MODE) { if (!(key instanceof PKCS11SessionChild)) throw new InvalidKeyException("PKCS11 signature engine expects a valid PKCS11 object."); if (!this.algorithm.startsWith(key.getAlgorithm())) throw new InvalidKeyException("PKCS11 key algorithm [" + key.getAlgorithm() + "] is incompatible with signature algorithm [" + this.algorithm + "]."); int pkcs11_alg = getPKCS11MechanismType(); this.worker = (PKCS11SessionChild) key; if (key instanceof PublicKey) { this.publicKey = (PublicKey) key; this.privateKey = null; } else if (key instanceof PrivateKey) { this.publicKey = null; this.privateKey = (PrivateKey) key; } else throw new InvalidKeyException( "PKCS11 signature engine expects a public or private key for decryption mode."); this.mode = opmode; try { initDecryptNative(this.worker.getPvh(), this.worker.getSlotHandle(), this.worker.getSessionHandle(), this.worker.getHandle(), pkcs11_alg); } catch (PKCS11Exception e) { throw new InvalidKeyException("PKCS11 exception initializing decryption:", e); } } else throw new InvalidKeyException( "Invalid operation mode [" + opmode + "] in PKCS11CipherSpi.engineInit()."); this.count = 0; }
From source file:org.sonar.api.config.AesCipherTest.java
@Test public void loadSecretKeyFromFile() throws Exception { AesCipher cipher = new AesCipher(new Settings()); Key secretKey = cipher.loadSecretFileFromFile(pathToSecretKey()); assertThat(secretKey.getAlgorithm(), is("AES")); assertThat(secretKey.getEncoded().length, greaterThan(10)); }
From source file:org.sonar.api.config.AesCipherTest.java
@Test public void loadSecretKeyFromFile_trim_content() throws Exception { URL resource = getClass().getResource("/org/sonar/api/config/AesCipherTest/non_trimmed_secret_key.txt"); String path = new File(resource.toURI()).getCanonicalPath(); AesCipher cipher = new AesCipher(new Settings()); Key secretKey = cipher.loadSecretFileFromFile(path); assertThat(secretKey.getAlgorithm(), is("AES")); assertThat(secretKey.getEncoded().length, greaterThan(10)); }
From source file:org.sonar.application.AesCipherTest.java
@Test public void loadSecretKeyFromFile() throws Exception { AesCipher cipher = new AesCipher(null); Key secretKey = cipher.loadSecretFileFromFile(pathToSecretKey()); assertThat(secretKey.getAlgorithm()).isEqualTo("AES"); assertThat(secretKey.getEncoded().length).isGreaterThan(10); }
From source file:org.sonar.application.AesCipherTest.java
@Test public void loadSecretKeyFromFile_trim_content() throws Exception { String path = getPath("non_trimmed_secret_key.txt"); AesCipher cipher = new AesCipher(null); Key secretKey = cipher.loadSecretFileFromFile(path); assertThat(secretKey.getAlgorithm()).isEqualTo("AES"); assertThat(secretKey.getEncoded().length).isGreaterThan(10); }