/** * Decrypt a property if the data definition (model-specific) requires it. * * @param propertyQName the property qualified name * @param inbound the property to decrypt * @return the decrypted property or the original if it wasn't encrypted */ public Serializable decrypt(QName propertyQName, Serializable inbound) { PropertyDefinition propertyDef = dictionaryService.getProperty(propertyQName); if (inbound == null || propertyDef == null || !(propertyDef.getDataType().getName().equals(DataTypeDefinition.ENCRYPTED))) { return inbound; } if (!(inbound instanceof SealedObject)) { return inbound; } try { Serializable outbound = encryptor.unsealObject(KeyProvider.ALIAS_METADATA, inbound); // Done return outbound; } catch(KeyException e) { throw new AlfrescoRuntimeException("Invalid metadata decryption key", e); } }
@Test() public void select_publicKey_exception() throws Exception { // given KeyInfo keyinfo = mock(KeyInfo.class); ArrayList<XMLStructure> list = new ArrayList<XMLStructure>(); KeyValue struct = mock(KeyValue.class); list.add(struct); doReturn(list).when(keyinfo).getContent(); doThrow(new KeyException("test")).when(struct).getPublicKey(); // when try { selector.select(keyinfo, null, null, null); fail(); } catch (KeySelectorException e) { assertTrue(e.getCause().getMessage().contains("test")); } }
/** * Generates a random Java JCE symmetric Key object from the specified XML Encryption algorithm URI. * * @param algoURI The XML Encryption algorithm URI * @return a randomly-generated symmetric Key * @throws NoSuchAlgorithmException thrown if the specified algorithm is invalid * @throws KeyException thrown if the length of the key to generate could not be determined */ public static SecretKey generateSymmetricKey(String algoURI) throws NoSuchAlgorithmException, KeyException { Logger log = getLogger(); String jceAlgorithmName = getKeyAlgorithmFromURI(algoURI); if (DatatypeHelper.isEmpty(jceAlgorithmName)) { log.error("Mapping from algorithm URI '" + algoURI + "' to key algorithm not available, key generation failed"); throw new NoSuchAlgorithmException("Algorithm URI'" + algoURI + "' is invalid for key generation"); } Integer keyLength = getKeyLengthFromURI(algoURI); if (keyLength == null) { log.error("Key length could not be determined from algorithm URI, can't generate key"); throw new KeyException("Key length not determinable from algorithm URI, could not generate new key"); } KeyGenerator keyGenerator = KeyGenerator.getInstance(jceAlgorithmName); keyGenerator.init(keyLength); return keyGenerator.generateKey(); }
/** * Decodes RSA/DSA private keys in DER, PEM, or PKCS#8 (encrypted or unencrypted) formats. * * @param key encoded key * @param password decryption password or null if the key is not encrypted * * @return deocded private key * * @throws KeyException thrown if the key can not be decoded */ public static PrivateKey decodePrivateKey(File key, char[] password) throws KeyException { if (!key.exists()) { throw new KeyException("Key file " + key.getAbsolutePath() + " does not exist"); } if (!key.canRead()) { throw new KeyException("Key file " + key.getAbsolutePath() + " is not readable"); } try { return decodePrivateKey(DatatypeHelper.fileToByteArray(key), password); } catch (IOException e) { throw new KeyException("Error reading Key file " + key.getAbsolutePath(), e); } }
public KeyValue newKeyValue(PublicKey key) throws KeyException { String algorithm = key.getAlgorithm(); if (algorithm.equals("DSA")) { return new DOMKeyValue.DSA(key); } else if (algorithm.equals("RSA")) { return new DOMKeyValue.RSA(key); } else if (algorithm.equals("EC")) { return new DOMKeyValue.EC(key); } else { throw new KeyException("unsupported key algorithm: " + algorithm); } }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof KeyValue)) { return false; } try { KeyValue kv = (KeyValue)obj; if (publicKey == null ) { if (kv.getPublicKey() != null) { return false; } } else if (!publicKey.equals(kv.getPublicKey())) { return false; } } catch (KeyException ke) { // no practical way to determine if the keys are equal return false; } return true; }
public KeySelectorResult select(KeyInfo keyInfo, KeySelector.Purpose purpose, AlgorithmMethod method, XMLCryptoContext context) throws KeySelectorException { if (keyInfo == null) { throw new KeySelectorException("Null KeyInfo object!"); } SignatureMethod sm = (SignatureMethod) method; for (XMLStructure xmlStructure : keyInfo.getContent()) { if (xmlStructure instanceof KeyValue) { PublicKey pk = null; try { pk = ((KeyValue)xmlStructure).getPublicKey(); } catch (KeyException ke) { throw new KeySelectorException(ke); } // make sure algorithm is compatible with method if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) { return new SimpleKSResult(pk); } } } throw new KeySelectorException("No KeyValue element found!"); }
@Test(expected = KeyException.class) public void testWALKeyWrappingWithIncorrectKey() throws Exception { // set up the key provider for testing to resolve a key for our test subject Configuration conf = new Configuration(); // we don't need HBaseConfiguration for this conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, KeyProviderForTesting.class.getName()); // generate a test key byte[] keyBytes = new byte[AES.KEY_LENGTH]; new SecureRandom().nextBytes(keyBytes); String algorithm = conf.get(HConstants.CRYPTO_WAL_ALGORITHM_CONF_KEY, HConstants.CIPHER_AES); Key key = new SecretKeySpec(keyBytes, algorithm); // wrap the test key byte[] wrappedKeyBytes = EncryptionUtil.wrapKey(conf, "hbase", key); assertNotNull(wrappedKeyBytes); // unwrap with an incorrect key EncryptionUtil.unwrapWALKey(conf, "other", wrappedKeyBytes); }
/** * Returns the public exponent. */ public BigInteger getPublicExponent() { if (exponent == null) { try { publicKeyBlob = getPublicKeyBlob(hCryptKey); exponent = new BigInteger(1, getExponent(publicKeyBlob)); } catch (KeyException e) { throw new ProviderException(e); } } return exponent; }
/** * Returns the modulus. */ public BigInteger getModulus() { if (modulus == null) { try { publicKeyBlob = getPublicKeyBlob(hCryptKey); modulus = new BigInteger(1, getModulus(publicKeyBlob)); } catch (KeyException e) { throw new ProviderException(e); } } return modulus; }
/** * Returns the public exponent. */ public BigInteger getPublicExponent() { if (exponent == null) { try { publicKeyBlob = getPublicKeyBlob(handles.hCryptKey); exponent = new BigInteger(1, getExponent(publicKeyBlob)); } catch (KeyException e) { throw new ProviderException(e); } } return exponent; }
/** * Returns the modulus. */ public BigInteger getModulus() { if (modulus == null) { try { publicKeyBlob = getPublicKeyBlob(handles.hCryptKey); modulus = new BigInteger(1, getModulus(publicKeyBlob)); } catch (KeyException e) { throw new ProviderException(e); } } return modulus; }
public byte[] decrypt(byte[] encryptedInput) throws CryptoException { try { SecretKey key = new SecretKeySpec(getAESKey(), ALGORITHM_AES); Cipher cipher = Cipher.getInstance(AES_TRANSFORMATION); String encodedIV = storage.retrieveString(KEY_IV_ALIAS); if (TextUtils.isEmpty(encodedIV)) { throw new InvalidAlgorithmParameterException("The AES Key exists but an IV was never stored. Try to encrypt something first."); } byte[] iv = Base64.decode(encodedIV, Base64.DEFAULT); cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv)); return cipher.doFinal(encryptedInput); } catch (KeyException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | BadPaddingException | IllegalBlockSizeException e) { Log.e(TAG, "Error while decrypting the input.", e); throw new CryptoException("Error while decrypting the input.", e); } }
@Test public void shouldThrowOnNoSuchProviderErrorWhenTryingToObtainRSAKeys() throws Exception { ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 19); exception.expect(KeyException.class); exception.expectMessage("An error occurred while trying to obtain the RSA KeyPair Entry from the Android KeyStore."); PowerMockito.when(keyStore.containsAlias(KEY_ALIAS)).thenReturn(false); KeyPairGeneratorSpec spec = PowerMockito.mock(KeyPairGeneratorSpec.class); KeyPairGeneratorSpec.Builder builder = newKeyPairGeneratorSpecBuilder(spec); PowerMockito.whenNew(KeyPairGeneratorSpec.Builder.class).withAnyArguments().thenReturn(builder); PowerMockito.mockStatic(KeyPairGenerator.class); PowerMockito.when(KeyPairGenerator.getInstance(ALGORITHM_RSA, ANDROID_KEY_STORE)) .thenThrow(new NoSuchProviderException()); cryptoUtil.getRSAKeyEntry(); }
@Test public void shouldThrowOnNoSuchAlgorithmErrorWhenTryingToObtainRSAKeys() throws Exception { ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 19); exception.expect(KeyException.class); exception.expectMessage("An error occurred while trying to obtain the RSA KeyPair Entry from the Android KeyStore."); PowerMockito.when(keyStore.containsAlias(KEY_ALIAS)).thenReturn(false); KeyPairGeneratorSpec spec = PowerMockito.mock(KeyPairGeneratorSpec.class); KeyPairGeneratorSpec.Builder builder = newKeyPairGeneratorSpecBuilder(spec); PowerMockito.whenNew(KeyPairGeneratorSpec.Builder.class).withAnyArguments().thenReturn(builder); PowerMockito.mockStatic(KeyPairGenerator.class); PowerMockito.when(KeyPairGenerator.getInstance(ALGORITHM_RSA, ANDROID_KEY_STORE)) .thenThrow(new NoSuchAlgorithmException()); cryptoUtil.getRSAKeyEntry(); }
private static PrivateKey getPrivateKeyFromByteBuffer(byte[] encodedKey, String keyPassword) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException, KeyException, IOException { PKCS8EncodedKeySpec encodedKeySpec = generateKeySpec( keyPassword == null ? null : keyPassword.toCharArray(), encodedKey); try { return KeyFactory.getInstance("RSA").generatePrivate(encodedKeySpec); } catch (InvalidKeySpecException ignore) { try { return KeyFactory.getInstance("DSA").generatePrivate(encodedKeySpec); } catch (InvalidKeySpecException ignore2) { try { return KeyFactory.getInstance("EC").generatePrivate(encodedKeySpec); } catch (InvalidKeySpecException e) { throw new InvalidKeySpecException("Neither RSA, DSA nor EC worked", e); } } } }
static byte[] readPrivateKey(InputStream in) throws KeyException { String content; try { content = FileUtil.input2String(in, Encoding.UTF8); } catch (IOException e) { throw new KeyException("failed to read key input stream", e); } String[] ls = content.split("\n"); StringBuilder b = new StringBuilder(); for (String s : ls) { if (s.startsWith("-----")) { continue; } b.append(s.trim().replace("\r", "")); } byte[] der = BASE64Util.base64ToByteArray(b.toString()); return der; }
private static byte[] readPrivateKey(InputStream in) throws KeyException { String content; try { content = readContent(in); } catch (IOException e) { throw new KeyException("failed to read key input stream", e); } Matcher m = KEY_PATTERN.matcher(content); if (!m.find()) { throw new KeyException("could not find a PKCS #8 private key in input stream" + " (see http://netty.io/wiki/sslcontextbuilder-and-private-key.html for more information)"); } return Base64.decode(m.group(1)); }
/** * Unwrap a key by decrypting it with the secret key of the given subject. * The configuration must be set up correctly for key alias resolution. Keys * are always unwrapped using AES. * @param conf configuration * @param subject subject key alias * @param value the encrypted key bytes * @return the raw key bytes * @throws IOException * @throws KeyException */ public static Key unwrapKey(Configuration conf, String subject, byte[] value) throws IOException, KeyException { EncryptionProtos.WrappedKey wrappedKey = EncryptionProtos.WrappedKey.PARSER .parseDelimitedFrom(new ByteArrayInputStream(value)); Cipher cipher = Encryption.getCipher(conf, "AES"); if (cipher == null) { throw new RuntimeException("Algorithm 'AES' not available"); } ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] iv = wrappedKey.hasIv() ? wrappedKey.getIv().toByteArray() : null; Encryption.decryptWithSubjectKey(out, wrappedKey.getData().newInput(), wrappedKey.getLength(), subject, conf, cipher, iv); byte[] keyBytes = out.toByteArray(); if (wrappedKey.hasHash()) { if (!Bytes.equals(wrappedKey.getHash().toByteArray(), Encryption.hash128(keyBytes))) { throw new KeyException("Key was not successfully unwrapped"); } } return new SecretKeySpec(keyBytes, wrappedKey.getAlgorithm()); }
private byte[] createCredentials(String username, String password) throws ConnectionException, LoginException, KeyException { String url = PortalConfiguration.SCHEDULER_URL.getValueAsString(); SchedulerAuthenticationInterface auth = SchedulerConnection.join(url); PublicKey pubKey = auth.getPublicKey(); byte[] privateKey = auth.getPrivateKey(); Credentials cred = Credentials.createCredentials(new CredData(CredData.parseLogin(username), CredData.parseDomain(username), password, privateKey), pubKey); byte[] credentialBytes = cred.getBase64(); return credentialBytes; }
private void validateContents(Map<String, String> usersToCheck, Multimap<String, String> groupsToCheck) throws IOException, KeyException { Properties props = new Properties(); try (Reader reader = new InputStreamReader(new FileInputStream(loginFile))) { props.load(reader); String groupContent = IOUtils.toString(groupFile.toURI()); for (Map.Entry<String, String> user : usersToCheck.entrySet()) { Assert.assertTrue("login file should contain " + user.getKey(), props.containsKey(user.getKey())); String encryptedPassword = (String) props.get(user.getKey()); String password = HybridEncryptionUtil.decryptBase64String(encryptedPassword, privateKey, FileLoginModule.ENCRYPTED_DATA_SEP); Assert.assertEquals("decrypted password for user " + user.getKey() + " should match", user.getValue(), password); for (String group : groupsToCheck.get(user.getKey())) { Assert.assertTrue("group file should contain " + user.getKey() + ":" + group, groupContent.contains(user.getKey() + ":" + group)); } } } }
@Test public void testGetJobResult() throws KeyException, AlreadyConnectedException, NotConnectedException, PermissionException, UnknownJobException { Mockito.when(frontendState.getIdentifiedJob(jobId)).thenReturn(ij); Mockito.when(ij.isFinished()).thenReturn(false); Mockito.when(frontendState.getJobState(jobId)).thenReturn(jobstate); try { schedulerFrontend.getJobResult(jobId); } catch (Exception e) { } Mockito.verify(frontendState, times(1)) .checkPermissions("getJobResult", ij, YOU_DO_NOT_HAVE_PERMISSION_TO_GET_THE_RESULT_OF_THIS_JOB); }
@Test public void testGetTaskResultFromIncarnation() throws KeyException, AlreadyConnectedException, NotConnectedException, PermissionException, UnknownJobException { Mockito.when(frontendState.getIdentifiedJob(jobId)).thenReturn(ij); Mockito.when(ij.isFinished()).thenReturn(false); Mockito.when(frontendState.getJobState(jobId)).thenReturn(jobstate); try { schedulerFrontend.getTaskResultFromIncarnation(jobId, "taskname", 1); } catch (Exception e) { } Mockito.verify(frontendState, times(1)) .checkPermissions("getTaskResultFromIncarnation", ij, YOU_DO_NOT_HAVE_PERMISSION_TO_GET_THE_TASK_RESULT_OF_THIS_JOB); }
@Test public void testResumeJob() throws KeyException, AlreadyConnectedException, NotConnectedException, PermissionException, UnknownJobException { Mockito.when(frontendState.getIdentifiedJob(jobId)).thenReturn(ij); Mockito.when(ij.isFinished()).thenReturn(false); Mockito.when(frontendState.getJobState(jobId)).thenReturn(jobstate); try { schedulerFrontend.resumeJob(jobId); } catch (Exception e) { } Mockito.verify(frontendState, times(1)).checkPermissions("resumeJob", ij, YOU_DO_NOT_HAVE_PERMISSION_TO_RESUME_THIS_JOB); }
@Test public void testKillJob() throws KeyException, AlreadyConnectedException, NotConnectedException, PermissionException, UnknownJobException { Mockito.when(frontendState.getIdentifiedJob(jobId)).thenReturn(ij); Mockito.when(ij.isFinished()).thenReturn(false); Mockito.when(frontendState.getJobState(jobId)).thenReturn(jobstate); try { schedulerFrontend.killJob(jobId); } catch (Exception e) { } Mockito.verify(frontendState, times(1)).checkPermissions("killJob", ij, YOU_DO_NOT_HAVE_PERMISSION_TO_KILL_THIS_JOB); }
@Test public void testGetJobServerLogs() throws KeyException, AlreadyConnectedException, NotConnectedException, PermissionException, UnknownJobException { Mockito.when(frontendState.getIdentifiedJob(jobId)).thenReturn(ij); Mockito.when(ij.isFinished()).thenReturn(false); Mockito.when(frontendState.getJobState(jobId)).thenReturn(jobstate); try { schedulerFrontend.getJobServerLogs("123"); } catch (Exception e) { } Mockito.verify(frontendState, times(1)) .checkPermissions("getJobServerLogs", ij, YOU_DO_NOT_HAVE_PERMISSIONS_TO_GET_THE_LOGS_OF_THIS_JOB); }
@Test public void testGetTaskServerLogs() throws KeyException, AlreadyConnectedException, NotConnectedException, PermissionException, UnknownJobException { Mockito.when(frontendState.getIdentifiedJob(jobId)).thenReturn(ij); Mockito.when(ij.isFinished()).thenReturn(false); Mockito.when(frontendState.getJobState(jobId)).thenReturn(jobstate); try { schedulerFrontend.getTaskServerLogs("123", "taskname"); } catch (Exception e) { } Mockito.verify(frontendState, times(1)) .checkPermissions("getTaskServerLogs", ij, YOU_DO_NOT_HAVE_PERMISSION_TO_GET_THE_TASK_LOGS_OF_THIS_JOB); }