Example usage for javax.crypto.spec DESKeySpec DESKeySpec

List of usage examples for javax.crypto.spec DESKeySpec DESKeySpec

Introduction

In this page you can find the example usage for javax.crypto.spec DESKeySpec DESKeySpec.

Prototype

public DESKeySpec(byte[] key) throws InvalidKeyException 

Source Link

Document

Creates a DESKeySpec object using the first 8 bytes in key as the key material for the DES key.

Usage

From source file:com.ikon.util.SecureStore.java

/**
 * DES decoder//from   w w w  . j  a v  a 2  s . com
 */
public static byte[] desDecode(String key, byte[] src)
        throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException,
        InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    DESKeySpec keySpec = new DESKeySpec(key.getBytes("UTF8"));
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey sKey = keyFactory.generateSecret(keySpec);

    Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
    cipher.init(Cipher.DECRYPT_MODE, sKey);
    byte[] dst = cipher.doFinal(src);

    return dst;
}

From source file:net.sf.hajdbc.codec.crypto.CipherCodecFactoryTest.java

@Before
public void before() throws Exception {
    File file = File.createTempFile("ha-jdbc", "keystore");

    SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
    this.key = factory.generateSecret(new DESKeySpec(Base64.decodeBase64(KEY.getBytes())));
    KeyStore store = KeyStore.getInstance(CipherCodecFactory.Property.KEYSTORE_TYPE.defaultValue);
    store.load(null, null);/* ww w .j  a va  2s. c o  m*/
    store.setKeyEntry(CipherCodecFactory.Property.KEY_ALIAS.defaultValue, this.key, KEY_PASSWORD.toCharArray(),
            null);

    FileOutputStream out = new FileOutputStream(file);
    try {
        store.store(out, STORE_PASSWORD.toCharArray());
    } finally {
        Resources.close(out);
    }

    System.setProperty(CipherCodecFactory.Property.KEYSTORE_FILE.name, file.getPath());
    System.setProperty(CipherCodecFactory.Property.KEYSTORE_PASSWORD.name, STORE_PASSWORD);
    System.setProperty(CipherCodecFactory.Property.KEY_PASSWORD.name, KEY_PASSWORD);
}

From source file:org.mayocat.security.DefaultCipher.java

private String crypt(String input, Mode mode) throws EncryptionException {
    if (Strings.isNullOrEmpty(this.configuration.getEncryptionKey())) {
        throw new EncryptionException("Invalid or missing cookie encryption key in configuration file. "
                + "You MUST specify a key in order to support cookie authentication.");
    }/*from  w  ww . j  a  v  a2 s  .  co m*/

    try {
        byte[] in = input.getBytes();

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        byte[] keyBytes = this.configuration.getEncryptionKey().getBytes("UTF-8");
        DESKeySpec desKeySpec = new DESKeySpec(keyBytes);
        SecretKey key = keyFactory.generateSecret(desKeySpec);

        javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding");
        IvParameterSpec spec = null;
        if (cipher.getParameters() != null) {
            spec = cipher.getParameters().getParameterSpec(IvParameterSpec.class);
        }

        switch (mode) {
        case CRYPT:
        default:
            if (spec != null) {
                cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, key, spec);
            } else {
                cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, key);
            }
            byte[] encrypted = cipher.doFinal(in);
            return new String(Base64.encodeBase64(encrypted));
        case DECRYPT:
            if (spec != null) {
                cipher.init(javax.crypto.Cipher.DECRYPT_MODE, key, spec);
            } else {
                cipher.init(javax.crypto.Cipher.DECRYPT_MODE, key);
            }
            byte[] decrypted = cipher.doFinal(Base64.decodeBase64(in));
            return new String(decrypted);
        }

    } catch (BadPaddingException e) {
        this.logger.warn("Bad padding when attempting to decipher cookies. Key changed ?");
        throw new EncryptionException(e);
    } catch (Exception e) {
        this.logger.error("Fail to perform cookie crypt or decrypt operation", e);
        throw new EncryptionException(e);
    }
}

From source file:club.jmint.crossing.specs.Security.java

public static String desEncrypt(String data, String key) throws CrossException {
    String ret = null;//from  w  ww  . ja va2  s .c om
    try {
        DESKeySpec desKey = new DESKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(desKey);

        Cipher cipher = Cipher.getInstance(CIPHER_DES_ALGORITHM);
        SecureRandom random = new SecureRandom();
        cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
        byte[] results = cipher.doFinal(data.getBytes("UTF-8"));
        ret = Base64.encodeBase64String(results);
    } catch (Exception e) {
        CrossLog.printStackTrace(e);
        throw new CrossException(ErrorCode.COMMON_ERR_ENCRYPTION.getCode(),
                ErrorCode.COMMON_ERR_ENCRYPTION.getInfo());
    }
    return ret;
}

From source file:org.toobsframework.util.Crypto.java

protected Crypto() {
    try {/* w w  w. j a  v  a2s.c o  m*/
        DESKeySpec keySpec = new DESKeySpec(keyData);
        SecretKey key = SecretKeyFactory.getInstance(ALGORITHM).generateSecret(keySpec);
        initEncryptCipher(key);
        initDecryptCipher(key);
    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.glaf.core.security.SecurityUtils.java

/**
 * DES/*from w w  w . ja v  a 2s  .c  o  m*/
 * 
 * @param data
 *            
 * @param key
 *            ???8?
 * @return ?
 */
public static String decode(String key, String data) {
    if (data == null) {
        return null;
    }
    try {
        DESKeySpec dks = new DESKeySpec(key.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // key??8?
        Key secretKey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
        IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
        AlgorithmParameterSpec paramSpec = iv;
        cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
        return new String(cipher.doFinal(hex2byte(data.getBytes())));
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new SecurityException(ex);
    }
}

From source file:org.talend.commons.utils.PasswordEncryptUtil.java

private static SecretKey getSecretKeyUTF8() throws Exception {
    if (passwordKey == null) {
        byte rawKeyData[] = rawKey.getBytes(CHARSET);
        DESKeySpec dks = new DESKeySpec(rawKeyData);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); //$NON-NLS-1$
        passwordKey = keyFactory.generateSecret(dks);
    }//from  w  w  w  . jav a2 s. c  om
    return passwordKey;
}

From source file:org.jajim.utilidades.cifrado.Cifrador.java

/**
 * Constructor de la clase. Inicializa el cifrador.
 * <p>/*from w ww. jav a  2 s.  c o m*/
 * @throws ImposibleCifrarDescifrarException Si no se puede instanciar un ci frador adecuado.
 */
public Cifrador() throws ImposibleCifrarDescifrarException {

    try {
        // Inicializacin de la clave
        SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
        String clave = "cjliamve";
        DESKeySpec kspec = new DESKeySpec(clave.getBytes());
        sk = skf.generateSecret(kspec);
        // Inicializacin del cifrador
        cifrado = Cipher.getInstance("DES");
    } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException
            | NoSuchPaddingException e) {
        // En caso de que se produzca un error se escribe en el fichero
        // de log y se lanza una excepcin
        ManejadorDeLogs mdl = ManejadorDeLogs.getManejadorDeLogs();
        mdl.escribir("No se puede crear un cifrador de DES");
        throw new ImposibleCifrarDescifrarException();
    }
}

From source file:com.sirius.utils.encrypt.DESEncryptor.java

private Key getKey(Object key) throws Exception {
    if (key instanceof String) {
        DESKeySpec dks = new DESKeySpec(((String) key).getBytes());
        SecretKeyFactory skf = SecretKeyFactory.getInstance(ALGORITHM, security_provider);
        return skf.generateSecret(dks);
    } else {//from w  w w. j  a va2 s  .  c  om
        throw new EncryptException("Invilid key.");
    }
}

From source file:org.yes.cart.shoppingcart.support.impl.AbstractCryptedTuplizerImpl.java

/**
 * Default Constructor.//from  ww  w .  j  a  v a 2  s .  com
 *
 * @param keyRingPassword      key ring password to use.
 * @param secretKeyFactoryName Secret Key Factory Name.
 * @param cipherName           Cipher name.
 */
public AbstractCryptedTuplizerImpl(final String keyRingPassword, final String secretKeyFactoryName,
        final String cipherName) {

    try {
        final DESKeySpec desKeySpec = new DESKeySpec(keyRingPassword.getBytes());

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(secretKeyFactoryName);
        secretKey = keyFactory.generateSecret(desKeySpec);

        // Create Cipher
        desCipher = Cipher.getInstance(cipherName);
        desCipher.init(Cipher.ENCRYPT_MODE, secretKey);

        // create uncipher
        desUnCipher = Cipher.getInstance(cipherName);
        desUnCipher.init(Cipher.DECRYPT_MODE, secretKey);
    } catch (Exception ike) {
        LOG.error(ike.getMessage(), ike);
        throw new RuntimeException("Unable to load Cipher for CookieTuplizer", ike);
    }

}