public String encrypt(String plainText) { try { checkThatKeystoreFileExists(); byte[] bytes = plainText.getBytes(SecurityConstants.CHARSET); byte[] enc = getCipher(Cipher.ENCRYPT_MODE).doFinal(bytes); return new String(Base64.encodeBase64(enc), SecurityConstants.CHARSET); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } }
protected SecretKey getDefaultSecretKey() throws Exception { String keyPassword = nextSecureHexString(8); KeySpec keySpec = new PBEKeySpec(keyPassword.toCharArray(), SecurityConstants.SALT, SecurityConstants.ITERATION_COUNT, 56); SecretKey secretKey = SecretKeyFactory.getInstance(SecurityConstants.ALGORITHM) .generateSecret(keySpec); return secretKey; }
protected SecretKey getSecretKey() throws Exception { String password = getKeyStorePassword(); KeyStore.ProtectionParameter param = new KeyStore.PasswordProtection(password.toCharArray()); KeyStore ks = getKeyStore(password); KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry) ks.getEntry( SecurityConstants.ALIAS_SYM_SECRET_KEY, param); if (entry == null) { log.debug("Generating secret key"); entry = new KeyStore.SecretKeyEntry(getDefaultSecretKey()); ks.setEntry(SecurityConstants.ALIAS_SYM_SECRET_KEY, entry, param); saveKeyStore(ks, password); } else { log.debug("Retrieving secret key"); } return entry.getSecretKey(); }
protected Cipher getCipher(int mode) throws Exception { if (secretKey == null) { secretKey = getSecretKey(); } Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm()); initializeCipher(cipher, mode); log.debug("Using {} algorithm provided by {}.", cipher.getAlgorithm(), cipher.getProvider() .getName()); return cipher; }
public String nextSecureHexString(int len) { if (len <= 0) throw new IllegalArgumentException("length must be positive"); SecureRandom secRan = getSecRan(); MessageDigest alg = null; try { alg = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { return null; } alg.reset(); int numIter = len / 40 + 1; StringBuffer outBuffer = new StringBuffer(); for (int iter = 1; iter < numIter + 1; iter++) { byte randomBytes[] = new byte[40]; secRan.nextBytes(randomBytes); alg.update(randomBytes); byte hash[] = alg.digest(); for (int i = 0; i < hash.length; i++) { Integer c = new Integer(hash[i]); String hex = Integer.toHexString(c.intValue() + 128); if (hex.length() == 1) hex = "0" + hex; outBuffer.append(hex); } } return outBuffer.toString().substring(0, len); }
public String decrypt(String encText) { try { checkThatKeystoreFileExists(); byte[] dec = Base64.decodeBase64(encText.getBytes()); byte[] bytes = getCipher(Cipher.DECRYPT_MODE).doFinal(dec); return new String(bytes, SecurityConstants.CHARSET); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } }