use of javax.crypto.SealedObject in project jdk8u_jdk by JetBrains.
the class PBESealedObject method runTest.
// Have a generic throws Exception as it can throw many different exceptions
public boolean runTest(Provider p, String algo, PrintStream out) throws Exception {
byte[] salt = new byte[8];
int ITERATION_COUNT = 1000;
AlgorithmParameters pbeParams = null;
String baseAlgo = new StringTokenizer(algo, "/").nextToken().toUpperCase();
boolean isAES = baseAlgo.contains("AES");
try {
// Initialization
Cipher ci = Cipher.getInstance(algo, p);
new Random().nextBytes(salt);
AlgorithmParameterSpec aps = new PBEParameterSpec(salt, ITERATION_COUNT);
SecretKeyFactory skf = SecretKeyFactory.getInstance(baseAlgo, p);
SecretKey key = skf.generateSecret(new PBEKeySpec("Secret Lover".toCharArray()));
// Seal
if (isAES) {
ci.init(Cipher.ENCRYPT_MODE, key);
pbeParams = ci.getParameters();
} else {
ci.init(Cipher.ENCRYPT_MODE, key, aps);
}
SealedObject so = new SealedObject(key, ci);
// Unseal and compare
if (isAES) {
ci.init(Cipher.DECRYPT_MODE, key, pbeParams);
} else {
ci.init(Cipher.DECRYPT_MODE, key, aps);
}
SecretKey unsealedKey;
unsealedKey = (SecretKey) so.getObject(ci);
if (!Arrays.equals(unsealedKey.getEncoded(), key.getEncoded())) {
return false;
}
unsealedKey = (SecretKey) so.getObject(key);
if (!Arrays.equals(unsealedKey.getEncoded(), key.getEncoded())) {
return false;
}
unsealedKey = (SecretKey) so.getObject(key, "SunJCE");
return Arrays.equals(unsealedKey.getEncoded(), key.getEncoded());
} catch (InvalidKeyException ex) {
if (baseAlgo.endsWith("TRIPLEDES") || baseAlgo.endsWith("AES_256")) {
out.println("Expected exception , keyStrength > 128 within" + algo);
return true;
}
throw ex;
}
}
use of javax.crypto.SealedObject in project jdk8u_jdk by JetBrains.
the class SealedObjectTest method doTest.
/*
* Run the test:
* - init a cipher with AES/GCM/NoPadding transformation
* - seal an object
* - check if we can't seal it again with the same key/IV
* - unseal the object using different methods of SealedObject class
* - check if the original and sealed objects are equal
*/
static void doTest() throws Exception {
// init a secret Key
KeyGenerator kg = KeyGenerator.getInstance(AES, PROVIDER);
kg.init(KEY_LENGTH);
SecretKey key = kg.generateKey();
// initialization
Cipher cipher = Cipher.getInstance(TRANSFORMATION, PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, key);
AlgorithmParameters params = cipher.getParameters();
// seal an object
SealedObject so = new SealedObject(key, cipher);
try {
// check if we can't seal it again with the same key/IV
so = new SealedObject(key, cipher);
throw new RuntimeException("FAILED: expected IllegalStateException hasn't " + "been thrown");
} catch (IllegalStateException ise) {
System.out.println("Expected exception when seal it again with" + " the same key/IV: " + ise);
}
// unseal the object using getObject(Cipher) and compare
cipher.init(Cipher.DECRYPT_MODE, key, params);
SecretKey unsealedKey = (SecretKey) so.getObject(cipher);
assertKeysSame(unsealedKey, key, "SealedObject.getObject(Cipher)");
// unseal the object using getObject(Key) and compare
unsealedKey = (SecretKey) so.getObject(key);
assertKeysSame(unsealedKey, key, "SealedObject.getObject(Key)");
// unseal the object using getObject(Key, String) and compare
unsealedKey = (SecretKey) so.getObject(key, PROVIDER);
assertKeysSame(unsealedKey, key, "SealedObject.getObject(Key, String)");
}
use of javax.crypto.SealedObject in project teiid by teiid.
the class BasicCryptor method sealObject.
public synchronized Object sealObject(Object object) throws CryptoException {
try {
if (useSealedObject) {
return new SealedObject((Serializable) object, encryptCipher);
}
AccessibleByteArrayOutputStream baos = new AccessibleByteArrayOutputStream(1 << 13);
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(object);
oos.flush();
oos.close();
return encrypt(baos.getBuffer(), 0, baos.getCount());
} catch (Exception e) {
try {
initEncryptCipher();
} catch (CryptoException err) {
// shouldn't happen
}
throw new CryptoException(CorePlugin.Event.TEIID10013, CorePlugin.Util.gs(CorePlugin.Event.TEIID10013, e.getMessage()));
}
}
use of javax.crypto.SealedObject in project Jartop by TheRedSpy15.
the class User method login.
final synchronized void login(String password, boolean loadWith256) throws IOException, InterruptedException {
boolean loggedIn = true;
final byte bruteForcePauseLength = 50;
final byte maximumTries = 20;
// Determining key size
byte keySize;
if (// 256
loadWith256)
// 256
keySize = 32;
else
// 128
keySize = 16;
try {
try {
// Hashing
final String hash = Hashing.sha256().hashString(password, Charsets.UTF_8).toString().substring(0, keySize);
// Creating keys
final byte[] key = hash.getBytes();
final String transformation = "AES";
final SecretKeySpec sks = new SecretKeySpec(key, transformation);
// Creating cipher
final Cipher cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.DECRYPT_MODE, sks);
// Streams
final FileInputStream fileInputStream = new FileInputStream(getUserFile().getAbsoluteFile());
final CipherInputStream cipherInputStream = new CipherInputStream(fileInputStream, cipher);
try (ObjectInputStream objectInputStream = new ObjectInputStream(cipherInputStream)) {
// Reading
SealedObject sealedObject = (SealedObject) objectInputStream.readObject();
Core.setUserData((User) sealedObject.getObject(cipher));
} finally {
// Closing streams
fileInputStream.close();
cipherInputStream.close();
}
} catch (NoSuchPaddingException | NoSuchAlgorithmException | ClassNotFoundException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
}
} catch (Exception e) {
// assuming wrong password
loggedIn = false;
Core.getUAS().setFailedAttempts((byte) (Core.getUAS().getFailedAttempts() + 1));
// secure delete
if (Core.getUAS().getFailedAttempts() >= maximumTries) {
Core.getUAS().secureDelete(Core.getUserData().getUserFile(), false);
}
// to slow down brute force attacks
Core.getUserData().wait(bruteForcePauseLength);
Logger.getAnonymousLogger().warning("Log in failed - likely wrong password");
Notifications.create().title("Warning").text("Log in failed - likely wrong password").darkStyle().showWarning();
}
// Loading desktop
if (loggedIn) {
Parent desktopScene = FXMLLoader.load(Core.class.getResource("Desktop.fxml"));
Core.getDesktop().setScene(new Scene(desktopScene));
Core.getUserData().setGuest(false);
Logger.getAnonymousLogger().info("Logged in successfully");
Notifications.create().title("Notice").text("Logged in as " + getName()).darkStyle().showInformation();
}
}
use of javax.crypto.SealedObject in project ranger by apache.
the class RangerKeyStore method engineLoadKeyStoreFile.
public void engineLoadKeyStoreFile(InputStream stream, char[] storePass, char[] keyPass, char[] masterKey, String fileFormat) throws IOException, NoSuchAlgorithmException, CertificateException {
if (logger.isDebugEnabled()) {
logger.debug("==> RangerKeyStoreProvider.engineLoadKeyStoreFile()");
}
synchronized (deltaEntries) {
KeyStore ks;
if (keyVaultEnabled) {
try {
ks = KeyStore.getInstance(fileFormat);
ks.load(stream, storePass);
deltaEntries.clear();
for (Enumeration<String> name = ks.aliases(); name.hasMoreElements(); ) {
SecretKeyByteEntry entry = new SecretKeyByteEntry();
String alias = (String) name.nextElement();
Key k = ks.getKey(alias, keyPass);
SecretKey secretKey = null;
if (k instanceof JavaKeyStoreProvider.KeyMetadata) {
JavaKeyStoreProvider.KeyMetadata keyMetadata = (JavaKeyStoreProvider.KeyMetadata) k;
Field f = JavaKeyStoreProvider.KeyMetadata.class.getDeclaredField(METADATA_FIELDNAME);
f.setAccessible(true);
Metadata metadata = (Metadata) f.get(keyMetadata);
entry.bit_length = metadata.getBitLength();
entry.cipher_field = metadata.getAlgorithm();
entry.version = metadata.getVersions();
Constructor<RangerKeyStoreProvider.KeyMetadata> constructor = RangerKeyStoreProvider.KeyMetadata.class.getDeclaredConstructor(Metadata.class);
constructor.setAccessible(true);
RangerKeyStoreProvider.KeyMetadata nk = constructor.newInstance(metadata);
k = nk;
secretKey = new SecretKeySpec(k.getEncoded(), getAlgorithm(metadata.getAlgorithm()));
} else if (k instanceof KeyByteMetadata) {
Metadata metadata = ((KeyByteMetadata) k).metadata;
entry.cipher_field = metadata.getCipher();
entry.version = metadata.getVersions();
entry.bit_length = metadata.getBitLength();
if (k.getEncoded() != null && k.getEncoded().length > 0) {
secretKey = new SecretKeySpec(k.getEncoded(), getAlgorithm(metadata.getAlgorithm()));
} else {
KeyGenerator keyGenerator = KeyGenerator.getInstance(getAlgorithm(metadata.getCipher()));
keyGenerator.init(metadata.getBitLength());
byte[] keyByte = keyGenerator.generateKey().getEncoded();
secretKey = new SecretKeySpec(keyByte, getAlgorithm(metadata.getCipher()));
}
} else if (k instanceof KeyMetadata) {
Metadata metadata = ((KeyMetadata) k).metadata;
entry.bit_length = metadata.getBitLength();
entry.cipher_field = metadata.getCipher();
entry.version = metadata.getVersions();
if (k.getEncoded() != null && k.getEncoded().length > 0) {
secretKey = new SecretKeySpec(k.getEncoded(), getAlgorithm(metadata.getAlgorithm()));
} else {
KeyGenerator keyGenerator = KeyGenerator.getInstance(getAlgorithm(metadata.getCipher()));
keyGenerator.init(metadata.getBitLength());
byte[] keyByte = keyGenerator.generateKey().getEncoded();
secretKey = new SecretKeySpec(keyByte, getAlgorithm(metadata.getCipher()));
}
} else {
entry.bit_length = (k.getEncoded().length * NUMBER_OF_BITS_PER_BYTE);
entry.cipher_field = k.getAlgorithm();
if (alias.split("@").length == 2) {
entry.version = Integer.parseInt(alias.split("@")[1]) + 1;
} else {
entry.version = 1;
}
if (k.getEncoded() != null && k.getEncoded().length > 0) {
secretKey = new SecretKeySpec(k.getEncoded(), getAlgorithm(k.getAlgorithm()));
}
}
String keyName = alias.split("@")[0];
validateKeyName(keyName);
entry.attributes = "{\"key.acl.name\":\"" + keyName + "\"}";
entry.key = masterKeyProvider.encryptZoneKey(secretKey);
entry.date = ks.getCreationDate(alias);
entry.description = k.getFormat() + " - " + ks.getType();
deltaEntries.put(alias, entry);
}
} catch (Throwable t) {
logger.error("Unable to load keystore file ", t);
throw new IOException(t);
}
} else {
try {
ks = KeyStore.getInstance(fileFormat);
ks.load(stream, storePass);
deltaEntries.clear();
for (Enumeration<String> name = ks.aliases(); name.hasMoreElements(); ) {
SecretKeyEntry entry = new SecretKeyEntry();
String alias = (String) name.nextElement();
Key k = ks.getKey(alias, keyPass);
if (k instanceof JavaKeyStoreProvider.KeyMetadata) {
JavaKeyStoreProvider.KeyMetadata keyMetadata = (JavaKeyStoreProvider.KeyMetadata) k;
Field f = JavaKeyStoreProvider.KeyMetadata.class.getDeclaredField(METADATA_FIELDNAME);
f.setAccessible(true);
Metadata metadata = (Metadata) f.get(keyMetadata);
entry.bit_length = metadata.getBitLength();
entry.cipher_field = metadata.getAlgorithm();
entry.version = metadata.getVersions();
Constructor<RangerKeyStoreProvider.KeyMetadata> constructor = RangerKeyStoreProvider.KeyMetadata.class.getDeclaredConstructor(Metadata.class);
constructor.setAccessible(true);
RangerKeyStoreProvider.KeyMetadata nk = constructor.newInstance(metadata);
k = nk;
} else if (k instanceof KeyMetadata) {
Metadata metadata = ((KeyMetadata) k).metadata;
entry.bit_length = metadata.getBitLength();
entry.cipher_field = metadata.getCipher();
entry.version = metadata.getVersions();
} else {
entry.bit_length = (k.getEncoded().length * NUMBER_OF_BITS_PER_BYTE);
entry.cipher_field = k.getAlgorithm();
entry.version = (alias.split("@").length == 2) ? (Integer.parseInt(alias.split("@")[1]) + 1) : 1;
}
String keyName = alias.split("@")[0];
validateKeyName(keyName);
entry.attributes = "{\"key.acl.name\":\"" + keyName + "\"}";
Class<?> c = null;
Object o = null;
try {
c = Class.forName("com.sun.crypto.provider.KeyProtector");
Constructor<?> constructor = c.getDeclaredConstructor(char[].class);
constructor.setAccessible(true);
o = constructor.newInstance(masterKey);
// seal and store the key
Method m = c.getDeclaredMethod("seal", Key.class);
m.setAccessible(true);
entry.sealedKey = (SealedObject) m.invoke(o, k);
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
logger.error(e.getMessage());
throw new IOException(e.getMessage());
}
entry.date = ks.getCreationDate(alias);
entry.description = k.getFormat() + " - " + ks.getType();
deltaEntries.put(alias, entry);
}
} catch (Throwable t) {
logger.error("Unable to load keystore file ", t);
throw new IOException(t);
}
}
}
}
Aggregations