Java Examples for javax.crypto.spec.PBEParameterSpec
The following java examples will help you to understand the usage of javax.crypto.spec.PBEParameterSpec. These source code samples are taken from different open source projects.
Example 1
| Project: ChatSecureAndroid-master File: OpenSSLPBECommon.java View source code |
protected static Cipher initializeCipher(char[] password, byte[] salt, int cipherMode, final String algorithm, int iterationCount) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException, InvalidAlgorithmParameterException {
PBEKeySpec keySpec = new PBEKeySpec(password);
SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
SecretKey key = factory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(cipherMode, key, new PBEParameterSpec(salt, iterationCount));
return cipher;
}Example 2
| Project: java_security-master File: PBETest.java View source code |
// 用jdk实现:
public static void jdkPBE() {
try {
// �始化�
SecureRandom random = new SecureRandom();
byte[] salt = random.generateSeed(8);
// �令与密钥
String password = "timliu";
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWITHMD5andDES");
Key key = factory.generateSecret(pbeKeySpec);
// åŠ å¯†
PBEParameterSpec pbeParameterSpac = new PBEParameterSpec(salt, 100);
Cipher cipher = Cipher.getInstance("PBEWITHMD5andDES");
cipher.init(Cipher.ENCRYPT_MODE, key, pbeParameterSpac);
byte[] result = cipher.doFinal(src.getBytes());
System.out.println("jdk pbe encrypt:" + Hex.encodeHexString(result));
// 解密
cipher.init(Cipher.DECRYPT_MODE, key, pbeParameterSpac);
result = cipher.doFinal(result);
System.out.println("jdk pbe decrypt:" + new String(result));
} catch (Exception e) {
e.printStackTrace();
}
}Example 3
| Project: prive-android-master File: OpenSSLPBECommon.java View source code |
protected static Cipher initializeCipher(char[] password, byte[] salt, int cipherMode, final String algorithm, int iterationCount) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException, InvalidAlgorithmParameterException {
PBEKeySpec keySpec = new PBEKeySpec(password);
SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
SecretKey key = factory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(cipherMode, key, new PBEParameterSpec(salt, iterationCount));
return cipher;
}Example 4
| Project: Zom-Android-master File: OpenSSLPBECommon.java View source code |
protected static Cipher initializeCipher(char[] password, byte[] salt, int cipherMode, final String algorithm, int iterationCount) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException, InvalidAlgorithmParameterException {
PBEKeySpec keySpec = new PBEKeySpec(password);
SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
SecretKey key = factory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(cipherMode, key, new PBEParameterSpec(salt, iterationCount));
return cipher;
}Example 5
| Project: java-presentation-manager-master File: StringEncrypter.java View source code |
public void init(char[] pass, byte[] salt, int iterations) throws SecurityException {
try {
PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec(salt, 20);
SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey k = kf.generateSecret(new javax.crypto.spec.PBEKeySpec(pass));
encryptCipher = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding");
encryptCipher.init(Cipher.ENCRYPT_MODE, k, ps);
decryptCipher = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding");
decryptCipher.init(Cipher.DECRYPT_MODE, k, ps);
} catch (Exception e) {
throw new SecurityException("Could not initialize CryptoLibrary: " + e.getMessage());
}
}Example 6
| Project: android-15-master File: PBEParameterSpecTest.java View source code |
/**
* PBEParameterSpec(byte[] salt, int iterationCount) method testing.
* Tests the behavior of the method in the case of null input array
* and tests that input array is copied during the object initialization.
*/
public void testPBEParameterSpec() {
byte[] salt = { 1, 2, 3, 4, 5 };
int iterationCount = 10;
try {
new PBEParameterSpec(null, iterationCount);
fail("A NullPointerException should be was thrown " + "in the case of null salt.");
} catch (NullPointerException e) {
}
PBEParameterSpec pbeps = new PBEParameterSpec(salt, iterationCount);
salt[0]++;
assertFalse("The change of salt specified in the constructor " + "should not cause the change of internal array.", salt[0] == pbeps.getSalt()[0]);
}Example 7
| Project: android-libcore64-master File: PBEParameterSpecTest.java View source code |
/**
* PBEParameterSpec(byte[] salt, int iterationCount) method testing.
* Tests the behavior of the method in the case of null input array
* and tests that input array is copied during the object initialization.
*/
public void testPBEParameterSpec() {
byte[] salt = { 1, 2, 3, 4, 5 };
int iterationCount = 10;
try {
new PBEParameterSpec(null, iterationCount);
fail("A NullPointerException should be was thrown " + "in the case of null salt.");
} catch (NullPointerException e) {
}
PBEParameterSpec pbeps = new PBEParameterSpec(salt, iterationCount);
salt[0]++;
assertFalse("The change of salt specified in the constructor " + "should not cause the change of internal array.", salt[0] == pbeps.getSalt()[0]);
}Example 8
| Project: android-sdk-sources-for-api-level-23-master File: PBEParameterSpecTest.java View source code |
/**
* PBEParameterSpec(byte[] salt, int iterationCount) method testing.
* Tests the behavior of the method in the case of null input array
* and tests that input array is copied during the object initialization.
*/
public void testPBEParameterSpec() {
byte[] salt = { 1, 2, 3, 4, 5 };
int iterationCount = 10;
try {
new PBEParameterSpec(null, iterationCount);
fail("A NullPointerException should be was thrown " + "in the case of null salt.");
} catch (NullPointerException e) {
}
PBEParameterSpec pbeps = new PBEParameterSpec(salt, iterationCount);
salt[0]++;
assertFalse("The change of salt specified in the constructor " + "should not cause the change of internal array.", salt[0] == pbeps.getSalt()[0]);
}Example 9
| Project: android_libcore-master File: WrapCipherSpi.java View source code |
protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
CipherParameters param;
if (key instanceof JCEPBEKey) {
JCEPBEKey k = (JCEPBEKey) key;
if (params instanceof PBEParameterSpec) {
param = PBE.Util.makePBEParameters(k, params, wrapEngine.getAlgorithmName());
} else if (k.getParam() != null) {
param = k.getParam();
} else {
throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set.");
}
} else {
param = new KeyParameter(key.getEncoded());
}
if (params instanceof javax.crypto.spec.IvParameterSpec) {
IvParameterSpec iv = (IvParameterSpec) params;
CipherParameters paramPlusIV = new ParametersWithIV(param, iv.getIV());
param = paramPlusIV;
}
switch(opmode) {
case Cipher.WRAP_MODE:
wrapEngine.init(true, param);
break;
case Cipher.UNWRAP_MODE:
wrapEngine.init(false, param);
break;
case Cipher.ENCRYPT_MODE:
case Cipher.DECRYPT_MODE:
throw new IllegalArgumentException("engine only valid for wrapping");
default:
System.out.println("eeek!");
}
}Example 10
| Project: android_platform_libcore-master File: PBEParameterSpecTest.java View source code |
/**
* PBEParameterSpec(byte[] salt, int iterationCount) method testing.
* Tests the behavior of the method in the case of null input array
* and tests that input array is copied during the object initialization.
*/
public void testPBEParameterSpec() {
byte[] salt = { 1, 2, 3, 4, 5 };
int iterationCount = 10;
try {
new PBEParameterSpec(null, iterationCount);
fail("A NullPointerException should be was thrown " + "in the case of null salt.");
} catch (NullPointerException e) {
}
PBEParameterSpec pbeps = new PBEParameterSpec(salt, iterationCount);
salt[0]++;
assertFalse("The change of salt specified in the constructor " + "should not cause the change of internal array.", salt[0] == pbeps.getSalt()[0]);
}Example 11
| Project: ARTPart-master File: PBEParameterSpecTest.java View source code |
/**
* PBEParameterSpec(byte[] salt, int iterationCount) method testing.
* Tests the behavior of the method in the case of null input array
* and tests that input array is copied during the object initialization.
*/
public void testPBEParameterSpec() {
byte[] salt = { 1, 2, 3, 4, 5 };
int iterationCount = 10;
try {
new PBEParameterSpec(null, iterationCount);
fail("A NullPointerException should be was thrown " + "in the case of null salt.");
} catch (NullPointerException e) {
}
PBEParameterSpec pbeps = new PBEParameterSpec(salt, iterationCount);
salt[0]++;
assertFalse("The change of salt specified in the constructor " + "should not cause the change of internal array.", salt[0] == pbeps.getSalt()[0]);
}Example 12
| Project: cdo-master File: SecurityUtil.java View source code |
/**
* @since 2.0
*/
public static byte[] encrypt(byte[] data, char[] password, String algorithmName, byte[] salt, int count) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
// Create PBE parameter set
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
SecretKeyFactory keyFac = SecretKeyFactory.getInstance(algorithmName);
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
// Create PBE Cipher
Cipher pbeCipher = Cipher.getInstance(algorithmName);
// Initialize PBE Cipher with key and parameters
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
return pbeCipher.doFinal(data);
}Example 13
| Project: mclauncher-api-master File: LegacyLoginEncryptionProcessor.java View source code |
// notchcode begin
private static Cipher getCipher(int mode) throws Exception {
Random random = new Random(SALT);
byte[] salt = new byte[8];
random.nextBytes(salt);
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 5);
//$NON-NLS-1$
SecretKey pbeKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(new PBEKeySpec(PBE_KEY_STR.toCharArray()));
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
cipher.init(mode, pbeKey, pbeParamSpec);
return cipher;
}Example 14
| Project: modpack-master File: ScramblingSinkFilter.java View source code |
public static Cipher getCipher(int mode, String password) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
// These parameters were used for encrypting lastlogin on old official Minecraft launchers
Random random = new Random(0x29482c2L);
byte salt[] = new byte[8];
random.nextBytes(salt);
PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 5);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = factory.generateSecret(new PBEKeySpec(password.toCharArray()));
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
cipher.init(mode, key, paramSpec);
return cipher;
}Example 15
| Project: open-mika-master File: WrapCipherSpi.java View source code |
protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
CipherParameters param;
if (key instanceof JCEPBEKey) {
JCEPBEKey k = (JCEPBEKey) key;
if (params instanceof PBEParameterSpec) {
param = PBE.Util.makePBEParameters(k, params, wrapEngine.getAlgorithmName());
} else if (k.getParam() != null) {
param = k.getParam();
} else {
throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set.");
}
} else {
param = new KeyParameter(key.getEncoded());
}
if (params instanceof javax.crypto.spec.IvParameterSpec) {
IvParameterSpec iv = (IvParameterSpec) params;
CipherParameters paramPlusIV = new ParametersWithIV(param, iv.getIV());
param = paramPlusIV;
}
switch(opmode) {
case Cipher.WRAP_MODE:
wrapEngine.init(true, param);
break;
case Cipher.UNWRAP_MODE:
wrapEngine.init(false, param);
break;
case Cipher.ENCRYPT_MODE:
case Cipher.DECRYPT_MODE:
throw new IllegalArgumentException("engine only valid for wrapping");
default:
System.out.println("eeek!");
}
}Example 16
| Project: picketlink-master File: StringUtil.java View source code |
/**
* Given a masked password {@link String}, decode it
*
* @param maskedString a password string that is masked
* @param salt Salt
* @param iterationCount Iteration Count
*
* @return Decoded String
*
* @throws Exception
*/
public static String decode(String maskedString, String salt, int iterationCount) throws Exception {
String pbeAlgo = PicketLinkCommonConstants.PBE_ALGORITHM;
if (maskedString.startsWith(PicketLinkCommonConstants.PASS_MASK_PREFIX)) {
// Create the PBE secret key
SecretKeyFactory factory = SecretKeyFactory.getInstance(pbeAlgo);
char[] password = "somearbitrarycrazystringthatdoesnotmatter".toCharArray();
PBEParameterSpec cipherSpec = new PBEParameterSpec(salt.getBytes(), iterationCount);
PBEKeySpec keySpec = new PBEKeySpec(password);
SecretKey cipherKey = factory.generateSecret(keySpec);
maskedString = maskedString.substring(PicketLinkCommonConstants.PASS_MASK_PREFIX.length());
String decodedValue = PBEUtils.decode64(maskedString, pbeAlgo, cipherKey, cipherSpec);
maskedString = decodedValue;
}
return maskedString;
}Example 17
| Project: property-db-master File: PBEParameterSpecTest.java View source code |
/**
* PBEParameterSpec(byte[] salt, int iterationCount) method testing.
* Tests the behavior of the method in the case of null input array
* and tests that input array is copied during the object initialization.
*/
public void testPBEParameterSpec() {
byte[] salt = { 1, 2, 3, 4, 5 };
int iterationCount = 10;
try {
new PBEParameterSpec(null, iterationCount);
fail("A NullPointerException should be was thrown " + "in the case of null salt.");
} catch (NullPointerException e) {
}
PBEParameterSpec pbeps = new PBEParameterSpec(salt, iterationCount);
salt[0]++;
assertFalse("The change of salt specified in the constructor " + "should not cause the change of internal array.", salt[0] == pbeps.getSalt()[0]);
}Example 18
| Project: robovm-master File: PBEParameterSpecTest.java View source code |
/**
* PBEParameterSpec(byte[] salt, int iterationCount) method testing.
* Tests the behavior of the method in the case of null input array
* and tests that input array is copied during the object initialization.
*/
public void testPBEParameterSpec() {
byte[] salt = { 1, 2, 3, 4, 5 };
int iterationCount = 10;
try {
new PBEParameterSpec(null, iterationCount);
fail("A NullPointerException should be was thrown " + "in the case of null salt.");
} catch (NullPointerException e) {
}
PBEParameterSpec pbeps = new PBEParameterSpec(salt, iterationCount);
salt[0]++;
assertFalse("The change of salt specified in the constructor " + "should not cause the change of internal array.", salt[0] == pbeps.getSalt()[0]);
}Example 19
| Project: simplequery-master File: PasswordEncryptionService.java View source code |
public String encrypt(String property) throws GeneralSecurityException, UnsupportedEncodingException {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
return base64Encode(pbeCipher.doFinal(property.getBytes("UTF-8")));
}Example 20
| Project: softwaremill-common-master File: TextCoder.java View source code |
private Cipher createCipher(int mode, String plainPassword, byte[] salt) throws Exception {
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, ITERATION_COUNT);
PBEKeySpec pbeKeySpec = new PBEKeySpec(plainPassword.toCharArray());
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(mode, secretKey, pbeParamSpec);
return cipher;
}Example 21
| Project: android-demos-master File: Encrypt.java View source code |
public String crypt(int mode, String encryption_subject) throws CryptException {
final PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec(SALT, 20);
final SecretKeyFactory kf = getSecretKeyFactory();
final SecretKey k = getSecretKey(kf);
final Cipher crypter = getCipherInstance();
String result;
switch(mode) {
case Cipher.DECRYPT_MODE:
initialise(ps, k, crypter, Cipher.DECRYPT_MODE);
result = getString(encryption_subject, crypter);
break;
case Cipher.ENCRYPT_MODE:
default:
initialise(ps, k, crypter, Cipher.ENCRYPT_MODE);
result = encode(encryption_subject, crypter);
}
return result;
}Example 22
| Project: bc-java-master File: BaseWrapCipher.java View source code |
protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
CipherParameters param;
if (key instanceof BCPBEKey) {
BCPBEKey k = (BCPBEKey) key;
if (params instanceof PBEParameterSpec) {
param = PBE.Util.makePBEParameters(k, params, wrapEngine.getAlgorithmName());
} else if (k.getParam() != null) {
param = k.getParam();
} else {
throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set.");
}
} else {
param = new KeyParameter(key.getEncoded());
}
if (params instanceof IvParameterSpec) {
IvParameterSpec iv = (IvParameterSpec) params;
param = new ParametersWithIV(param, iv.getIV());
}
if (param instanceof KeyParameter && ivSize != 0) {
iv = new byte[ivSize];
random.nextBytes(iv);
param = new ParametersWithIV(param, iv);
}
if (random != null) {
param = new ParametersWithRandom(param, random);
}
switch(opmode) {
case Cipher.WRAP_MODE:
wrapEngine.init(true, param);
break;
case Cipher.UNWRAP_MODE:
wrapEngine.init(false, param);
break;
case Cipher.ENCRYPT_MODE:
case Cipher.DECRYPT_MODE:
throw new IllegalArgumentException("engine only valid for wrapping");
default:
System.out.println("eeek!");
}
}Example 23
| Project: bugvm-master File: PBE.java View source code |
/**
* construct a key and iv (if necessary) suitable for use with a
* Cipher.
*/
public static CipherParameters makePBEParameters(BCPBEKey pbeKey, AlgorithmParameterSpec spec, String targetAlgorithm) {
if ((spec == null) || !(spec instanceof PBEParameterSpec)) {
throw new IllegalArgumentException("Need a PBEParameter spec with a PBE key.");
}
PBEParameterSpec pbeParam = (PBEParameterSpec) spec;
PBEParametersGenerator generator = makePBEGenerator(pbeKey.getType(), pbeKey.getDigest());
byte[] key = pbeKey.getEncoded();
CipherParameters param;
if (pbeKey.shouldTryWrongPKCS12()) {
key = new byte[2];
}
generator.init(key, pbeParam.getSalt(), pbeParam.getIterationCount());
if (pbeKey.getIvSize() != 0) {
param = generator.generateDerivedParameters(pbeKey.getKeySize(), pbeKey.getIvSize());
} else {
param = generator.generateDerivedParameters(pbeKey.getKeySize());
}
if (targetAlgorithm.startsWith("DES")) {
if (param instanceof ParametersWithIV) {
KeyParameter kParam = (KeyParameter) ((ParametersWithIV) param).getParameters();
DESParameters.setOddParity(kParam.getKey());
} else {
KeyParameter kParam = (KeyParameter) param;
DESParameters.setOddParity(kParam.getKey());
}
}
for (int i = 0; i != key.length; i++) {
key[i] = 0;
}
return param;
}Example 24
| Project: com.revolsys.open-master File: PasswordUtil.java View source code |
public static byte[] encrypt(final byte[] data, final char[] password, final byte[] salt, final int noIterations) {
try {
final String method = "PBEWithMD5AndTripleDES";
final SecretKeyFactory kf = SecretKeyFactory.getInstance(method);
final PBEKeySpec keySpec = new PBEKeySpec(password);
final SecretKey key = kf.generateSecret(keySpec);
final Cipher ciph = Cipher.getInstance(method);
final PBEParameterSpec params = new PBEParameterSpec(salt, noIterations);
return ciph.doFinal(data);
} catch (final Exception e) {
throw new RuntimeException("Spurious encryption error");
}
}Example 25
| Project: eclipse-master File: SecureProperties.java View source code |
private Cipher createCipher(int mode, byte[] salt) throws GeneralSecurityException {
SecretKeyFactory keyFactory;
keyFactory = SecretKeyFactory.getInstance(KEY_FACTORY);
SecretKey key = keyFactory.generateSecret(password);
PBEParameterSpec entropy = new PBEParameterSpec(salt, 8);
Cipher cipher = Cipher.getInstance(CIPHER);
cipher.init(mode, key, entropy);
return cipher;
}Example 26
| Project: federation-master File: StringUtil.java View source code |
/**
* Given a masked password {@link String}, decode it
*
* @param maskedString a password string that is masked
* @param salt Salt
* @param iterationCount Iteration Count
* @return Decoded String
* @throws Exception
*/
public static String decode(String maskedString, String salt, int iterationCount) throws Exception {
String pbeAlgo = PicketLinkFederationConstants.PBE_ALGORITHM;
if (maskedString.startsWith(PicketLinkFederationConstants.PASS_MASK_PREFIX)) {
// Create the PBE secret key
SecretKeyFactory factory = SecretKeyFactory.getInstance(pbeAlgo);
char[] password = "somearbitrarycrazystringthatdoesnotmatter".toCharArray();
PBEParameterSpec cipherSpec = new PBEParameterSpec(salt.getBytes(), iterationCount);
PBEKeySpec keySpec = new PBEKeySpec(password);
SecretKey cipherKey = factory.generateSecret(keySpec);
maskedString = maskedString.substring(PicketLinkFederationConstants.PASS_MASK_PREFIX.length());
String decodedValue = PBEUtils.decode64(maskedString, pbeAlgo, cipherKey, cipherSpec);
maskedString = decodedValue;
}
return maskedString;
}Example 27
| Project: greenhouse-master File: CipherUtils.java View source code |
public static void initCipher(Cipher cipher, int mode, SecretKey secretKey, byte[] salt, int iterationCount) {
try {
cipher.init(mode, secretKey, new PBEParameterSpec(salt, iterationCount));
} catch (InvalidKeyException e) {
throw new IllegalArgumentException("Unable to initialize due to invalid secret key", e);
} catch (InvalidAlgorithmParameterException e) {
throw new IllegalStateException("Unable to initialize due to invalid decryption parameter spec", e);
}
}Example 28
| Project: irma_future_id-master File: PBE.java View source code |
/**
* construct a key and iv (if necessary) suitable for use with a
* Cipher.
*/
public static CipherParameters makePBEParameters(BCPBEKey pbeKey, AlgorithmParameterSpec spec, String targetAlgorithm) {
if ((spec == null) || !(spec instanceof PBEParameterSpec)) {
throw new IllegalArgumentException("Need a PBEParameter spec with a PBE key.");
}
PBEParameterSpec pbeParam = (PBEParameterSpec) spec;
PBEParametersGenerator generator = makePBEGenerator(pbeKey.getType(), pbeKey.getDigest());
byte[] key = pbeKey.getEncoded();
CipherParameters param;
if (pbeKey.shouldTryWrongPKCS12()) {
key = new byte[2];
}
generator.init(key, pbeParam.getSalt(), pbeParam.getIterationCount());
if (pbeKey.getIvSize() != 0) {
param = generator.generateDerivedParameters(pbeKey.getKeySize(), pbeKey.getIvSize());
} else {
param = generator.generateDerivedParameters(pbeKey.getKeySize());
}
if (targetAlgorithm.startsWith("DES")) {
if (param instanceof ParametersWithIV) {
KeyParameter kParam = (KeyParameter) ((ParametersWithIV) param).getParameters();
DESParameters.setOddParity(kParam.getKey());
} else {
KeyParameter kParam = (KeyParameter) param;
DESParameters.setOddParity(kParam.getKey());
}
}
for (int i = 0; i != key.length; i++) {
key[i] = 0;
}
return param;
}Example 29
| Project: JFileSync3-master File: SecurityUtils.java View source code |
// getCipher()
public static Cipher getPasswordCipher(String cipherName, int cipherMode, String password, String salt) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException {
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
PBEParameterSpec paramSpec = new PBEParameterSpec(salt.getBytes(), password.length());
SecretKeyFactory keyFac = SecretKeyFactory.getInstance(cipherName);
SecretKey pbeKey = keyFac.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance(cipherName, PROVIDER);
cipher.init(cipherMode, pbeKey, paramSpec);
return cipher;
}Example 30
| Project: openjdk-master File: EntryProtectionTest.java View source code |
private void setUp() {
out.println("Using KEYSTORE_PATH:" + KEYSTORE_PATH);
Utils.createKeyStore(Utils.KeyStoreType.pkcs12, KEYSTORE_PATH, ALIAS);
Random rand = RandomFactory.getRandom();
rand.nextBytes(SALT);
out.print("Salt: ");
for (byte b : SALT) {
out.format("%02X ", b);
}
out.println("");
PASSWORD_PROTECTION.add(new KeyStore.PasswordProtection(PASSWORD, "PBEWithMD5AndDES", new PBEParameterSpec(SALT, ITERATION_COUNT)));
PASSWORD_PROTECTION.add(new KeyStore.PasswordProtection(PASSWORD, "PBEWithSHA1AndDESede", null));
PASSWORD_PROTECTION.add(new KeyStore.PasswordProtection(PASSWORD, "PBEWithSHA1AndRC2_40", null));
PASSWORD_PROTECTION.add(new KeyStore.PasswordProtection(PASSWORD, "PBEWithSHA1AndRC2_128", null));
PASSWORD_PROTECTION.add(new KeyStore.PasswordProtection(PASSWORD, "PBEWithSHA1AndRC4_40", null));
PASSWORD_PROTECTION.add(new KeyStore.PasswordProtection(PASSWORD, "PBEWithSHA1AndRC4_128", null));
}Example 31
| Project: RipplePower-master File: PBEPBKDF2.java View source code |
protected void engineInit(AlgorithmParameterSpec paramSpec) throws InvalidParameterSpecException {
if (!(paramSpec instanceof PBEParameterSpec)) {
throw new InvalidParameterSpecException("PBEParameterSpec required to initialise a PBKDF2 PBE parameters algorithm parameters object");
}
PBEParameterSpec pbeSpec = (PBEParameterSpec) paramSpec;
this.params = new PBKDF2Params(pbeSpec.getSalt(), pbeSpec.getIterationCount());
}Example 32
| Project: spring-greenhouse-clickstart-master File: CipherUtils.java View source code |
public static void initCipher(Cipher cipher, int mode, SecretKey secretKey, byte[] salt, int iterationCount) {
try {
cipher.init(mode, secretKey, new PBEParameterSpec(salt, iterationCount));
} catch (InvalidKeyException e) {
throw new IllegalArgumentException("Unable to initialize due to invalid secret key", e);
} catch (InvalidAlgorithmParameterException e) {
throw new IllegalStateException("Unable to initialize due to invalid decryption parameter spec", e);
}
}Example 33
| Project: vaultjbosstool-master File: Main.java View source code |
public static void main(String[] args) throws Exception {
Map<String, Object> data = new HashMap<String, Object>();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("WARNING: This tool will convert JKS to JCEKS if your keystore is not a JCEKS.");
System.out.println("Keystore URL: (Ex: /tmp/new/a.keystore)");
data.put("KEYSTORE_URL", in.readLine());
System.out.println("Keystore Password: (Ex: MASK-2CnDY1FriorSpKmoIGU5WR)");
data.put("KEYSTORE_PASSWORD", in.readLine());
System.out.println("Salt: (Ex: 12345678)");
data.put("SALT", in.readLine());
System.out.println("Interation: (Ex: 44)");
data.put("ITERATION_COUNT", in.readLine());
System.out.println("Alias: (Ex: vault)");
data.put("KEYSTORE_ALIAS", in.readLine());
System.out.println("Enc file directory: (Ex: /tmp/new)");
data.put("ENC_FILE_DIR", in.readLine());
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEwithMD5andDES");
char[] password = "somearbitrarycrazystringthatdoesnotmatter".toCharArray();
PBEParameterSpec cipherSpec = new PBEParameterSpec(((String) data.get("SALT")).getBytes(), Integer.valueOf((String) data.get("ITERATION_COUNT")));
PBEKeySpec keySpec = new PBEKeySpec(password);
SecretKey cipherKey = factory.generateSecret(keySpec);
String decodedValue = PBEUtils.decode64(((String) data.get("KEYSTORE_PASSWORD")).substring("MASK-".length()), "PBEwithMD5andDES", cipherKey, cipherSpec);
System.out.println("Keystore password: " + decodedValue);
PicketBoxSecurityVault meuPick = new PicketBoxSecurityVault();
meuPick.init(data);
System.out.println("List of vault attributes:");
for (String s : meuPick.keyList()) {
String block = s.split(":")[0];
String attribute = s.split(":")[2];
char[] senha = meuPick.retrieve(block, attribute, null);
System.out.println("Block: " + block + " Attribute: " + attribute + " Pass: " + String.valueOf(senha));
}
}Example 34
| Project: AnalyzerBeans-master File: EncodedStringConverter.java View source code |
@Override
public String fromString(Class<?> type, String encodedPassword) {
if (encodedPassword == null) {
return null;
}
try {
SecretKeyFactory instance = SecretKeyFactory.getInstance(ALGORHITM);
SecretKey key = instance.generateSecret(new PBEKeySpec(_secret));
Cipher cipher = Cipher.getInstance(ALGORHITM);
cipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(_salt, 20));
byte[] bytes = encodedPassword.getBytes("UTF-8");
bytes = cipher.doFinal(Base64.decodeBase64(bytes));
return new String(bytes);
} catch (Exception e) {
throw new IllegalStateException("Unable to decode password", e);
}
}Example 35
| Project: atlas-lb-master File: PKCS8Generator.java View source code |
public PemObject generate() throws PemGenerationException {
byte[] keyData = key.getEncoded();
if (algorithm == null) {
return new PemObject("PRIVATE KEY", keyData);
}
DERObjectIdentifier algOID = new DERObjectIdentifier(algorithm);
if (PEMUtilities.isPKCS5Scheme2(algOID)) {
byte[] salt = new byte[20];
if (random == null) {
random = new SecureRandom();
}
random.nextBytes(salt);
SecretKey key = PEMUtilities.generateSecretKeyForPKCS5Scheme2(algorithm, password, salt, iterationCount);
AlgorithmParameters params = paramGen.generateParameters();
try {
cipher.init(Cipher.ENCRYPT_MODE, key, params);
EncryptionScheme scheme = new EncryptionScheme(new DERObjectIdentifier(algorithm), ASN1Object.fromByteArray(params.getEncoded()));
KeyDerivationFunc func = new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, new PBKDF2Params(salt, iterationCount));
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(func);
v.add(scheme);
EncryptedPrivateKeyInfo info = new EncryptedPrivateKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, new PBES2Parameters(new DERSequence(v))), cipher.doFinal(keyData));
return new PemObject("ENCRYPTED PRIVATE KEY", info.getEncoded());
} catch (IOException e) {
throw new PemGenerationException(e.getMessage(), e);
} catch (GeneralSecurityException e) {
throw new PemGenerationException(e.getMessage(), e);
}
} else if (PEMUtilities.isPKCS12(algOID)) {
byte[] salt = new byte[20];
if (random == null) {
random = new SecureRandom();
}
random.nextBytes(salt);
try {
PBEKeySpec pbeSpec = new PBEKeySpec(password);
PBEParameterSpec defParams = new PBEParameterSpec(salt, iterationCount);
cipher.init(Cipher.ENCRYPT_MODE, secKeyFact.generateSecret(pbeSpec), defParams);
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DEROctetString(salt));
v.add(new DERInteger(iterationCount));
EncryptedPrivateKeyInfo info = new EncryptedPrivateKeyInfo(new AlgorithmIdentifier(algOID, new PKCS12PBEParams(new DERSequence(v))), cipher.doFinal(keyData));
return new PemObject("ENCRYPTED PRIVATE KEY", info.getEncoded());
} catch (IOException e) {
throw new PemGenerationException(e.getMessage(), e);
} catch (GeneralSecurityException e) {
throw new PemGenerationException(e.getMessage(), e);
}
} else {
throw new PemGenerationException("unknown algorithm: " + algorithm);
}
}Example 36
| Project: DataCleaner-master File: EncodedStringConverter.java View source code |
@Override
public String fromString(final Class<?> type, final String encodedPassword) {
if (encodedPassword == null) {
return null;
}
try {
final SecretKeyFactory instance = SecretKeyFactory.getInstance(ALGORHITM);
final SecretKey key = instance.generateSecret(new PBEKeySpec(_secret));
final Cipher cipher = Cipher.getInstance(ALGORHITM);
cipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(_salt, 20));
byte[] bytes = encodedPassword.getBytes("UTF-8");
bytes = cipher.doFinal(Base64.decodeBase64(bytes));
return new String(bytes);
} catch (final Exception e) {
throw new IllegalStateException("Unable to decode password", e);
}
}Example 37
| Project: doqui-index-master File: EncryptionHelper.java View source code |
public static String encrypt(String val) throws Exception {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ENCRYPTION);
PBEKeySpec keySpec = new PBEKeySpec(PASSPHRASE.toCharArray());
SecretKey key = keyFactory.generateSecret(keySpec);
PBEParameterSpec paramSpec = new PBEParameterSpec(SALT.getBytes(), COUNT);
Cipher cipher = Cipher.getInstance(ENCRYPTION);
cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
byte[] ciphertext = cipher.doFinal(val.getBytes());
return toHexString(ciphertext);
}Example 38
| Project: ef-orm-master File: PasswordEncryptor.java View source code |
/**
* 基于密ç ?çš„åŠ å¯†
* @param in
* @param password
* @return
*/
public byte[] encrypt(InputStream in, String password) {
try {
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), pbe_salt, pbe_iterationCount);
SecretKey key = SecretKeyFactory.getInstance(pbeAlogorithm.name()).generateSecret(keySpec);
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(pbe_salt, pbe_iterationCount);
return EncrypterUtil.encrypt(in, key, paramSpec, false);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}Example 39
| Project: FileBunker-master File: DESCipherOutputStream.java View source code |
public static Cipher createCipher(String passPhrase, int mode) {
Cipher cipher;
int iterationCount = 19;
try {
// Create the key
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
cipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
// Create the ciphers
cipher.init(mode, key, paramSpec);
} catch (java.security.GeneralSecurityException e) {
throw new RuntimeException(e);
}
return cipher;
}Example 40
| Project: js-android-app-master File: MigrationV4.java View source code |
private String encrypt(String value) {
try {
final byte[] bytes = value != null ? value.getBytes(UTF8) : new byte[0];
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
KeySpec keySpec = new PBEKeySpec(SECRET.toCharArray());
SecretKey key = keyFactory.generateSecret(keySpec);
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
AlgorithmParameterSpec spec = new PBEParameterSpec(fetchSalt(), ITERATION_COUNT);
pbeCipher.init(Cipher.ENCRYPT_MODE, key, spec);
return toBase64(pbeCipher.doFinal(bytes));
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}Example 41
| Project: Mediawiki-Japi-master File: Crypt.java View source code |
/**
* encrypt the given property
* @param property
* @return
* @throws GeneralSecurityException
* @throws UnsupportedEncodingException
*/
String encrypt(String property) throws GeneralSecurityException, UnsupportedEncodingException {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(cypher));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, 20));
return base64Encode(pbeCipher.doFinal(property.getBytes("UTF-8")));
}Example 42
| Project: oobd-master File: PKCS8Generator.java View source code |
public PemObject generate() throws PemGenerationException {
byte[] keyData = key.getEncoded();
if (algorithm == null) {
return new PemObject("PRIVATE KEY", keyData);
}
ASN1ObjectIdentifier algOID = new ASN1ObjectIdentifier(algorithm);
if (PEMUtilities.isPKCS5Scheme2(algOID)) {
byte[] salt = new byte[20];
if (random == null) {
random = new SecureRandom();
}
random.nextBytes(salt);
SecretKey key = PEMUtilities.generateSecretKeyForPKCS5Scheme2(algorithm, password, salt, iterationCount);
AlgorithmParameters params = paramGen.generateParameters();
try {
cipher.init(Cipher.ENCRYPT_MODE, key, params);
EncryptionScheme scheme = new EncryptionScheme(new ASN1ObjectIdentifier(algorithm), ASN1Primitive.fromByteArray(params.getEncoded()));
KeyDerivationFunc func = new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, new PBKDF2Params(salt, iterationCount));
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(func);
v.add(scheme);
EncryptedPrivateKeyInfo info = new EncryptedPrivateKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBES2, new PBES2Parameters(new DERSequence(v))), cipher.doFinal(keyData));
return new PemObject("ENCRYPTED PRIVATE KEY", info.getEncoded());
} catch (IOException e) {
throw new PemGenerationException(e.getMessage(), e);
} catch (GeneralSecurityException e) {
throw new PemGenerationException(e.getMessage(), e);
}
} else if (PEMUtilities.isPKCS12(algOID)) {
byte[] salt = new byte[20];
if (random == null) {
random = new SecureRandom();
}
random.nextBytes(salt);
try {
PBEKeySpec pbeSpec = new PBEKeySpec(password);
PBEParameterSpec defParams = new PBEParameterSpec(salt, iterationCount);
cipher.init(Cipher.ENCRYPT_MODE, secKeyFact.generateSecret(pbeSpec), defParams);
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new DEROctetString(salt));
v.add(new ASN1Integer(iterationCount));
EncryptedPrivateKeyInfo info = new EncryptedPrivateKeyInfo(new AlgorithmIdentifier(algOID, PKCS12PBEParams.getInstance(new DERSequence(v))), cipher.doFinal(keyData));
return new PemObject("ENCRYPTED PRIVATE KEY", info.getEncoded());
} catch (IOException e) {
throw new PemGenerationException(e.getMessage(), e);
} catch (GeneralSecurityException e) {
throw new PemGenerationException(e.getMessage(), e);
}
} else {
throw new PemGenerationException("unknown algorithm: " + algorithm);
}
}Example 43
| Project: openicf-master File: RSAAuthenticationManager8Utils.java View source code |
/**
* Encrypts the given string - assumed to be a config property- using the
* constant pwd and salt using MD5 and DES.
*
* @param property the String to encrypt
* @return an encrypted representation of the string.
*
* @throws GeneralSecurityException
* @throws UnsupportedEncodingException
*/
public static String encrypt(String property) throws GeneralSecurityException, UnsupportedEncodingException {
// DEBUG:
//logger.info("Encrypting property: {0}.", property);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
return base64Encode(pbeCipher.doFinal(property.getBytes("UTF-8")));
}Example 44
| Project: ORCID-Source-master File: DesEncrypter.java View source code |
private void initDesEncrypter(final String passPhrase) {
try {
// Create the key
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
// Create the ciphers
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (GeneralSecurityException e) {
LOGGER.trace("DesEncrypter.creation failed", e);
throw new ApplicationException("DesEncrypter creation failed", e);
}
}Example 45
| Project: pydio-sdk-java-master File: PassManager.java View source code |
public static String encrypt(String property) throws GeneralSecurityException {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
return "$AJXP_ENC$" + toHex(pbeCipher.doFinal(property.getBytes()));
}Example 46
| Project: rhq-sync-tool-master File: PasswordUtil.java View source code |
public static String encode(String password) {
byte[] salt = SALT.substring(0, 8).getBytes();
int count = 15;
char[] masterPassword = MASTER.toCharArray();
byte[] passwordToEncode;
try {
passwordToEncode = password.getBytes("UTF-8");
PBEParameterSpec cipherSpec = new PBEParameterSpec(salt, count);
PBEKeySpec keySpec = new PBEKeySpec(masterPassword);
SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey cipherKey = factory.generateSecret(keySpec);
return PBEUtils.encode64(passwordToEncode, ALGORITHM, cipherKey, cipherSpec);
} catch (UnsupportedEncodingException e) {
logger.warn("Fail to encode password:" + e.getMessage());
throw new IllegalStateException(e);
} catch (Exception e) {
logger.warn("Fail to encode password:" + e.getMessage());
throw new IllegalStateException(e);
}
}Example 47
| Project: TuCanMobile-master File: EncryptionHelper.java View source code |
public static String encrypt(String plain) {
if (plain == null || plain.equals(""))
return "";
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SALT2.toCharArray()));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
return base64Encode(pbeCipher.doFinal(plain.getBytes("UTF-8")));
} catch (Exception e) {
throw new RuntimeException("failed to encrypt", e);
}
}Example 48
| Project: upm-android-master File: EncryptionService.java View source code |
private void initCiphers() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, SALT_GEN_ITER_COUNT);
encryptionCipher = Cipher.getInstance(PBEWithSHA256And256BitAES);
decryptionCipher = Cipher.getInstance(PBEWithSHA256And256BitAES);
encryptionCipher.init(Cipher.ENCRYPT_MODE, secretKey, pbeParamSpec);
decryptionCipher.init(Cipher.DECRYPT_MODE, secretKey, pbeParamSpec);
}Example 49
| Project: upm-swing-master File: DESDecryptionService.java View source code |
private static byte[] process(char[] password, int mode, byte[] salt, byte[] plainText) throws CryptoException {
byte[] retVal = null;
try {
PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
SecretKeyFactory keyFac = SecretKeyFactory.getInstance(PBEWithMD5AndDES);
SecretKey secreyKey = keyFac.generateSecret(pbeKeySpec);
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20);
Cipher desDecryptionCipher = Cipher.getInstance(PBEWithMD5AndDES);
desDecryptionCipher.init(mode, secreyKey, pbeParamSpec);
retVal = desDecryptionCipher.doFinal(plainText);
} catch (NoSuchAlgorithmException e) {
throw new CryptoException(e);
} catch (IllegalBlockSizeException e) {
throw new CryptoException(e);
} catch (BadPaddingException e) {
throw new CryptoException(e);
} catch (NoSuchPaddingException e) {
throw new CryptoException(e);
} catch (InvalidKeySpecException e) {
throw new CryptoException(e);
} catch (InvalidKeyException e) {
throw new CryptoException(e);
} catch (InvalidAlgorithmParameterException e) {
throw new CryptoException(e);
}
return retVal;
}Example 50
| Project: viAutomator-master File: LoginConfiguration.java View source code |
/**
* Method to encrypt the password of the VMWare-user
*
* @param password The plain password of the VMWare-user
* @return An encrypted password
* @throws Exception if something goes wrong
*/
public static String encode(final String password) throws Exception {
byte[] salt = SALT.substring(0, 8).getBytes();
int count = 15;
char[] masterPassword = MASTER.toCharArray();
byte[] passwordToEncode = password.getBytes("UTF-8");
PBEParameterSpec cipherSpec = new PBEParameterSpec(salt, count);
PBEKeySpec keySpec = new PBEKeySpec(masterPassword);
SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey cipherKey = factory.generateSecret(keySpec);
return PBEUtils.encode64(passwordToEncode, ALGORITHM, cipherKey, cipherSpec);
}Example 51
| Project: WoodenLib-master File: DesEncryption.java View source code |
private void initCypherSuite(String passPhrase) throws Exception {
java.security.spec.KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), this.salt, this.iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
this.ecipher = Cipher.getInstance(key.getAlgorithm());
this.dcipher = Cipher.getInstance(key.getAlgorithm());
java.security.spec.AlgorithmParameterSpec paramSpec = new PBEParameterSpec(this.salt, this.iterationCount);
this.ecipher.init(1, key, paramSpec);
this.dcipher.init(2, key, paramSpec);
}Example 52
| Project: android-delicious-master File: ObscuredSharedPreferences.java View source code |
protected String encrypt(String value) {
try {
final byte[] bytes = value != null ? value.getBytes(UTF8) : new byte[0];
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(secret));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(getSalt(), 20));
return new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP), UTF8);
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 53
| Project: classlib6-master File: HmacPKCS12PBESHA1.java View source code |
/**
* Initializes the HMAC with the given secret key and algorithm parameters.
*
* @param key the secret key.
* @param params the algorithm parameters.
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this MAC.
u* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this MAC.
*/
protected void engineInit(Key key, AlgorithmParameterSpec params) throws InvalidKeyException, InvalidAlgorithmParameterException {
char[] passwdChars;
byte[] salt = null;
int iCount = 0;
if (key instanceof javax.crypto.interfaces.PBEKey) {
javax.crypto.interfaces.PBEKey pbeKey = (javax.crypto.interfaces.PBEKey) key;
passwdChars = pbeKey.getPassword();
// maybe null if unspecified
salt = pbeKey.getSalt();
// maybe 0 if unspecified
iCount = pbeKey.getIterationCount();
} else if (key instanceof SecretKey) {
byte[] passwdBytes = key.getEncoded();
if ((passwdBytes == null) || !(key.getAlgorithm().regionMatches(true, 0, "PBE", 0, 3))) {
throw new InvalidKeyException("Missing password");
}
passwdChars = new char[passwdBytes.length];
for (int i = 0; i < passwdChars.length; i++) {
passwdChars[i] = (char) (passwdBytes[i] & 0x7f);
}
} else {
throw new InvalidKeyException("SecretKey of PBE type required");
}
if (params == null) {
// generate default for salt and iteration count if necessary
if (salt == null) {
salt = new byte[20];
SunJCE.RANDOM.nextBytes(salt);
}
if (iCount == 0)
iCount = 100;
} else if (!(params instanceof PBEParameterSpec)) {
throw new InvalidAlgorithmParameterException("PBEParameterSpec type required");
} else {
PBEParameterSpec pbeParams = (PBEParameterSpec) params;
// make sure the parameter values are consistent
if (salt != null) {
if (!Arrays.equals(salt, pbeParams.getSalt())) {
throw new InvalidAlgorithmParameterException("Inconsistent value of salt between key and params");
}
} else {
salt = pbeParams.getSalt();
}
if (iCount != 0) {
if (iCount != pbeParams.getIterationCount()) {
throw new InvalidAlgorithmParameterException("Different iteration count between key and params");
}
} else {
iCount = pbeParams.getIterationCount();
}
}
// which is what PKCS#5 recommends and openssl does.
if (salt.length < 8) {
throw new InvalidAlgorithmParameterException("Salt must be at least 8 bytes long");
}
if (iCount <= 0) {
throw new InvalidAlgorithmParameterException("IterationCount must be a positive number");
}
byte[] derivedKey = PKCS12PBECipherCore.derive(passwdChars, salt, iCount, hmac.getDigestLength(), PKCS12PBECipherCore.MAC_KEY);
SecretKey cipherKey = new SecretKeySpec(derivedKey, "HmacSHA1");
hmac.init(cipherKey, null);
}Example 54
| Project: codetraq-master File: PasswordProcessor.java View source code |
/**
* Encrypts a text using the <code>passPhrase</code> above and an algorithm supported
* by your virtual machine implementation. You can change the default algorithm with
* another algorithm, but please make sure your virtual machine supports it.
* @param valueToEncrypt - text to encrypt
* @return an encrypted, Base64 encoded text
*/
public static String encryptString(String valueToEncrypt) {
String output = null;
try {
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterations);
SecretKey secretKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterations);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
// begin encrypting...
byte[] byteToEncrypt = valueToEncrypt.getBytes("UTF8");
byte[] encrypted = cipher.doFinal(byteToEncrypt);
output = new Base64().encodeToString(encrypted);
} catch (Exception ex) {
Logger.getLogger(PasswordProcessor.class.getName()).log(Level.SEVERE, null, ex);
}
return output;
}Example 55
| Project: Desktop-master File: DesEncrypter.java View source code |
/**
*/
private void init(final byte[] salt) {
if (ecipher != null && mSalt != null && !Arrays.equals(mSalt, salt)) {
ecipher = null;
dcipher = null;
}
if (salt != null) {
mSalt = salt;
}
if (ecipher == null) {
try {
SecretKey key;
try {
KeySpec keySpec = new PBEKeySpec(passPhrase, mSalt, iterationCount);
key = SecretKeyFactory.getInstance(mAlgorithm).generateSecret(keySpec);
} catch (final java.security.spec.InvalidKeySpecException e) {
try {
passPhrase = URLEncoder.encode(new String(passPhrase), "UTF-8").toCharArray();
} catch (UnsupportedEncodingException e1) {
throw e;
}
KeySpec keySpec = new PBEKeySpec(passPhrase, mSalt, iterationCount);
key = SecretKeyFactory.getInstance(mAlgorithm).generateSecret(keySpec);
}
ecipher = Cipher.getInstance(mAlgorithm);
dcipher = Cipher.getInstance(mAlgorithm);
final AlgorithmParameterSpec paramSpec = new PBEParameterSpec(mSalt, iterationCount);
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (final java.security.InvalidAlgorithmParameterException e) {
LogUtils.severe(e);
} catch (final java.security.spec.InvalidKeySpecException e) {
LogUtils.severe(e);
} catch (final javax.crypto.NoSuchPaddingException e) {
LogUtils.severe(e);
} catch (final java.security.NoSuchAlgorithmException e) {
LogUtils.severe(e);
} catch (final java.security.InvalidKeyException e) {
LogUtils.severe(e);
}
}
}Example 56
| Project: Docear-master File: DesEncrypter.java View source code |
/**
*/
private void init(final byte[] salt) {
if (ecipher != null && mSalt != null && !Arrays.equals(mSalt, salt)) {
ecipher = null;
dcipher = null;
}
if (salt != null) {
mSalt = salt;
}
if (ecipher == null) {
try {
SecretKey key;
try {
KeySpec keySpec = new PBEKeySpec(passPhrase, mSalt, iterationCount);
key = SecretKeyFactory.getInstance(mAlgorithm).generateSecret(keySpec);
} catch (final java.security.spec.InvalidKeySpecException e) {
try {
passPhrase = URLEncoder.encode(new String(passPhrase), "UTF-8").toCharArray();
} catch (UnsupportedEncodingException e1) {
throw e;
}
KeySpec keySpec = new PBEKeySpec(passPhrase, mSalt, iterationCount);
key = SecretKeyFactory.getInstance(mAlgorithm).generateSecret(keySpec);
}
ecipher = Cipher.getInstance(mAlgorithm);
dcipher = Cipher.getInstance(mAlgorithm);
final AlgorithmParameterSpec paramSpec = new PBEParameterSpec(mSalt, iterationCount);
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (final java.security.InvalidAlgorithmParameterException e) {
LogUtils.severe(e);
} catch (final java.security.spec.InvalidKeySpecException e) {
LogUtils.severe(e);
} catch (final javax.crypto.NoSuchPaddingException e) {
LogUtils.severe(e);
} catch (final java.security.NoSuchAlgorithmException e) {
LogUtils.severe(e);
} catch (final java.security.InvalidKeyException e) {
LogUtils.severe(e);
}
}
}Example 57
| Project: eve-java-master File: EncryptionUtil.java View source code |
/**
* Encrypt a string.
*
* @param text
* the text
* @return encryptedText
* @throws InvalidKeyException
* the invalid key exception
* @throws InvalidAlgorithmParameterException
* the invalid algorithm parameter exception
* @throws NoSuchAlgorithmException
* the no such algorithm exception
* @throws InvalidKeySpecException
* the invalid key spec exception
* @throws NoSuchPaddingException
* the no such padding exception
* @throws IllegalBlockSizeException
* the illegal block size exception
* @throws BadPaddingException
* the bad padding exception
* @throws UnsupportedEncodingException
* the unsupported encoding exception
*/
public static String encrypt(final String text) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
final PBEParameterSpec pbeParamSpec = new PBEParameterSpec(S, C);
final PBEKeySpec pbeKeySpec = new PBEKeySpec(P);
final SecretKeyFactory keyFac = SecretKeyFactory.getInstance(ENC);
final SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
final Cipher pbeCipher = Cipher.getInstance(ENC);
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
final byte[] encryptedText = pbeCipher.doFinal(text.getBytes("UTF-8"));
String encodedString = new String(Base64.encodeBase64(encryptedText));
String safeString = encodedString.replace('+', '-').replace('/', '_');
return safeString;
}Example 58
| Project: gatein-portal-master File: PortalSetupService.java View source code |
public String decodePassword(String encodedPassword) throws Exception {
if (encodedPassword == null) {
return null;
}
byte[] salt = SALT.substring(0, 8).getBytes();
int count = COUNT;
char[] password = KEY.toCharArray();
PBEParameterSpec cipherSpec = new PBEParameterSpec(salt, count);
PBEKeySpec keySpec = new PBEKeySpec(password);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEwithMD5andDES");
SecretKey cipherKey = factory.generateSecret(keySpec);
return PBEUtils.decode64(encodedPassword, "PBEwithMD5andDES", cipherKey, cipherSpec);
}Example 59
| Project: ikvm-openjdk-master File: HmacPKCS12PBESHA1.java View source code |
/**
* Initializes the HMAC with the given secret key and algorithm parameters.
*
* @param key the secret key.
* @param params the algorithm parameters.
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this MAC.
u* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this MAC.
*/
protected void engineInit(Key key, AlgorithmParameterSpec params) throws InvalidKeyException, InvalidAlgorithmParameterException {
char[] passwdChars;
byte[] salt = null;
int iCount = 0;
if (key instanceof javax.crypto.interfaces.PBEKey) {
javax.crypto.interfaces.PBEKey pbeKey = (javax.crypto.interfaces.PBEKey) key;
passwdChars = pbeKey.getPassword();
// maybe null if unspecified
salt = pbeKey.getSalt();
// maybe 0 if unspecified
iCount = pbeKey.getIterationCount();
} else if (key instanceof SecretKey) {
byte[] passwdBytes = key.getEncoded();
if ((passwdBytes == null) || !(key.getAlgorithm().regionMatches(true, 0, "PBE", 0, 3))) {
throw new InvalidKeyException("Missing password");
}
passwdChars = new char[passwdBytes.length];
for (int i = 0; i < passwdChars.length; i++) {
passwdChars[i] = (char) (passwdBytes[i] & 0x7f);
}
} else {
throw new InvalidKeyException("SecretKey of PBE type required");
}
if (params == null) {
// generate default for salt and iteration count if necessary
if (salt == null) {
salt = new byte[20];
SunJCE.RANDOM.nextBytes(salt);
}
if (iCount == 0)
iCount = 100;
} else if (!(params instanceof PBEParameterSpec)) {
throw new InvalidAlgorithmParameterException("PBEParameterSpec type required");
} else {
PBEParameterSpec pbeParams = (PBEParameterSpec) params;
// make sure the parameter values are consistent
if (salt != null) {
if (!Arrays.equals(salt, pbeParams.getSalt())) {
throw new InvalidAlgorithmParameterException("Inconsistent value of salt between key and params");
}
} else {
salt = pbeParams.getSalt();
}
if (iCount != 0) {
if (iCount != pbeParams.getIterationCount()) {
throw new InvalidAlgorithmParameterException("Different iteration count between key and params");
}
} else {
iCount = pbeParams.getIterationCount();
}
}
// which is what PKCS#5 recommends and openssl does.
if (salt.length < 8) {
throw new InvalidAlgorithmParameterException("Salt must be at least 8 bytes long");
}
if (iCount <= 0) {
throw new InvalidAlgorithmParameterException("IterationCount must be a positive number");
}
byte[] derivedKey = PKCS12PBECipherCore.derive(passwdChars, salt, iCount, hmac.getDigestLength(), PKCS12PBECipherCore.MAC_KEY);
SecretKey cipherKey = new SecretKeySpec(derivedKey, "HmacSHA1");
hmac.init(cipherKey, null);
}Example 60
| Project: jdk7u-jdk-master File: HmacPKCS12PBESHA1.java View source code |
/**
* Initializes the HMAC with the given secret key and algorithm parameters.
*
* @param key the secret key.
* @param params the algorithm parameters.
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this MAC.
u* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this MAC.
*/
protected void engineInit(Key key, AlgorithmParameterSpec params) throws InvalidKeyException, InvalidAlgorithmParameterException {
char[] passwdChars;
byte[] salt = null;
int iCount = 0;
if (key instanceof javax.crypto.interfaces.PBEKey) {
javax.crypto.interfaces.PBEKey pbeKey = (javax.crypto.interfaces.PBEKey) key;
passwdChars = pbeKey.getPassword();
// maybe null if unspecified
salt = pbeKey.getSalt();
// maybe 0 if unspecified
iCount = pbeKey.getIterationCount();
} else if (key instanceof SecretKey) {
byte[] passwdBytes = key.getEncoded();
if ((passwdBytes == null) || !(key.getAlgorithm().regionMatches(true, 0, "PBE", 0, 3))) {
throw new InvalidKeyException("Missing password");
}
passwdChars = new char[passwdBytes.length];
for (int i = 0; i < passwdChars.length; i++) {
passwdChars[i] = (char) (passwdBytes[i] & 0x7f);
}
} else {
throw new InvalidKeyException("SecretKey of PBE type required");
}
if (params == null) {
// generate default for salt and iteration count if necessary
if (salt == null) {
salt = new byte[20];
SunJCE.RANDOM.nextBytes(salt);
}
if (iCount == 0)
iCount = 100;
} else if (!(params instanceof PBEParameterSpec)) {
throw new InvalidAlgorithmParameterException("PBEParameterSpec type required");
} else {
PBEParameterSpec pbeParams = (PBEParameterSpec) params;
// make sure the parameter values are consistent
if (salt != null) {
if (!Arrays.equals(salt, pbeParams.getSalt())) {
throw new InvalidAlgorithmParameterException("Inconsistent value of salt between key and params");
}
} else {
salt = pbeParams.getSalt();
}
if (iCount != 0) {
if (iCount != pbeParams.getIterationCount()) {
throw new InvalidAlgorithmParameterException("Different iteration count between key and params");
}
} else {
iCount = pbeParams.getIterationCount();
}
}
// which is what PKCS#5 recommends and openssl does.
if (salt.length < 8) {
throw new InvalidAlgorithmParameterException("Salt must be at least 8 bytes long");
}
if (iCount <= 0) {
throw new InvalidAlgorithmParameterException("IterationCount must be a positive number");
}
byte[] derivedKey = PKCS12PBECipherCore.derive(passwdChars, salt, iCount, hmac.getDigestLength(), PKCS12PBECipherCore.MAC_KEY);
SecretKey cipherKey = new SecretKeySpec(derivedKey, "HmacSHA1");
hmac.init(cipherKey, null);
}Example 61
| Project: ManagedRuntimeInitiative-master File: HmacPKCS12PBESHA1.java View source code |
/**
* Initializes the HMAC with the given secret key and algorithm parameters.
*
* @param key the secret key.
* @param params the algorithm parameters.
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this MAC.
u* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this MAC.
*/
protected void engineInit(Key key, AlgorithmParameterSpec params) throws InvalidKeyException, InvalidAlgorithmParameterException {
char[] passwdChars;
byte[] salt = null;
int iCount = 0;
if (key instanceof javax.crypto.interfaces.PBEKey) {
javax.crypto.interfaces.PBEKey pbeKey = (javax.crypto.interfaces.PBEKey) key;
passwdChars = pbeKey.getPassword();
// maybe null if unspecified
salt = pbeKey.getSalt();
// maybe 0 if unspecified
iCount = pbeKey.getIterationCount();
} else if (key instanceof SecretKey) {
byte[] passwdBytes = key.getEncoded();
if ((passwdBytes == null) || !(key.getAlgorithm().regionMatches(true, 0, "PBE", 0, 3))) {
throw new InvalidKeyException("Missing password");
}
passwdChars = new char[passwdBytes.length];
for (int i = 0; i < passwdChars.length; i++) {
passwdChars[i] = (char) (passwdBytes[i] & 0x7f);
}
} else {
throw new InvalidKeyException("SecretKey of PBE type required");
}
if (params == null) {
// generate default for salt and iteration count if necessary
if (salt == null) {
salt = new byte[20];
SunJCE.RANDOM.nextBytes(salt);
}
if (iCount == 0)
iCount = 100;
} else if (!(params instanceof PBEParameterSpec)) {
throw new InvalidAlgorithmParameterException("PBEParameterSpec type required");
} else {
PBEParameterSpec pbeParams = (PBEParameterSpec) params;
// make sure the parameter values are consistent
if (salt != null) {
if (!Arrays.equals(salt, pbeParams.getSalt())) {
throw new InvalidAlgorithmParameterException("Inconsistent value of salt between key and params");
}
} else {
salt = pbeParams.getSalt();
}
if (iCount != 0) {
if (iCount != pbeParams.getIterationCount()) {
throw new InvalidAlgorithmParameterException("Different iteration count between key and params");
}
} else {
iCount = pbeParams.getIterationCount();
}
}
// which is what PKCS#5 recommends and openssl does.
if (salt.length < 8) {
throw new InvalidAlgorithmParameterException("Salt must be at least 8 bytes long");
}
if (iCount <= 0) {
throw new InvalidAlgorithmParameterException("IterationCount must be a positive number");
}
byte[] derivedKey = PKCS12PBECipherCore.derive(passwdChars, salt, iCount, hmac.getDigestLength(), PKCS12PBECipherCore.MAC_KEY);
SecretKey cipherKey = new SecretKeySpec(derivedKey, "HmacSHA1");
hmac.init(cipherKey, null);
}Example 62
| Project: MCFreedomLauncher-master File: SPAuthenticationService.java View source code |
private static Cipher getCipher(int mode, String password) throws Exception {
Random random = new Random(43287234L);
byte[] salt = new byte[8];
random.nextBytes(salt);
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 5);
SecretKey pbeKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(new PBEKeySpec(password.toCharArray()));
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
cipher.init(mode, pbeKey, pbeParamSpec);
return cipher;
}Example 63
| Project: McLauncher-master File: Loginer.java View source code |
private Cipher getCipher(int mode, String password) throws Exception {
final Random random = new Random(43287234L);
final byte[] salt = new byte[8];
random.nextBytes(salt);
final PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 5);
final SecretKey pbeKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(new PBEKeySpec(password.toCharArray()));
final Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
cipher.init(mode, pbeKey, pbeParamSpec);
return cipher;
}Example 64
| Project: Offline3fAuth-master File: ObjCrypter.java View source code |
/** Encrypts the Serializable object with AES
* @param plaintext the Serializable object to encrypt
* @param password the password to use for encryption, if it's null or empty the default pass will be used instead
* @return an encrypter String formatted as json containing the used cipher and the encrypted object
*/
public static String encryptAES(Serializable plaintext, String password) {
try {
final PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20);
final PBEKeySpec pbeKeySpec = new PBEKeySpec((password == null || password.equalsIgnoreCase("")) ? defaultPass : password.toCharArray());
final SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(AES_ALG);
final SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
final Cipher cipher = Cipher.getInstance(AES_ALG);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, pbeParamSpec);
return gson.toJson(new SealedObject(plaintext, cipher));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 65
| Project: openbd-core-master File: Cryptography.java View source code |
public static byte[] doCipher(int _mode, byte[] _data, String _fullAlgorithm, byte[] _key, byte[] _ivOrSalt, int _iterations) throws GeneralSecurityException {
String algorithm;
int mode = (_mode == ENCRYPT_MODE ? javax.crypto.Cipher.ENCRYPT_MODE : javax.crypto.Cipher.DECRYPT_MODE);
String feedbackMode = "ecb";
int delimIndex = _fullAlgorithm.indexOf('/');
if (delimIndex != -1) {
algorithm = _fullAlgorithm.substring(0, delimIndex).toLowerCase();
int secondDelim = _fullAlgorithm.indexOf('/', delimIndex + 1);
if (secondDelim == -1) {
feedbackMode = _fullAlgorithm.substring(delimIndex + 1).toLowerCase();
} else {
feedbackMode = _fullAlgorithm.substring(delimIndex + 1, secondDelim).toLowerCase();
}
} else {
algorithm = _fullAlgorithm.toLowerCase();
}
byte[] ivOrSalt = _ivOrSalt;
byte[] data = _data;
boolean prependIV = false;
boolean ecbMode = feedbackMode.equals("ecb");
boolean isPBE = algorithm.startsWith("pbe");
SecretKey secretKey = new SecretKeySpec(Base64.base64Decode(_key), algorithm);
Cipher cipher = Cipher.getInstance(_fullAlgorithm);
int ivSize = cipher.getBlockSize();
//-- work out the IV (or Salt) value
if (_ivOrSalt != null) {
ivOrSalt = _ivOrSalt;
// if we're decrypting and the mode requires an IV and no IV has been specified we need to obtain it from the data
} else if (mode == javax.crypto.Cipher.DECRYPT_MODE && (isPBE || !ecbMode)) {
ivOrSalt = new byte[ivSize];
data = new byte[data.length - ivSize];
System.arraycopy(_data, 0, ivOrSalt, 0, ivSize);
System.arraycopy(_data, ivSize, data, 0, data.length);
// otherwise generate it. This should be prepended to the encrypted data
} else if (isPBE || !ecbMode) {
ivOrSalt = new byte[ivSize];
secureRandom.nextBytes(ivOrSalt);
prependIV = true;
}
AlgorithmParameterSpec paramSpec = null;
if (// i.e. this is Password Based Encryption alg
isPBE) {
paramSpec = new PBEParameterSpec(ivOrSalt, _iterations);
} else if (!ecbMode) {
paramSpec = new IvParameterSpec(ivOrSalt);
}
if (paramSpec != null) {
cipher.init(mode, secretKey, paramSpec);
} else {
cipher.init(mode, secretKey);
}
// if we're encrypting and had to generate the IV then prepend it to the encrypted data
if (//TODO: simplify
prependIV && (isPBE || !ecbMode)) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
bos.write(ivOrSalt);
bos.write(cipher.doFinal(data));
} catch (// not going to happen
IOException // not going to happen
e) {
com.nary.Debug.printStackTrace(e);
}
return bos.toByteArray();
} else {
return cipher.doFinal(data);
}
}Example 66
| Project: OpenDashboard-master File: Utilities.java View source code |
/**
* Encrypt the password.
*
* @param password the password
* @return the encrypted password string
* @throws GeneralSecurityException the general security exception
*/
public static String encrypt(String password) throws GeneralSecurityException {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(KEY));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
return base64Encode(pbeCipher.doFinal(password.getBytes()));
}Example 67
| Project: openjdk8-jdk-master File: PBMAC1Core.java View source code |
/**
* Initializes the HMAC with the given secret key and algorithm parameters.
*
* @param key the secret key.
* @param params the algorithm parameters.
*
* @exception InvalidKeyException if the given key is inappropriate for
* initializing this MAC.
* @exception InvalidAlgorithmParameterException if the given algorithm
* parameters are inappropriate for this MAC.
*/
protected void engineInit(Key key, AlgorithmParameterSpec params) throws InvalidKeyException, InvalidAlgorithmParameterException {
char[] passwdChars;
byte[] salt = null;
int iCount = 0;
if (key instanceof javax.crypto.interfaces.PBEKey) {
javax.crypto.interfaces.PBEKey pbeKey = (javax.crypto.interfaces.PBEKey) key;
passwdChars = pbeKey.getPassword();
// maybe null if unspecified
salt = pbeKey.getSalt();
// maybe 0 if unspecified
iCount = pbeKey.getIterationCount();
} else if (key instanceof SecretKey) {
byte[] passwdBytes = key.getEncoded();
if ((passwdBytes == null) || !(key.getAlgorithm().regionMatches(true, 0, "PBE", 0, 3))) {
throw new InvalidKeyException("Missing password");
}
passwdChars = new char[passwdBytes.length];
for (int i = 0; i < passwdChars.length; i++) {
passwdChars[i] = (char) (passwdBytes[i] & 0x7f);
}
} else {
throw new InvalidKeyException("SecretKey of PBE type required");
}
if (params == null) {
// retrieve the generated defaults.
if ((salt == null) || (iCount == 0)) {
throw new InvalidAlgorithmParameterException("PBEParameterSpec required for salt and iteration count");
}
} else if (!(params instanceof PBEParameterSpec)) {
throw new InvalidAlgorithmParameterException("PBEParameterSpec type required");
} else {
PBEParameterSpec pbeParams = (PBEParameterSpec) params;
// make sure the parameter values are consistent
if (salt != null) {
if (!Arrays.equals(salt, pbeParams.getSalt())) {
throw new InvalidAlgorithmParameterException("Inconsistent value of salt between key and params");
}
} else {
salt = pbeParams.getSalt();
}
if (iCount != 0) {
if (iCount != pbeParams.getIterationCount()) {
throw new InvalidAlgorithmParameterException("Different iteration count between key and params");
}
} else {
iCount = pbeParams.getIterationCount();
}
}
// which is what PKCS#5 recommends and openssl does.
if (salt.length < 8) {
throw new InvalidAlgorithmParameterException("Salt must be at least 8 bytes long");
}
if (iCount <= 0) {
throw new InvalidAlgorithmParameterException("IterationCount must be a positive number");
}
PBEKeySpec pbeSpec = new PBEKeySpec(passwdChars, salt, iCount, blockLength);
// password char[] was cloned in PBEKeySpec constructor,
// so we can zero it out here
java.util.Arrays.fill(passwdChars, ' ');
SecretKey s = null;
PBKDF2Core kdf = getKDFImpl(kdfAlgo);
try {
s = kdf.engineGenerateSecret(pbeSpec);
} catch (InvalidKeySpecException ikse) {
InvalidKeyException ike = new InvalidKeyException("Cannot construct PBE key");
ike.initCause(ikse);
throw ike;
}
byte[] derivedKey = s.getEncoded();
SecretKey cipherKey = new SecretKeySpec(derivedKey, kdfAlgo);
super.engineInit(cipherKey, null);
}Example 68
| Project: picketbox-master File: PBEIdentityLoginModule.java View source code |
private String encode(String secret) throws Exception {
// Create the PBE secret key
cipherSpec = new PBEParameterSpec(salt, iterationCount);
PBEKeySpec keySpec = new PBEKeySpec(pbepass);
SecretKeyFactory factory = SecretKeyFactory.getInstance(pbealgo);
SecretKey cipherKey = factory.generateSecret(keySpec);
// Decode the secret
Cipher cipher = Cipher.getInstance(pbealgo);
cipher.init(Cipher.ENCRYPT_MODE, cipherKey, cipherSpec);
byte[] encoding = cipher.doFinal(secret.getBytes());
return Base64Utils.tob64(encoding);
}Example 69
| Project: PlexRBAC-master File: PasswordUtils.java View source code |
public static String decrypt(String text) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, InvalidKeySpecException {
final byte[] cipherText = text.getBytes();
// decryption pass
// Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS7Padding", "BC");
// SecretKeySpec key = new SecretKeySpec(ENCRYPTION_KEY, "DESede");
// cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV_BYTES));
//
// byte[] plainText = new byte[cipherText.length];
// int ptLength = cipher.update(cipherText, 0, cipherText.length,
// plainText, 0);
// ptLength += cipher.doFinal(plainText, ptLength);
// decrypt the data using PBE
byte[] salt = new byte[] { 0x7d, 0x60, 0x43, 0x5f, 0x02, (byte) 0xe9, (byte) 0xe0, (byte) 0xae };
int iterationCount = 2048;
PBEKeySpec pbeSpec = new PBEKeySpec(ENCRYPTION_PASSWORD.toCharArray());
SecretKeyFactory keyFact = SecretKeyFactory.getInstance("PBEWithSHAAnd3KeyTripleDES", "BC");
Cipher cipher = Cipher.getInstance("PBEWithSHAAnd3KeyTripleDES", "BC");
Key sKey = keyFact.generateSecret(pbeSpec);
cipher.init(Cipher.DECRYPT_MODE, sKey, new PBEParameterSpec(salt, iterationCount));
return new String(cipher.doFinal(cipherText));
}Example 70
| Project: ProjectIndigo-master File: UserManager.java View source code |
private static final Cipher getCipher(int mode, String password) throws Exception {
Random random = new Random(43287234L);
byte[] salt = new byte[8];
random.nextBytes(salt);
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 5);
SecretKey pbeKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(new PBEKeySpec(password.toCharArray()));
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
cipher.init(mode, pbeKey, pbeParamSpec);
return cipher;
}Example 71
| Project: railo-master File: Cryptor.java View source code |
/**
* @param input - the clear-text input to be encrypted, or the encrypted input to be decrypted
* @param key - the encryption key
* @param algorithm - algorithm in JCE scheme
* @param ivOrSalt - Initialization Vector for algorithms with Feedback Mode that is not ECB, or Salt for Password Based Encryption algorithms
* @param iterations - number of Iterations for Password Based Encryption algorithms (recommended minimum value is 1000)
* @param doDecrypt - the Operation Type, pass false for Encrypt or true for Decrypt
* @return
* @throws PageException
*/
static byte[] crypt(byte[] input, String key, String algorithm, byte[] ivOrSalt, int iterations, boolean doDecrypt) throws PageException {
byte[] result = null;
Key secretKey = null;
AlgorithmParameterSpec params = null;
String algo = algorithm;
boolean isFBM = false, isPBE = StringUtil.startsWithIgnoreCase(algo, "PBE");
int ivsLen = 0, algoDelimPos = algorithm.indexOf('/');
if (algoDelimPos > -1) {
algo = algorithm.substring(0, algoDelimPos);
isFBM = !StringUtil.startsWithIgnoreCase(algorithm.substring(algoDelimPos + 1), "ECB");
}
try {
Cipher cipher = Cipher.getInstance(algorithm);
if (ivOrSalt == null) {
if (isPBE || isFBM) {
ivsLen = cipher.getBlockSize();
ivOrSalt = new byte[ivsLen];
if (doDecrypt)
System.arraycopy(input, 0, ivOrSalt, 0, ivsLen);
else
secureRandom.nextBytes(ivOrSalt);
}
}
if (isPBE) {
secretKey = SecretKeyFactory.getInstance(algorithm).generateSecret(new PBEKeySpec(key.toCharArray()));
// set Salt and Iterations for PasswordBasedEncryption
params = new PBEParameterSpec(ivOrSalt, iterations > 0 ? iterations : DEFAULT_ITERATIONS);
} else {
secretKey = new SecretKeySpec(Coder.decode(Coder.ENCODING_BASE64, key), algo);
if (isFBM)
// set Initialization Vector for non-ECB Feedback Mode
params = new IvParameterSpec(ivOrSalt);
}
if (doDecrypt) {
cipher.init(Cipher.DECRYPT_MODE, secretKey, params);
result = cipher.doFinal(input, ivsLen, input.length - ivsLen);
} else {
cipher.init(Cipher.ENCRYPT_MODE, secretKey, params);
result = new byte[ivsLen + cipher.getOutputSize(input.length)];
if (ivsLen > 0)
System.arraycopy(ivOrSalt, 0, result, 0, ivsLen);
cipher.doFinal(input, 0, input.length, result, ivsLen);
}
return result;
} catch (Throwable t) {
throw Caster.toPageException(t);
}
}Example 72
| Project: ranger-master File: PasswordUtils.java View source code |
public static String encryptPassword(String aPassword) throws IOException {
setPropertiesvalues(aPassword);
Map<String, String> env = System.getenv();
String encryptKeyStr = env.get("ENCRYPT_KEY");
char[] encryptKey;
if (encryptKeyStr == null) {
encryptKey = ENCRYPT_KEY;
} else {
encryptKey = encryptKeyStr.toCharArray();
}
String saltStr = env.get("ENCRYPT_SALT");
byte[] salt;
if (saltStr == null) {
salt = SALT;
} else {
salt = saltStr.getBytes();
}
String ret = null;
String strToEncrypt = null;
if (aPassword == null) {
strToEncrypt = "";
} else {
strToEncrypt = aPassword.length() + LEN_SEPARATOR_STR + password;
}
try {
Cipher engine = Cipher.getInstance(CRYPT_ALGO);
PBEKeySpec keySpec = new PBEKeySpec(encryptKey);
SecretKeyFactory skf = SecretKeyFactory.getInstance(CRYPT_ALGO);
SecretKey key = skf.generateSecret(keySpec);
engine.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, ITERATION_COUNT));
byte[] encryptedStr = engine.doFinal(strToEncrypt.getBytes());
ret = new String(Base64.encode(encryptedStr));
} catch (Throwable t) {
LOG.error("Unable to encrypt password due to error", t);
throw new IOException("Unable to encrypt password due to error", t);
}
return ret;
}Example 73
| Project: tesora-dve-pub-master File: PECryptoUtils.java View source code |
private static Cipher createCrypter(int mode) throws Exception {
// Create the key
KeySpec keySpec = new PBEKeySpec(settings.getPassword().toCharArray(), settings.getSalt(), settings.getIterations());
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
Cipher cipher = Cipher.getInstance(key.getAlgorithm());
cipher.init(mode, key, new PBEParameterSpec(settings.getSalt(), settings.getIterations()));
return cipher;
}Example 74
| Project: UnisaConnect-master File: CryptoMan_2.java View source code |
private static String encryptPkcs12(String plaintext, SecretKey key, byte[] salt) {
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, ITERATION_COUNT);
cipher.init(Cipher.ENCRYPT_MODE, key, pbeSpec);
// Log.d(TAG, "Cipher IV: " + toHex(cipher.getIV()));
byte[] cipherText = cipher.doFinal(plaintext.getBytes("UTF-8"));
return String.format("%s%s%s", toBase64(salt), DELIMITER, toBase64(cipherText));
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}Example 75
| Project: weplantaforest-master File: ParamEncrypter.java View source code |
public void init(final String pass, final byte[] salt, final int iterations) throws SecurityException {
try {
final PBEParameterSpec ps = new PBEParameterSpec(salt, iterations);
final SecretKeyFactory skf = SecretKeyFactory.getInstance(ALGORITHM);
final PBEKeySpec ks = new PBEKeySpec(pass.toCharArray());
final SecretKey sk = skf.generateSecret(ks);
_encrypter = Cipher.getInstance(TRANSFORMATION);
_encrypter.init(Cipher.ENCRYPT_MODE, sk, ps);
_decrypter = Cipher.getInstance(TRANSFORMATION);
_decrypter.init(Cipher.DECRYPT_MODE, sk, ps);
} catch (final Exception e) {
throw new SecurityException("Could not initialize CryptoLibrary: ", e);
}
}Example 76
| Project: xipki-master File: PasswordBasedEncryption.java View source code |
public static byte[] encrypt(final byte[] plaintext, final char[] password, final int iterationCount, final byte[] salt) throws GeneralSecurityException {
ParamUtil.requireNonNull("plaintext", plaintext);
ParamUtil.requireNonNull("password", password);
ParamUtil.requireMin("iterationCount", iterationCount, 1);
ParamUtil.requireNonNull("salt", salt);
init();
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(CIPHER_ALGO, "BC");
PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
SecretKey pbeKey = secretKeyFactory.generateSecret(pbeKeySpec);
Cipher cipher = Cipher.getInstance(CIPHER_ALGO, "BC");
PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, iterationCount);
cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParameterSpec);
pbeKeySpec.clearPassword();
return cipher.doFinal(plaintext);
}Example 77
| Project: WebGoat-Legacy-master File: Encoding.java View source code |
/**
* Convenience method for encrypting a string.
*
* @param str
* Description of the Parameter
* @param pw
* Description of the Parameter
* @return String the encrypted string.
*/
public static synchronized String decryptString(String str, String pw) {
try {
PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec(salt, 20);
SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
Cipher passwordDecryptCipher = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding");
char[] pass = pw.toCharArray();
SecretKey k = kf.generateSecret(new javax.crypto.spec.PBEKeySpec(pass));
passwordDecryptCipher.init(Cipher.DECRYPT_MODE, k, ps);
byte[] dec = decoder.decodeBuffer(str);
byte[] utf8 = passwordDecryptCipher.doFinal(dec);
return new String(utf8, "UTF-8");
} catch (Exception e) {
return ("This is not an encrypted string");
}
}Example 78
| Project: AccessAdmin-master File: EncryptedPreferences.java View source code |
@SuppressWarnings("deprecation")
protected String encrypt(String value) {
try {
final byte[] bytes = value != null ? value.getBytes(UTF8) : new byte[0];
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(context.getContentResolver(), Settings.System.ANDROID_ID).getBytes(UTF8), 20));
return new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP), UTF8);
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 79
| Project: AegisWallet-master File: Crypto.java View source code |
public static String encryptPkcs12(String plaintext, SecretKey key, byte[] salt) {
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, ITERATION_COUNT);
cipher.init(Cipher.ENCRYPT_MODE, key, pbeSpec);
byte[] cipherText = cipher.doFinal(plaintext.getBytes("UTF-8"));
return String.format("%s%s%s", toBase64(salt), DELIMITER, toBase64(cipherText));
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}Example 80
| Project: baas.io-sdk-android-master File: BaasioPreferences.java View source code |
protected static String encrypt(Context context, String uuid, String value) {
try {
final byte[] bytes = value != null ? value.getBytes("UTF-8") : new byte[0];
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(uuid.getBytes("UTF-8"), 20));
return new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP), "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 81
| Project: ButterRemote-Android-master File: ObscuredSharedPreferences.java View source code |
protected String encrypt(String value) {
try {
final byte[] bytes = value != null ? value.getBytes(UTF8) : new byte[0];
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(PBE_WITH_MD5_AND_DES);
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
Cipher pbeCipher = Cipher.getInstance(PBE_WITH_MD5_AND_DES);
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(context.getContentResolver(), Settings.System.ANDROID_ID).getBytes(UTF8), 20));
return new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP), UTF8);
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 82
| Project: CoursesPortlet-master File: SecureRequestCredentials.java View source code |
private static Cipher getCipher(String username, int opmode) {
final Cipher cipher;
try {
cipher = Cipher.getInstance(PASSWORD_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
throw new Error("Failed to create Cipher for algorithm '" + PASSWORD_ALGORITHM + "'. " + SecureRequestCredentials.class.getSimpleName() + " will not work", e);
} catch (NoSuchPaddingException e) {
throw new Error("Failed to create Cipher for algorithm '" + PASSWORD_ALGORITHM + "'. " + SecureRequestCredentials.class.getSimpleName() + " will not work", e);
}
final byte[] salt = getSalt(username);
final PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, ITERATIONS);
try {
cipher.init(opmode, SECRET_KEY, pbeParamSpec);
} catch (InvalidKeyException e) {
throw new Error("Failed to init Cipher for SecretKey '" + SECRET_KEY + "'. " + SecureRequestCredentials.class.getSimpleName() + " will not work", e);
} catch (InvalidAlgorithmParameterException e) {
throw new Error("Failed to init Cipher for PBEParameterSpec '" + pbeParamSpec + "'. " + SecureRequestCredentials.class.getSimpleName() + " will not work", e);
}
return cipher;
}Example 83
| Project: DevConSummit-master File: ObscuredSharedPreferences.java View source code |
protected String encrypt(String value) {
try {
final byte[] bytes = value != null ? value.getBytes(UTF8) : new byte[0];
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(context.getContentResolver(), Settings.System.ANDROID_ID).getBytes(UTF8), 20));
return new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP), UTF8);
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 84
| Project: emf-master File: AESCipherImpl.java View source code |
private static byte[] transformWithPassword(byte[] bytes, byte[] iv, String password, int mode) throws Exception {
// generate the key
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(PBE_ALGORITHM);
SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(iv, PBE_ITERATIONS);
// encrypt the input
Cipher keyCipher = Cipher.getInstance(PBE_ALGORITHM);
keyCipher.init(mode, pbeKey, pbeParamSpec);
return keyCipher.doFinal(bytes);
}Example 85
| Project: GeoGig-master File: Remote.java View source code |
public static String encryptPassword(String password) {
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
return Base64.encodeBytes(pbeCipher.doFinal(password.getBytes("UTF-8")));
} catch (Exception e) {
return password;
}
}Example 86
| Project: gig-master File: Remote.java View source code |
public static String encryptPassword(String password) {
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
return Base64.encodeBytes(pbeCipher.doFinal(password.getBytes("UTF-8")));
} catch (Exception e) {
return password;
}
}Example 87
| Project: GPXConverter-master File: AccountManager.java View source code |
public static String encrypt(String property) throws GeneralSecurityException, UnsupportedEncodingException {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
return base64Encode(pbeCipher.doFinal(property.getBytes("UTF-8")));
}Example 88
| Project: hbci4java-master File: HBCIPassportRDH.java View source code |
public void saveChanges() {
try {
if (getPassportKey() == null)
setPassportKey(calculatePassportKey(FOR_SAVE));
PBEParameterSpec paramspec = new PBEParameterSpec(CIPHER_SALT, CIPHER_ITERATIONS);
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
cipher.init(Cipher.ENCRYPT_MODE, getPassportKey(), paramspec);
File passportfile = new File(getFilename());
File directory = passportfile.getAbsoluteFile().getParentFile();
String prefix = passportfile.getName() + "_";
File tempfile = File.createTempFile(prefix, "", directory);
ObjectOutputStream o = new ObjectOutputStream(new CipherOutputStream(new FileOutputStream(tempfile), cipher));
o.writeObject(getCountry());
o.writeObject(getBLZ());
o.writeObject(getHost());
o.writeObject(getPort());
o.writeObject(getUserId());
o.writeObject(getSysId());
o.writeObject(getSigId());
o.writeObject(getBPD());
o.writeObject(getUPD());
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
HBCIKey key = getKey(i, j);
if (key != null) {
o.writeObject(new HBCIKey(key.country, key.blz, key.userid, key.num, key.version, key.key));
} else
o.writeObject(null);
}
}
o.writeObject(getCID());
o.writeObject(getHBCIVersion());
o.writeObject(getCustomerId());
o.close();
this.safeReplace(passportfile, tempfile);
HBCIKey k = getMyPrivateSigKey();
if (k != null && k.key != null && !(k.key instanceof RSAPrivateCrtKey)) {
HBCIUtils.log("private sig key is no CRT key, please contact the author!", HBCIUtils.LOG_WARN);
}
k = getMyPrivateEncKey();
if (k != null && k.key != null && !(k.key instanceof RSAPrivateCrtKey)) {
HBCIUtils.log("private enc key is no CRT key, please contact the author!", HBCIUtils.LOG_WARN);
}
} catch (Exception e) {
throw new HBCI_Exception("*** saving of passport file failed", e);
}
}Example 89
| Project: hutool-master File: SymmetricCrypto.java View source code |
/**
* �始化
* @param algorithm 算法
* @param key 密钥,如果为<code>null</code>自动生�一个key
* @return {@link SymmetricCrypto}
*/
public SymmetricCrypto init(String algorithm, SecretKey key) {
this.secretKey = key;
if (algorithm.startsWith("PBE")) {
//对于PBE算法使用éš?æœºæ•°åŠ ç›?
this.params = new PBEParameterSpec(RandomUtil.randomBytes(8), 100);
}
try {
clipher = Cipher.getInstance(algorithm);
} catch (Exception e) {
throw new CryptoException(e);
}
return this;
}Example 90
| Project: ilarkesto-master File: PBECrypt.java View source code |
public static byte[] encrypt(byte[] input, char[] password) throws Exception {
/*
* Get ourselves a random number generator, needed in a number of places for encrypting.
*/
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
/*
* A "salt" is considered an essential part of password-based encryption. The salt is selected at
* random for each encryption. It is not considered "sensitive", so it is tacked onto the generated
* ciphertext without any special processing. It doesn't matter if an attacker actually gets the salt.
* The salt is used as part of the key, with the very useful result that if you encrypt the same
* plaintext with the same password twice, you get *different* ciphertexts. There are lots of pages on
* the 'net with information about salts and password-based encryption, so read them if you want more
* details. Suffice to say salt=good, no salt=bad.
*/
byte[] salt = new byte[SALT_LENGTH];
sr.nextBytes(salt);
/*
* We've now got enough information to build the actual key. We do this by encapsulating the variables
* in a PBEKeySpec and using a SecretKeyFactory to transform the spec into a key.
*/
PBEKeySpec keyspec = new PBEKeySpec(password, salt, ITERATION_COUNT);
SecretKeyFactory skf = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey key = skf.generateSecret(keyspec);
/*
* We'll use a ByteArrayOutputStream to conveniently gather up data as it's encrypted.
*/
ByteArrayOutputStream baos = new ByteArrayOutputStream();
/*
* We've to a key, but to actually encrypt something, we need a "cipher". The cipher is created, then
* initialized with the key, salt, and iteration count. We use a PBEParameterSpec to hold the salt and
* iteration count needed by the Cipher object.
*/
PBEParameterSpec paramspec = new PBEParameterSpec(salt, ITERATION_COUNT);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key, paramspec, sr);
/*
* First, in our output, we need to save the salt in plain unencrypted form.
*/
baos.write(salt);
/*
* Next, encrypt our plaintext using the Cipher object, and write it into our output buffer.
*/
baos.write(cipher.doFinal(input));
/*
* We're done. For security reasons, we probably want the PBEKeySpec object to clear its internal copy
* of the password, so it can't be stolen later.
*/
keyspec.clearPassword();
return baos.toByteArray();
}Example 91
| Project: ISAcreator-master File: EncryptedObject.java View source code |
/**
* Generates a key given a passphrase using the PBEWithMD5AndDES algorithm
*
* @param passphrase - The passphrase to generate the key with
* @throws NoSuchAlgorithmException *
* @throws NoSuchPaddingException *
* @throws InvalidKeyException *
* @throws InvalidKeySpecException *
* @throws InvalidAlgorithmParameterException
* *
*/
public void generateKey(String passphrase) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException, InvalidAlgorithmParameterException {
KeySpec keySpec = new PBEKeySpec(passphrase.toCharArray(), salt, iterationCount);
SecretKey secretKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
// initialise the encryption cipher
encryptCipher = Cipher.getInstance(secretKey.getAlgorithm());
// initialise the decryption cipher
decryptCipher = Cipher.getInstance(secretKey.getAlgorithm());
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
decryptCipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
}Example 92
| Project: Lucee-master File: Cryptor.java View source code |
private static byte[] _crypt(byte[] input, String key, String algorithm, byte[] ivOrSalt, int iterations, boolean doDecrypt) throws PageException {
byte[] result = null;
Key secretKey = null;
AlgorithmParameterSpec params = null;
String algo = algorithm;
boolean isFBM = false, isPBE = StringUtil.startsWithIgnoreCase(algo, "PBE");
int ivsLen = 0, algoDelimPos = algorithm.indexOf('/');
if (algoDelimPos > -1) {
algo = algorithm.substring(0, algoDelimPos);
isFBM = !StringUtil.startsWithIgnoreCase(algorithm.substring(algoDelimPos + 1), "ECB");
}
try {
Cipher cipher = Cipher.getInstance(algorithm);
if (ivOrSalt == null) {
if (isPBE || isFBM) {
ivsLen = cipher.getBlockSize();
ivOrSalt = new byte[ivsLen];
if (doDecrypt)
System.arraycopy(input, 0, ivOrSalt, 0, ivsLen);
else
secureRandom.nextBytes(ivOrSalt);
}
}
if (isPBE) {
secretKey = SecretKeyFactory.getInstance(algorithm).generateSecret(new PBEKeySpec(key.toCharArray()));
// set Salt and Iterations for PasswordBasedEncryption
params = new PBEParameterSpec(ivOrSalt, iterations > 0 ? iterations : DEFAULT_ITERATIONS);
} else {
secretKey = new SecretKeySpec(Coder.decode(Coder.ENCODING_BASE64, key), algo);
if (isFBM)
// set Initialization Vector for non-ECB Feedback Mode
params = new IvParameterSpec(ivOrSalt);
}
if (doDecrypt) {
cipher.init(Cipher.DECRYPT_MODE, secretKey, params);
result = cipher.doFinal(input, ivsLen, input.length - ivsLen);
} else {
cipher.init(Cipher.ENCRYPT_MODE, secretKey, params);
result = new byte[ivsLen + cipher.getOutputSize(input.length)];
if (ivsLen > 0)
System.arraycopy(ivOrSalt, 0, result, 0, ivsLen);
cipher.doFinal(input, 0, input.length, result, ivsLen);
}
return result;
} catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
throw Caster.toPageException(t);
}
}Example 93
| Project: nexus-core-master File: DefaultPlexusCipher.java View source code |
// ---------------------------------------------------------------
private Cipher init(String passPhrase, byte[] salt, boolean encrypt) throws PlexusCipherException {
int mode = encrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE;
try {
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray());
SecretKey key = SecretKeyFactory.getInstance(algorithm, SECURITY_PROVIDER).generateSecret(keySpec);
Cipher cipher = Cipher.getInstance(algorithm);
PBEParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
cipher.init(mode, key, paramSpec);
return cipher;
} catch (Exception e) {
throw new PlexusCipherException(e);
}
}Example 94
| Project: nifi-master File: OpenSSLPKCS5CipherProvider.java View source code |
protected Cipher getInitializedCipher(EncryptionMethod encryptionMethod, String password, byte[] salt, boolean encryptMode) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
if (encryptionMethod == null) {
throw new IllegalArgumentException("The encryption method must be specified");
}
if (StringUtils.isEmpty(password)) {
throw new IllegalArgumentException("Encryption with an empty password is not supported");
}
validateSalt(encryptionMethod, salt);
String algorithm = encryptionMethod.getAlgorithm();
String provider = encryptionMethod.getProvider();
// Initialize secret key from password
final PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
final SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm, provider);
SecretKey tempKey = factory.generateSecret(pbeKeySpec);
final PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, getIterationCount());
Cipher cipher = Cipher.getInstance(algorithm, provider);
cipher.init(encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, tempKey, parameterSpec);
return cipher;
}Example 95
| Project: OneSwarm-master File: CryptoManagerImpl.java View source code |
protected byte[] encryptWithPBE(byte[] data, char[] password) throws CryptoManagerException {
try {
byte[] salt = new byte[8];
new SecureRandom().nextBytes(salt);
PBEKeySpec keySpec = new PBEKeySpec(password);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(PBE_ALG);
SecretKey key = keyFactory.generateSecret(keySpec);
PBEParameterSpec paramSpec = new PBEParameterSpec(salt, PBE_ITERATIONS);
Cipher cipher = Cipher.getInstance(PBE_ALG);
cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
byte[] enc = cipher.doFinal(data);
byte[] res = new byte[salt.length + enc.length];
System.arraycopy(salt, 0, res, 0, salt.length);
System.arraycopy(enc, 0, res, salt.length, enc.length);
return (res);
} catch (Throwable e) {
throw (new CryptoManagerException("PBE encryption failed", e));
}
}Example 96
| Project: org.eclipse.emf-master File: AESCipherImpl.java View source code |
private static byte[] transformWithPassword(byte[] bytes, byte[] iv, String password, int mode) throws Exception {
// generate the key
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(PBE_ALGORITHM);
SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(iv, PBE_ITERATIONS);
// encrypt the input
Cipher keyCipher = Cipher.getInstance(PBE_ALGORITHM);
keyCipher.init(mode, pbeKey, pbeParamSpec);
return keyCipher.doFinal(bytes);
}Example 97
| Project: orion.server-master File: SimpleUserPasswordUtil.java View source code |
private static byte[] decryptPassword(byte[] password, byte[] salt) {
try {
byte[] decryptedPassword = null;
PBEKeySpec pbeKeySpec = new PBEKeySpec(getPassword(), salt, 1024, 256);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(ENCRYPTION_ALGORITHM);
SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, 10);
Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey, pbeParameterSpec);
decryptedPassword = cipher.doFinal(password);
return decryptedPassword;
} catch (NoSuchAlgorithmException e) {
LogHelper.log(e);
} catch (InvalidKeySpecException e) {
LogHelper.log(e);
} catch (InvalidKeyException e) {
LogHelper.log(e);
} catch (IllegalBlockSizeException e) {
LogHelper.log(e);
} catch (BadPaddingException e) {
LogHelper.log(e);
} catch (NoSuchPaddingException e) {
LogHelper.log(e);
} catch (InvalidAlgorithmParameterException e) {
LogHelper.log(e);
}
return null;
}Example 98
| Project: osp-master File: Cryptic.java View source code |
/**
* Encrypts the input with a password and saves in cryptic form.
*
* @param input UTF-8 String to encrypt
* @return the encrypted content
*/
public String encrypt(String content, String password) {
try {
// create the key and parameter spec
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, interactions);
SecretKey key = SecretKeyFactory.getInstance(keyFormat).generateSecret(keySpec);
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, interactions);
// create the cipher
Cipher ecipher = Cipher.getInstance(key.getAlgorithm());
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
// get byte[] from content and encrypt with cipher
byte[] bytes = content.getBytes(encoding);
byte[] enc = ecipher.doFinal(bytes);
// save encrypted bytes as string of chars 0-63
// note this doubles the string length
cryptic = new String(Base64Coder.encode(enc));
} catch (Exception ex) {
ex.printStackTrace();
}
return cryptic;
}Example 99
| Project: oxalis-master File: EncryptionTest.java View source code |
/**
* Experimental test method. Does not test any part of the system
*
* @throws Exception
*/
@Test
public void encryptDataWithWrappedKey() throws Exception {
// Creates the shared key to be used for encrypting the data
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
Key sharedKey = keyGenerator.generateKey();
// Wraps the shared key within an asymmetric key
String password = "The quick brown fox jumped over the lazy dog";
byte[] salt = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x07, 0x06, 0x08 };
PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, 20);
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey passwordKey = kf.generateSecret(pbeKeySpec);
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
cipher.init(Cipher.WRAP_MODE, passwordKey, pbeParameterSpec);
byte[] wrappedSharedKey = cipher.wrap(sharedKey);
// Encrypt some data with shared key
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sharedKey);
String plainText = "Hello world";
byte[] input = plainText.getBytes();
byte[] encrypted = cipher.doFinal(input);
// Read the wrapped key and the encrypted data
// First; unwrap the key
cipher = Cipher.getInstance("PBEWithMD5AndDES");
// TODO: pass the parameters of the wrappedSharedKey
cipher.init(Cipher.UNWRAP_MODE, passwordKey, pbeParameterSpec);
Key unwrappedKey = cipher.unwrap(wrappedSharedKey, "AES", Cipher.SECRET_KEY);
// Decrypt the data
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, unwrappedKey);
String newData = new String(cipher.doFinal(encrypted));
assertEquals(newData, plainText);
}Example 100
| Project: pentaho-platform-master File: CipherEncryptionService.java View source code |
public void afterPropertiesSet() throws ObjectFactoryException {
if ((saltString == null) || (algorithm == null) || (encryptionKey == null)) {
throw new ObjectFactoryException("Required properties not set - need Salt, algorithm and encryption key");
}
if (saltString.length() != this.saltLength) {
// Make sure that the salt length is 8 bytes - the PBEParameterSpec doesn't anything but
if (saltString.length() < saltLength) {
// postfix bytes to pad it out
saltString = (saltString + "!@#$%^&*").substring(0, saltLength);
} else if (saltString.length() > saltLength) {
// Trim off longer than 8-bytes
saltString = saltString.substring(0, saltLength);
}
}
byte[] saltBytes = saltString.getBytes();
paramSpec = new PBEParameterSpec(saltBytes, getIterations());
PBEKeySpec skeySpec = new PBEKeySpec(getEncryptionKey().toCharArray(), saltBytes, getIterations());
try {
secretKey = SecretKeyFactory.getInstance(getAlgorithm()).generateSecret(skeySpec);
} catch (Exception ex) {
ex.printStackTrace();
throw new ObjectFactoryException("Encryption requested not available");
}
}Example 101
| Project: popcorn-android-master File: ObscuredSharedPreferences.java View source code |
protected String encrypt(String value) {
try {
final byte[] bytes = value != null ? value.getBytes(UTF8) : new byte[0];
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(context.getContentResolver(), Settings.System.ANDROID_ID).getBytes(UTF8), 20));
return new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP), UTF8);
} catch (Exception e) {
throw new RuntimeException(e);
}
}