List of usage examples for java.security InvalidKeyException InvalidKeyException
public InvalidKeyException(Throwable cause)
From source file:uk.ac.bbsrc.tgac.miso.integration.util.SignatureHelper.java
public static boolean validateSignature(HttpServletRequest request, String publicKey, String signature) throws InvalidKeyException, Exception { if (request == null || signature == null || publicKey == null) { throw new InvalidKeyException("Cannot verify signature when request or signature are null!"); }//from w w w .jav a 2 s .co m log.debug("VERIFYING HMAC: " + signature + " vs " + createSignatureFromRequest(request, publicKey)); return signature.equals(createSignatureFromRequest(request, publicKey)); }
From source file:com.doplgangr.secrecy.filesystem.encryption.AES_Crypter.java
AES_Crypter(String vaultPath, String passphrase, String encryptionMode) throws InvalidKeyException { secureRandom = new SecureRandom(); this.vaultPath = vaultPath; this.encryptionMode = encryptionMode; File headerFile = new File(this.vaultPath + VAULT_HEADER_FILENAME); if (!headerFile.exists()) { try {/*w w w.ja va 2s.c o m*/ KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM); keyGenerator.init(AES_KEY_SIZE_BIT); Key encryptionKey = keyGenerator.generateKey(); byte[] vaultNonce = new byte[NONCE_LENGTH_BYTE]; byte[] salt = new byte[SALT_SIZE_BYTE]; secureRandom.nextBytes(vaultNonce); secureRandom.nextBytes(salt); int pbkdf2Iterations = generatePBKDF2IterationCount(passphrase, salt); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM); SecretKey keyFromPassphrase = secretKeyFactory.generateSecret( new PBEKeySpec(passphrase.toCharArray(), salt, pbkdf2Iterations, AES_KEY_SIZE_BIT)); writeVaultHeader(headerFile, vaultNonce, salt, pbkdf2Iterations, encryptionKey, keyFromPassphrase); } catch (Exception e) { Util.log("Cannot create vault header!"); e.printStackTrace(); } } try { FileInputStream headerInputStream = new FileInputStream(headerFile); vaultHeader = VaultHeader.parseFrom(headerInputStream); } catch (Exception e) { Util.log("Cannot read vault header!"); e.printStackTrace(); } try { SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM); SecretKey keyFromPassphrase = secretKeyFactory.generateSecret(new PBEKeySpec(passphrase.toCharArray(), vaultHeader.getSalt().toByteArray(), vaultHeader.getPbkdf2Iterations(), AES_KEY_SIZE_BIT)); Cipher c = Cipher.getInstance(HEADER_ENCRYPTION_MODE); c.init(Cipher.UNWRAP_MODE, keyFromPassphrase, new IvParameterSpec(vaultHeader.getVaultIV().toByteArray())); vaultFileEncryptionKey = (SecretKey) c.unwrap(vaultHeader.getEncryptedAesKey().toByteArray(), KEY_ALGORITHM, Cipher.SECRET_KEY); } catch (InvalidKeyException e) { throw new InvalidKeyException("Passphrase is wrong!"); } catch (Exception e) { Util.log("Cannot decrypt AES key"); e.printStackTrace(); } }
From source file:com.turo.pushy.apns.auth.ApnsSigningKey.java
/** * Loads a signing key from the given input stream. * * @param inputStream the input stream from which to load the key * @param teamId the ten-character, Apple-issued identifier for the team to which the key belongs * @param keyId the ten-character, Apple-issued identitifier for the key itself * * @return an APNs signing key with the given key ID and associated with the given team * * @throws IOException if a key could not be loaded from the given file for any reason * @throws NoSuchAlgorithmException if the JVM does not support elliptic curve keys * @throws InvalidKeyException if the loaded key is invalid for any reason *//* w w w .j a va 2 s . c om*/ public static ApnsSigningKey loadFromInputStream(final InputStream inputStream, final String teamId, final String keyId) throws IOException, NoSuchAlgorithmException, InvalidKeyException { final ECPrivateKey signingKey; { final String base64EncodedPrivateKey; { final StringBuilder privateKeyBuilder = new StringBuilder(); final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); boolean haveReadHeader = false; boolean haveReadFooter = false; for (String line; (line = reader.readLine()) != null;) { if (!haveReadHeader) { if (line.contains("BEGIN PRIVATE KEY")) { haveReadHeader = true; } } else { if (line.contains("END PRIVATE KEY")) { haveReadFooter = true; break; } else { privateKeyBuilder.append(line); } } } if (!(haveReadHeader && haveReadFooter)) { throw new IOException("Could not find private key header/footer"); } base64EncodedPrivateKey = privateKeyBuilder.toString(); } final byte[] keyBytes = Base64.decodeBase64(base64EncodedPrivateKey); final PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); final KeyFactory keyFactory = KeyFactory.getInstance("EC"); try { signingKey = (ECPrivateKey) keyFactory.generatePrivate(keySpec); } catch (InvalidKeySpecException e) { throw new InvalidKeyException(e); } } return new ApnsSigningKey(keyId, teamId, signingKey); }
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 www . ja va 2s . 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:com.turo.pushy.apns.auth.ApnsVerificationKey.java
/** * Loads a verification key from the given input stream. * * @param inputStream the input stream from which to load the key * @param teamId the ten-character, Apple-issued identifier for the team to which the key belongs * @param keyId the ten-character, Apple-issued identitifier for the key itself * * @return an APNs verification key with the given key ID and associated with the given team * * @throws IOException if a key could not be loaded from the given file for any reason * @throws NoSuchAlgorithmException if the JVM does not support elliptic curve keys * @throws InvalidKeyException if the loaded key is invalid for any reason *//*from ww w . ja va 2s. c o m*/ public static ApnsVerificationKey loadFromInputStream(final InputStream inputStream, final String teamId, final String keyId) throws IOException, NoSuchAlgorithmException, InvalidKeyException { final ECPublicKey verificationKey; { final String base64EncodedPublicKey; { final StringBuilder publicKeyBuilder = new StringBuilder(); final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); boolean haveReadHeader = false; boolean haveReadFooter = false; for (String line; (line = reader.readLine()) != null;) { if (!haveReadHeader) { if (line.contains("BEGIN PUBLIC KEY")) { haveReadHeader = true; } } else { if (line.contains("END PUBLIC KEY")) { haveReadFooter = true; break; } else { publicKeyBuilder.append(line); } } } if (!(haveReadHeader && haveReadFooter)) { throw new IOException("Could not find public key header/footer"); } base64EncodedPublicKey = publicKeyBuilder.toString(); } final byte[] keyBytes = Base64.decodeBase64(base64EncodedPublicKey); final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); final KeyFactory keyFactory = KeyFactory.getInstance("EC"); try { verificationKey = (ECPublicKey) keyFactory.generatePublic(keySpec); } catch (InvalidKeySpecException e) { throw new InvalidKeyException(e); } } return new ApnsVerificationKey(keyId, teamId, verificationKey); }
From source file:org.apache.jcp.xml.dsig.internal.dom.DOMHMACSignatureMethod.java
byte[] sign(Key key, SignedInfo si, XMLSignContext context) throws InvalidKeyException, XMLSignatureException { if (key == null || si == null) { throw new NullPointerException(); }/*from www . jav a 2 s . c o m*/ if (!(key instanceof SecretKey)) { throw new InvalidKeyException("key must be SecretKey"); } if (hmac == null) { try { hmac = Mac.getInstance(getJCAAlgorithm()); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } } if (outputLengthSet && outputLength < getDigestLength()) { throw new XMLSignatureException("HMACOutputLength must not be less than " + getDigestLength()); } hmac.init((SecretKey) key); ((DOMSignedInfo) si).canonicalize(context, new MacOutputStream(hmac)); return hmac.doFinal(); }
From source file:net.firejack.platform.web.security.x509.KeyUtils.java
public static void verify(String cert64, String public64) throws CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, NoSuchProviderException, InvalidKeyException { if (StringUtils.isBlank(cert64)) { throw new CertificateException("Certificate is empty"); } else if (StringUtils.isBlank(public64)) { throw new InvalidKeyException("Public key is empty"); }/*w w w . ja v a 2s . c o m*/ byte[] cert = Base64.decode(cert64); byte[] key = Base64.decode(public64); X509CertImpl x509 = new X509CertImpl(cert); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(key); PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("UTC")); x509.verify(publicKey); x509.checkValidity(utc.getTime()); }
From source file:org.cesecore.keys.util.KeyStoreTools.java
private X509Certificate getSelfCertificate(String myname, long validity, String sigAlg, KeyPair keyPair) throws InvalidKeyException, CertificateException { final long currentTime = new Date().getTime(); final Date firstDate = new Date(currentTime - 24 * 60 * 60 * 1000); final Date lastDate = new Date(currentTime + validity * 1000); final X500Name issuer = new X500Name(myname); final BigInteger serno = BigInteger.valueOf(firstDate.getTime()); final PublicKey publicKey = keyPair.getPublic(); if (publicKey == null) { throw new InvalidKeyException("Public key is null"); }/* ww w .j a v a 2 s .com*/ try { final X509v3CertificateBuilder cg = new JcaX509v3CertificateBuilder(issuer, serno, firstDate, lastDate, issuer, publicKey); log.debug("Keystore signing algorithm " + sigAlg); final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(sigAlg).setProvider(this.providerName).build(keyPair.getPrivate()), 20480); final X509CertificateHolder cert = cg.build(signer); return (X509Certificate) CertTools.getCertfromByteArray(cert.getEncoded()); } catch (OperatorCreationException e) { log.error("Error creating content signer: ", e); throw new CertificateException(e); } catch (IOException e) { throw new CertificateException("Could not read certificate", e); } }
From source file:org.kaaproject.kaa.common.endpoint.security.KeyUtil.java
/** * Gets the public key from bytes./* ww w . j a v a 2 s . com*/ * * @param keyBytes the key bytes * @return the public * @throws InvalidKeyException invalid key exception */ public static PublicKey getPublic(byte[] keyBytes) throws InvalidKeyException { try { X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance(RSA); return kf.generatePublic(spec); } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { throw new InvalidKeyException(ex); } }
From source file:org.apache.jcp.xml.dsig.internal.dom.DOMSignatureMethod.java
boolean verify(Key key, SignedInfo si, byte[] sig, XMLValidateContext context) throws InvalidKeyException, SignatureException, XMLSignatureException { if (key == null || si == null || sig == null) { throw new NullPointerException(); }// www . jav a2 s .co m if (!(key instanceof PublicKey)) { throw new InvalidKeyException("key must be PublicKey"); } if (signature == null) { try { Provider p = (Provider) context.getProperty("org.jcp.xml.dsig.internal.dom.SignatureProvider"); signature = (p == null) ? Signature.getInstance(getJCAAlgorithm()) : Signature.getInstance(getJCAAlgorithm(), p); } catch (NoSuchAlgorithmException nsae) { throw new XMLSignatureException(nsae); } } signature.initVerify((PublicKey) key); if (log.isDebugEnabled()) { log.debug("Signature provider:" + signature.getProvider()); log.debug("verifying with key: " + key); } ((DOMSignedInfo) si).canonicalize(context, new SignerOutputStream(signature)); try { Type type = getAlgorithmType(); if (type == Type.DSA) { return signature.verify(convertXMLDSIGtoASN1(sig)); } else if (type == Type.ECDSA) { return signature.verify(SignatureECDSA.convertXMLDSIGtoASN1(sig)); } else { return signature.verify(sig); } } catch (IOException ioe) { throw new XMLSignatureException(ioe); } }