Java Code Examples for javax.crypto.SealedObject

The following examples show how to use javax.crypto.SealedObject. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: jdk8u60   Source File: KeyProtector.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Seals the given cleartext key, using the password provided at
 * construction time
 */
SealedObject seal(Key key)
    throws Exception
{
    // create a random salt (8 bytes)
    byte[] salt = new byte[8];
    SunJCE.getRandom().nextBytes(salt);

    // create PBE parameters from salt and iteration count
    PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20);

    // create PBE key from password
    PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
    SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
    pbeKeySpec.clearPassword();

    // seal key
    Cipher cipher;

    PBEWithMD5AndTripleDESCipher cipherSpi;
    cipherSpi = new PBEWithMD5AndTripleDESCipher();
    cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(),
                                       "PBEWithMD5AndTripleDES");
    cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec);
    return new SealedObjectForKeyProtector(key, cipher);
}
 
Example 2
Source Project: blockchain-java   Source File: WalletUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 保存钱包数据
 */
private void saveToDisk(Wallets wallets) {
    try {
        if (wallets == null) {
            log.error("Fail to save wallet to file ! wallets is null ");
            throw new Exception("ERROR: Fail to save wallet to file !");
        }
        SecretKeySpec sks = new SecretKeySpec(CIPHER_TEXT, ALGORITHM);
        // Create cipher
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, sks);
        SealedObject sealedObject = new SealedObject(wallets, cipher);
        // Wrap the output stream
        @Cleanup CipherOutputStream cos = new CipherOutputStream(
                new BufferedOutputStream(new FileOutputStream(WALLET_FILE)), cipher);
        @Cleanup ObjectOutputStream outputStream = new ObjectOutputStream(cos);
        outputStream.writeObject(sealedObject);
    } catch (Exception e) {
        log.error("Fail to save wallet to disk !", e);
        throw new RuntimeException("Fail to save wallet to disk !");
    }
}
 
Example 3
Source Project: blockchain-java   Source File: WalletUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 加载钱包数据
 */
private Wallets loadFromDisk() {
    try {
        SecretKeySpec sks = new SecretKeySpec(CIPHER_TEXT, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, sks);
        @Cleanup CipherInputStream cipherInputStream = new CipherInputStream(
                new BufferedInputStream(new FileInputStream(WALLET_FILE)), cipher);
        @Cleanup ObjectInputStream inputStream = new ObjectInputStream(cipherInputStream);
        SealedObject sealedObject = (SealedObject) inputStream.readObject();
        return (Wallets) sealedObject.getObject(cipher);
    } catch (Exception e) {
        log.error("Fail to load wallet from disk ! ", e);
        throw new RuntimeException("Fail to load wallet from disk ! ");
    }
}
 
Example 4
/**
 * Encrypt a properties if the data definition (model-specific) requires it.
 * 
 * @param propertyQName             the property qualified name
 * @param inbound                   the property to encrypt
 * @return                          the encrypted property or the original if encryption is not required
 */
public Serializable encrypt(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;
    }
    Serializable outbound = encryptor.sealObject(KeyProvider.ALIAS_METADATA, null, inbound);
    // Done
    return outbound;
}
 
Example 5
/**
 * 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);
    }
}
 
Example 6
@Override
Serializable convert(Serializable value)
{
    if (value == null)
    {
        return null;
    }
    else if (value instanceof SealedObject)
    {
        return value;
    }
    else
    {
        throw new IllegalArgumentException("Encrypted properties must be encrypted by the client.");
    }
}
 
Example 7
@Override
public Serializable sealObject(String keyAlias, AlgorithmParameters params, Serializable input)
{
    if (input == null)
    {
        return null;
    }
    Cipher cipher = getCipher(keyAlias, params, Cipher.ENCRYPT_MODE);
    if (cipher == null)
    {
        return input;
    }
    try
    {
        return new SealedObject(input, cipher);
    }
    catch (Exception e)
    {
        throw new AlfrescoRuntimeException("Failed to seal object", e);
    }
}
 
Example 8
/**
 * Seals the given cleartext key, using the password provided at
 * construction time
 */
SealedObject seal(Key key)
    throws Exception
{
    // create a random salt (8 bytes)
    byte[] salt = new byte[8];
    SunJCE.getRandom().nextBytes(salt);

    // create PBE parameters from salt and iteration count
    PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, ITERATION_COUNT);

    // create PBE key from password
    PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
    SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
    pbeKeySpec.clearPassword();

    // seal key
    Cipher cipher;

    PBEWithMD5AndTripleDESCipher cipherSpi;
    cipherSpi = new PBEWithMD5AndTripleDESCipher();
    cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(),
                                       "PBEWithMD5AndTripleDES");
    cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec);
    return new SealedObjectForKeyProtector(key, cipher);
}
 
Example 9
Source Project: openjdk-jdk9   Source File: KeyProtector.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Seals the given cleartext key, using the password provided at
 * construction time
 */
SealedObject seal(Key key)
    throws Exception
{
    // create a random salt (8 bytes)
    byte[] salt = new byte[8];
    SunJCE.getRandom().nextBytes(salt);

    // create PBE parameters from salt and iteration count
    PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20);

    // create PBE key from password
    PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
    SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
    pbeKeySpec.clearPassword();

    // seal key
    Cipher cipher;

    PBEWithMD5AndTripleDESCipher cipherSpi;
    cipherSpi = new PBEWithMD5AndTripleDESCipher();
    cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(),
                                       "PBEWithMD5AndTripleDES");
    cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec);
    return new SealedObjectForKeyProtector(key, cipher);
}
 
Example 10
Source Project: jdk8u-jdk   Source File: KeyProtector.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Seals the given cleartext key, using the password provided at
 * construction time
 */
SealedObject seal(Key key)
    throws Exception
{
    // create a random salt (8 bytes)
    byte[] salt = new byte[8];
    SunJCE.getRandom().nextBytes(salt);

    // create PBE parameters from salt and iteration count
    PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20);

    // create PBE key from password
    PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
    SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
    pbeKeySpec.clearPassword();

    // seal key
    Cipher cipher;

    PBEWithMD5AndTripleDESCipher cipherSpi;
    cipherSpi = new PBEWithMD5AndTripleDESCipher();
    cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(),
                                       "PBEWithMD5AndTripleDES");
    cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec);
    return new SealedObjectForKeyProtector(key, cipher);
}
 
Example 11
Source Project: hottub   Source File: KeyProtector.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Seals the given cleartext key, using the password provided at
 * construction time
 */
SealedObject seal(Key key)
    throws Exception
{
    // create a random salt (8 bytes)
    byte[] salt = new byte[8];
    SunJCE.getRandom().nextBytes(salt);

    // create PBE parameters from salt and iteration count
    PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20);

    // create PBE key from password
    PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
    SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
    pbeKeySpec.clearPassword();

    // seal key
    Cipher cipher;

    PBEWithMD5AndTripleDESCipher cipherSpi;
    cipherSpi = new PBEWithMD5AndTripleDESCipher();
    cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(),
                                       "PBEWithMD5AndTripleDES");
    cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec);
    return new SealedObjectForKeyProtector(key, cipher);
}
 
Example 12
/**
 * Seals the given cleartext key, using the password provided at
 * construction time
 */
SealedObject seal(Key key)
    throws Exception
{
    // create a random salt (8 bytes)
    byte[] salt = new byte[8];
    SunJCE.getRandom().nextBytes(salt);

    // create PBE parameters from salt and iteration count
    PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20);

    // create PBE key from password
    PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
    SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
    pbeKeySpec.clearPassword();

    // seal key
    Cipher cipher;

    PBEWithMD5AndTripleDESCipher cipherSpi;
    cipherSpi = new PBEWithMD5AndTripleDESCipher();
    cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(),
                                       "PBEWithMD5AndTripleDES");
    cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec);
    return new SealedObjectForKeyProtector(key, cipher);
}
 
Example 13
Source Project: openjdk-8   Source File: KeyProtector.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Seals the given cleartext key, using the password provided at
 * construction time
 */
SealedObject seal(Key key)
    throws Exception
{
    // create a random salt (8 bytes)
    byte[] salt = new byte[8];
    SunJCE.getRandom().nextBytes(salt);

    // create PBE parameters from salt and iteration count
    PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20);

    // create PBE key from password
    PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
    SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
    pbeKeySpec.clearPassword();

    // seal key
    Cipher cipher;

    PBEWithMD5AndTripleDESCipher cipherSpi;
    cipherSpi = new PBEWithMD5AndTripleDESCipher();
    cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(),
                                       "PBEWithMD5AndTripleDES");
    cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec);
    return new SealedObjectForKeyProtector(key, cipher);
}
 
Example 14
Source Project: jdk8u-jdk   Source File: KeyProtector.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Seals the given cleartext key, using the password provided at
 * construction time
 */
SealedObject seal(Key key)
    throws Exception
{
    // create a random salt (8 bytes)
    byte[] salt = new byte[8];
    SunJCE.getRandom().nextBytes(salt);

    // create PBE parameters from salt and iteration count
    PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20);

    // create PBE key from password
    PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
    SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
    pbeKeySpec.clearPassword();

    // seal key
    Cipher cipher;

    PBEWithMD5AndTripleDESCipher cipherSpi;
    cipherSpi = new PBEWithMD5AndTripleDESCipher();
    cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(),
                                       "PBEWithMD5AndTripleDES");
    cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec);
    return new SealedObjectForKeyProtector(key, cipher);
}
 
Example 15
Source Project: jdk8u-dev-jdk   Source File: KeyProtector.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Seals the given cleartext key, using the password provided at
 * construction time
 */
SealedObject seal(Key key)
    throws Exception
{
    // create a random salt (8 bytes)
    byte[] salt = new byte[8];
    SunJCE.getRandom().nextBytes(salt);

    // create PBE parameters from salt and iteration count
    PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20);

    // create PBE key from password
    PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
    SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
    pbeKeySpec.clearPassword();

    // seal key
    Cipher cipher;

    PBEWithMD5AndTripleDESCipher cipherSpi;
    cipherSpi = new PBEWithMD5AndTripleDESCipher();
    cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(),
                                       "PBEWithMD5AndTripleDES");
    cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec);
    return new SealedObjectForKeyProtector(key, cipher);
}
 
Example 16
Source Project: ranger   Source File: RangerKeyStore.java    License: Apache License 2.0 6 votes vote down vote up
private SealedObject sealKey(Key key, char[] password) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("==> RangerKeyStore.sealKey()");
    }
    // Create SecretKey
    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndTripleDES");
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
    pbeKeySpec.clearPassword();

    // Generate random bytes + set up the PBEParameterSpec
    SecureRandom random = new SecureRandom();
    byte[] salt = new byte[8];
    random.nextBytes(salt);
    PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20);

    // Seal the Key
    Cipher cipher = Cipher.getInstance("PBEWithMD5AndTripleDES");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, pbeSpec);
    if (logger.isDebugEnabled()) {
        logger.debug("<== RangerKeyStore.sealKey()");
    }
    return new RangerSealedObject(key, cipher);
}
 
Example 17
Source Project: ranger   Source File: RangerKeyStore.java    License: Apache License 2.0 6 votes vote down vote up
private Key unsealKey(SealedObject sealedKey, char[] password) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("==> RangerKeyStore.unsealKey()");
    }
    // Create SecretKey
    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndTripleDES");
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
    pbeKeySpec.clearPassword();

    // Get the AlgorithmParameters from RangerSealedObject
    AlgorithmParameters algorithmParameters = null;
    if (sealedKey instanceof RangerSealedObject) {
        algorithmParameters = ((RangerSealedObject) sealedKey).getParameters();
    } else {
        algorithmParameters = new RangerSealedObject(sealedKey).getParameters();
    }

    // Unseal the Key
    Cipher cipher = Cipher.getInstance("PBEWithMD5AndTripleDES");
    cipher.init(Cipher.DECRYPT_MODE, secretKey, algorithmParameters);
    if (logger.isDebugEnabled()) {
        logger.debug("<== RangerKeyStore.unsealKey()");
    }
    return (Key) sealedKey.getObject(cipher);
}
 
Example 18
Source Project: dragonwell8_jdk   Source File: KeyProtector.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Seals the given cleartext key, using the password provided at
 * construction time
 */
SealedObject seal(Key key)
    throws Exception
{
    // create a random salt (8 bytes)
    byte[] salt = new byte[8];
    SunJCE.getRandom().nextBytes(salt);

    // create PBE parameters from salt and iteration count
    PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, ITERATION_COUNT);

    // create PBE key from password
    PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
    SecretKey sKey = null;
    Cipher cipher;
    try {
        sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
        pbeKeySpec.clearPassword();

        // seal key
        PBEWithMD5AndTripleDESCipher cipherSpi;
        cipherSpi = new PBEWithMD5AndTripleDESCipher();
        cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(),
                                       "PBEWithMD5AndTripleDES");
        cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec);
    } finally {
        if (sKey != null) sKey.destroy();
    }
    return new SealedObjectForKeyProtector(key, cipher);
}
 
Example 19
public static void main(String[] args) throws IOException,
        IllegalBlockSizeException, ClassNotFoundException,
        BadPaddingException {
    Cipher nullCipher = new NullCipher();

    // Seal
    SealedObject so = new SealedObject(SEAL_STR, nullCipher);

    // Unseal and compare
    if (!(SEAL_STR.equals(so.getObject(nullCipher)))) {
        throw new RuntimeException("Unseal and compare failed.");
    }

    System.out.println("Test passed.");
}
 
Example 20
Source Project: TencentKona-8   Source File: KeyProtector.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Seals the given cleartext key, using the password provided at
 * construction time
 */
SealedObject seal(Key key)
    throws Exception
{
    // create a random salt (8 bytes)
    byte[] salt = new byte[8];
    SunJCE.getRandom().nextBytes(salt);

    // create PBE parameters from salt and iteration count
    PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, ITERATION_COUNT);

    // create PBE key from password
    PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
    SecretKey sKey = null;
    Cipher cipher;
    try {
        sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
        pbeKeySpec.clearPassword();

        // seal key
        PBEWithMD5AndTripleDESCipher cipherSpi;
        cipherSpi = new PBEWithMD5AndTripleDESCipher();
        cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(),
                                       "PBEWithMD5AndTripleDES");
        cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec);
    } finally {
        if (sKey != null) sKey.destroy();
    }
    return new SealedObjectForKeyProtector(key, cipher);
}
 
Example 21
public static void main(String[] args) throws IOException,
        IllegalBlockSizeException, ClassNotFoundException,
        BadPaddingException {
    Cipher nullCipher = new NullCipher();

    // Seal
    SealedObject so = new SealedObject(SEAL_STR, nullCipher);

    // Unseal and compare
    if (!(SEAL_STR.equals(so.getObject(nullCipher)))) {
        throw new RuntimeException("Unseal and compare failed.");
    }

    System.out.println("Test passed.");
}
 
Example 22
Source Project: jdk8u60   Source File: KeyProtector.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Unseals the sealed key.
 */
Key unseal(SealedObject so)
    throws NoSuchAlgorithmException, UnrecoverableKeyException
{
    try {
        // create PBE key from password
        PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
        SecretKey skey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
        pbeKeySpec.clearPassword();

        SealedObjectForKeyProtector soForKeyProtector = null;
        if (!(so instanceof SealedObjectForKeyProtector)) {
            soForKeyProtector = new SealedObjectForKeyProtector(so);
        } else {
            soForKeyProtector = (SealedObjectForKeyProtector)so;
        }
        AlgorithmParameters params = soForKeyProtector.getParameters();
        if (params == null) {
            throw new UnrecoverableKeyException("Cannot get " +
                                                "algorithm parameters");
        }
        PBEWithMD5AndTripleDESCipher cipherSpi;
        cipherSpi = new PBEWithMD5AndTripleDESCipher();
        Cipher cipher = new CipherForKeyProtector(cipherSpi,
                                                  SunJCE.getInstance(),
                                                  "PBEWithMD5AndTripleDES");
        cipher.init(Cipher.DECRYPT_MODE, skey, params);
        return (Key)soForKeyProtector.getObject(cipher);
    } catch (NoSuchAlgorithmException ex) {
        // Note: this catch needed to be here because of the
        // later catch of GeneralSecurityException
        throw ex;
    } catch (IOException ioe) {
        throw new UnrecoverableKeyException(ioe.getMessage());
    } catch (ClassNotFoundException cnfe) {
        throw new UnrecoverableKeyException(cnfe.getMessage());
    } catch (GeneralSecurityException gse) {
        throw new UnrecoverableKeyException(gse.getMessage());
    }
}
 
Example 23
Source Project: JPPF   Source File: CryptoSerialization.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(final Object o, final OutputStream os) throws Exception {
  // create a cipher instance
  Cipher cipher = Cipher.getInstance(Helper.getTransformation());
  // initialize the cipher with the key stored in the secured keystore
  cipher.init(Cipher.WRAP_MODE, getSecretKey(), getInitializationVector());
  // generate a new key that we will use to encrypt the data
  final SecretKey key = generateKey();
  // encrypt the new key, using the secret key found in the keystore
  final byte[] keyBytes = cipher.wrap(key);
  // now we write the encrypted key before the data
  final DataOutputStream dos = new DataOutputStream(os);
  // write the key length
  dos.writeInt(keyBytes.length);
  // write the key content
  dos.write(keyBytes);
  dos.flush();

  // get a new cipher for the actual encryption
  cipher = Cipher.getInstance(Helper.getTransformation());
  // init the cipher in encryption mode
  cipher.init(Cipher.ENCRYPT_MODE, key, getInitializationVector());
  // encrypt the plain riginal object into a sealed object
  final SealedObject sealed = new SealedObject((Serializable) o, cipher);
  // serialize the sealed object
  getDelegate().serialize(sealed, os);
}
 
Example 24
Source Project: JPPF   Source File: CryptoSerialization.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object deserialize(final InputStream is) throws Exception {
  // start by reading the secret key to use to decrypt the data
  final DataInputStream dis = new DataInputStream(is);
  // read the length of the key
  final int keyLength = dis.readInt();
  // read the encrypted key
  final byte[] keyBytes = new byte[keyLength];
  int count = 0;
  while (count < keyLength) {
    final int n = dis.read(keyBytes, count, keyLength - count);
    if (n > 0) count += n;
    else throw new EOFException("could only read " + count + " bytes of the key, out of " + keyLength);
  }
  // decrypt the key using the initial key stored in the keystore
  Cipher cipher = Cipher.getInstance(Helper.getTransformation());
  cipher.init(Cipher.UNWRAP_MODE, getSecretKey(), getInitializationVector());
  final SecretKey key = (SecretKey) cipher.unwrap(keyBytes, Helper.getAlgorithm(), Cipher.SECRET_KEY);

  // get a new cipher for the actual decryption
  cipher = Cipher.getInstance(Helper.getTransformation());
  // init the cipher in decryption mode with the retireved key
  cipher.init(Cipher.DECRYPT_MODE, key, getInitializationVector());
  // deserialize a sealed (encrypted) object
  final SealedObject sealed = (SealedObject) getDelegate().deserialize(is);
  // decrypt the sealed object into the plain riginal object
  return sealed.getObject(cipher);
}
 
Example 25
Source Project: openjdk-jdk8u   Source File: KeyProtector.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Seals the given cleartext key, using the password provided at
 * construction time
 */
SealedObject seal(Key key)
    throws Exception
{
    // create a random salt (8 bytes)
    byte[] salt = new byte[8];
    SunJCE.getRandom().nextBytes(salt);

    // create PBE parameters from salt and iteration count
    PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, ITERATION_COUNT);

    // create PBE key from password
    PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
    SecretKey sKey = null;
    Cipher cipher;
    try {
        sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
        pbeKeySpec.clearPassword();

        // seal key
        PBEWithMD5AndTripleDESCipher cipherSpi;
        cipherSpi = new PBEWithMD5AndTripleDESCipher();
        cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(),
                                       "PBEWithMD5AndTripleDES");
        cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec);
    } finally {
        if (sKey != null) sKey.destroy();
    }
    return new SealedObjectForKeyProtector(key, cipher);
}
 
Example 26
public static void main(String[] args) throws IOException,
        IllegalBlockSizeException, ClassNotFoundException,
        BadPaddingException {
    Cipher nullCipher = new NullCipher();

    // Seal
    SealedObject so = new SealedObject(SEAL_STR, nullCipher);

    // Unseal and compare
    if (!(SEAL_STR.equals(so.getObject(nullCipher)))) {
        throw new RuntimeException("Unseal and compare failed.");
    }

    System.out.println("Test passed.");
}
 
Example 27
public static void main(String[] args) throws IOException,
        IllegalBlockSizeException, ClassNotFoundException,
        BadPaddingException {
    Cipher nullCipher = new NullCipher();

    // Seal
    SealedObject so = new SealedObject(SEAL_STR, nullCipher);

    // Unseal and compare
    if (!(SEAL_STR.equals(so.getObject(nullCipher)))) {
        throw new RuntimeException("Unseal and compare failed.");
    }

    System.out.println("Test passed.");
}
 
Example 28
Source Project: Bytecoder   Source File: KeyProtector.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Seals the given cleartext key, using the password provided at
 * construction time
 */
SealedObject seal(Key key)
    throws Exception
{
    // create a random salt (8 bytes)
    byte[] salt = new byte[8];
    SunJCE.getRandom().nextBytes(salt);

    // create PBE parameters from salt and iteration count
    PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, ITERATION_COUNT);

    // create PBE key from password
    PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
    SecretKey sKey = null;
    Cipher cipher;
    try {
        sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES", false);
        pbeKeySpec.clearPassword();

        // seal key
        PBEWithMD5AndTripleDESCipher cipherSpi;
        cipherSpi = new PBEWithMD5AndTripleDESCipher();
        cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(),
                                           "PBEWithMD5AndTripleDES");
        cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec);
    } finally {
        if (sKey != null) sKey.destroy();
    }
    return new SealedObjectForKeyProtector(key, cipher);
}
 
Example 29
Source Project: openjdk-jdk9   Source File: KeyProtector.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Unseals the sealed key.
 */
Key unseal(SealedObject so)
    throws NoSuchAlgorithmException, UnrecoverableKeyException
{
    try {
        // create PBE key from password
        PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
        SecretKey skey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
        pbeKeySpec.clearPassword();

        SealedObjectForKeyProtector soForKeyProtector = null;
        if (!(so instanceof SealedObjectForKeyProtector)) {
            soForKeyProtector = new SealedObjectForKeyProtector(so);
        } else {
            soForKeyProtector = (SealedObjectForKeyProtector)so;
        }
        AlgorithmParameters params = soForKeyProtector.getParameters();
        if (params == null) {
            throw new UnrecoverableKeyException("Cannot get " +
                                                "algorithm parameters");
        }
        PBEWithMD5AndTripleDESCipher cipherSpi;
        cipherSpi = new PBEWithMD5AndTripleDESCipher();
        Cipher cipher = new CipherForKeyProtector(cipherSpi,
                                                  SunJCE.getInstance(),
                                                  "PBEWithMD5AndTripleDES");
        cipher.init(Cipher.DECRYPT_MODE, skey, params);
        return (Key)soForKeyProtector.getObject(cipher);
    } catch (NoSuchAlgorithmException ex) {
        // Note: this catch needed to be here because of the
        // later catch of GeneralSecurityException
        throw ex;
    } catch (IOException ioe) {
        throw new UnrecoverableKeyException(ioe.getMessage());
    } catch (ClassNotFoundException cnfe) {
        throw new UnrecoverableKeyException(cnfe.getMessage());
    } catch (GeneralSecurityException gse) {
        throw new UnrecoverableKeyException(gse.getMessage());
    }
}
 
Example 30
public static void main(String[] args) throws IOException,
        IllegalBlockSizeException, ClassNotFoundException,
        BadPaddingException {
    Cipher nullCipher = new NullCipher();

    // Seal
    SealedObject so = new SealedObject(SEAL_STR, nullCipher);

    // Unseal and compare
    if (!(SEAL_STR.equals(so.getObject(nullCipher)))) {
        throw new RuntimeException("Unseal and compare failed.");
    }

    System.out.println("Test passed.");
}