/** * 加密 * @param datasource byte[] * @param password String * @return byte[] */ public static String encrypt(String datasource, String password) { try { if(StringUtils.trimToNull(datasource) == null){ return null; } SecureRandom random = new SecureRandom(); DESKeySpec desKey = new DESKeySpec(password.getBytes()); // 创建一个密匙工厂,然后用它把DESKeySpec转换成 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(desKey); // Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance("DES"); // 用密匙初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, securekey, random); // 现在,获取数据并加密 // 正式执行加密操作 return new BASE64Encoder().encode(cipher.doFinal(datasource.getBytes())); } catch (Throwable e) { e.printStackTrace(); } return null; }
private static byte[] calculatePbeMac( DERObjectIdentifier oid, byte[] salt, int itCount, char[] password, byte[] data, String provider) throws Exception { SecretKeyFactory keyFact = SecretKeyFactory.getInstance(oid.getId(), provider); PBEParameterSpec defParams = new PBEParameterSpec(salt, itCount); PBEKeySpec pbeSpec = new PBEKeySpec(password); SecretKey key = keyFact.generateSecret(pbeSpec); Mac mac = Mac.getInstance(oid.getId(), provider); mac.init(key, defParams); mac.update(data); return mac.doFinal(); }
/** * A function that generates password-based AES & HMAC keys. It prints out exceptions but * doesn't throw them since none should be encountered. If they are * encountered, the return value is null. * * @param password The password to derive the keys from. * @return The AES & HMAC keys. * @throws GeneralSecurityException if AES is not implemented on this system, * or a suitable RNG is not available */ public static SecretKeys generateKeyFromPassword(String password, byte[] salt) throws GeneralSecurityException { fixPrng(); //Get enough random bytes for both the AES key and the HMAC key: KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, PBE_ITERATION_COUNT, AES_KEY_LENGTH_BITS + HMAC_KEY_LENGTH_BITS); SecretKeyFactory keyFactory = SecretKeyFactory .getInstance(PBE_ALGORITHM); byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded(); // Split the random bytes into two parts: byte[] confidentialityKeyBytes = copyOfRange(keyBytes, 0, AES_KEY_LENGTH_BITS /8); byte[] integrityKeyBytes = copyOfRange(keyBytes, AES_KEY_LENGTH_BITS /8, AES_KEY_LENGTH_BITS /8 + HMAC_KEY_LENGTH_BITS /8); //Generate the AES key SecretKey confidentialityKey = new SecretKeySpec(confidentialityKeyBytes, CIPHER); //Generate the HMAC key SecretKey integrityKey = new SecretKeySpec(integrityKeyBytes, HMAC_ALGORITHM); return new SecretKeys(confidentialityKey, integrityKey); }
private static byte[] PBKDF2(char[] secret, byte[] salt, int count, int keyLength) throws GeneralSecurityException { PBEKeySpec keySpec = new PBEKeySpec(secret, salt, count, keyLength); SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); SecretKey key = skf.generateSecret(keySpec); byte[] result = key.getEncoded(); return result; }
public PKCS8EncodedKeySpec getEncodedPrivateKeySpec(String key, String password) throws Exception { String privateKeyPEM = key .replace("-----BEGIN ENCRYPTED PRIVATE KEY-----", "") .replace("-----END ENCRYPTED PRIVATE KEY-----", "") .replaceAll("\\s", ""); // decode to get the binary DER representation byte[] privateKeyDER = Base64.getDecoder().decode(privateKeyPEM); EncryptedPrivateKeyInfo epkInfo = new EncryptedPrivateKeyInfo(privateKeyDER); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName()); PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray()); SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec); Cipher cipher = Cipher.getInstance(epkInfo.getAlgName()); cipher.init(Cipher.DECRYPT_MODE, pbeKey, epkInfo.getAlgParameters()); return epkInfo.getKeySpec(cipher); }
/** * 数据解密,算法(DES) * * @param cryptData * 加密数据 * @param desKey DES密钥 * @return 解密后的数据 */ public static String decrypt(String cryptData, byte[] desKey) { String decryptedData = null; try { // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom(); DESKeySpec deskey = new DESKeySpec(desKey); // 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(deskey); // 解密对象 Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, key, sr); // 把字符串解码为字节数组,并解密 decryptedData = new String(cipher.doFinal(Base64.getDecoder().decode(cryptData))); } catch (Exception e) { // log.error("解密错误,错误信息:", e); throw new RuntimeException("解密错误,错误信息:", e); } return decryptedData; }
/** * DES * @param src * @param password * @return */ public static byte[] decrypt(byte []src, String password) { try { // DES算法要求有一个可信任的随机数源 SecureRandom random = new SecureRandom(); // 创建一个DESKeySpec对象 DESKeySpec desKey = new DESKeySpec(password.getBytes()); // 创建一个密匙工厂 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); // 将DESKeySpec对象转换成SecretKey对象 SecretKey securekey = keyFactory.generateSecret(desKey); // Cipher对象实际完成解密操作 Cipher cipher = Cipher.getInstance("DES"); // 用密匙初始化Cipher对象 cipher.init(Cipher.DECRYPT_MODE, securekey, random); // 真正开始解密操作 return cipher.doFinal(src); } catch (Throwable e) { e.printStackTrace(); } return null; }
/** * DES加密 * * @author : chenssy * @date : 2016年5月20日 下午5:51:37 * * @param data * 待加密字符串 * @param key * 校验位 * @return */ @SuppressWarnings("restriction") protected static String encrypt(String data,String key) { String encryptedData = null; try { // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom(); DESKeySpec deskey = new DESKeySpec(key.getBytes()); // 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(deskey); // 加密对象 Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr); // 加密,并把字节数组编码成字符串 encryptedData = new sun.misc.BASE64Encoder().encode(cipher.doFinal(data.getBytes())); } catch (Exception e) { throw new RuntimeException("加密错误,错误信息:", e); } return encryptedData; }
/** * 解密 * @param src byte[] * @param password String * @return String * @throws Exception */ public static String decrypt(String decodeStr, String password) throws Exception { byte[] str=new BASE64Decoder().decodeBuffer(decodeStr); // DES算法要求有一个可信任的随机数源 SecureRandom random = new SecureRandom(); // 创建一个DESKeySpec对象 DESKeySpec desKey = new DESKeySpec(password.getBytes()); // 创建一个密匙工厂 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); // 将DESKeySpec对象转换成SecretKey对象 SecretKey securekey = keyFactory.generateSecret(desKey); // Cipher对象实际完成解密操作 Cipher cipher = Cipher.getInstance("DES"); // 用密匙初始化Cipher对象 cipher.init(Cipher.DECRYPT_MODE, securekey, random); // 真正开始解密操作 byte[] passByte=cipher.doFinal(str); return new String(passByte); }
/** * @param salt an array of random bytes to use for each (un)obfuscation * @param applicationId application identifier, e.g. the package name * @param deviceId device identifier. Use as many sources as possible to * create this unique identifier. */ public AESObfuscator(byte[] salt, String applicationId, String deviceId) { try { SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM); KeySpec keySpec = new PBEKeySpec((applicationId + deviceId).toCharArray(), salt, 1024, 256); SecretKey tmp = factory.generateSecret(keySpec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); mEncryptor = Cipher.getInstance(CIPHER_ALGORITHM); mEncryptor.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(IV)); mDecryptor = Cipher.getInstance(CIPHER_ALGORITHM); mDecryptor.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(IV)); } catch (GeneralSecurityException e) { // This can't happen on a compatible Android device. throw new RuntimeException("Invalid environment", e); } }
/** * The key is generating by SecretKeyFactory and its value just copying * in the key field of MySecretKey class. So, this is real key derived * using the given algo. */ public MyPBKDF2SecretKey(String passPhrase, String algo, byte[] salt1, int iterationCount, int keySize) throws InvalidKeySpecException, NoSuchAlgorithmException { algorithm = algo; salt = salt1; itereationCount = iterationCount; pass = passPhrase; PBEKeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount, keySize); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algo); SecretKey realKey = keyFactory.generateSecret(spec); keyLength = realKey.getEncoded().length; key = new byte[keyLength]; System.arraycopy(realKey.getEncoded(), 0, key, 0, keyLength); }
public boolean passwordsMatch(Object submittedPlaintext, String encrypted) { ByteSource plaintextBytes = ByteSource.Util.bytes(submittedPlaintext); if (encrypted == null || encrypted.length() == 0) { return plaintextBytes == null || plaintextBytes.isEmpty(); } else { if (plaintextBytes == null || plaintextBytes.isEmpty()) { return false; } } String plaintext = new String(plaintextBytes.getBytes()); String[] tokens = encrypted.split("\\$"); int iterations = Integer.parseInt(tokens[1]); byte[] salt = tokens[2].getBytes(); String hash = tokens[3]; KeySpec spec = new PBEKeySpec(plaintext.toCharArray(), salt, iterations, 256); try { String algorithmName = getAlgorithmFullName(tokens[0]); SecretKeyFactory f = SecretKeyFactory.getInstance(algorithmName); return hash.equals(Base64.encodeToString(f.generateSecret(spec).getEncoded())); } catch (Exception e) { log.error(e.getMessage()); return false; } }
public static PKCS8EncodedKeySpec getEncodedPrivateKeySpec(String key, String password) throws Exception { String privateKeyPEM = key .replace("-----BEGIN ENCRYPTED PRIVATE KEY-----", "") .replace("-----END ENCRYPTED PRIVATE KEY-----", "") .replaceAll("\\s", ""); // decode to get the binary DER representation byte[] privateKeyDER = Base64.getDecoder().decode(privateKeyPEM); EncryptedPrivateKeyInfo epkInfo = new EncryptedPrivateKeyInfo(privateKeyDER); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName()); PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray()); SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec); Cipher cipher = Cipher.getInstance(epkInfo.getAlgName()); cipher.init(Cipher.DECRYPT_MODE, pbeKey, epkInfo.getAlgParameters()); return epkInfo.getKeySpec(cipher); }
private static PKCS8EncodedKeySpec readPrivateKey(File keyFile, Optional<String> keyPassword) throws IOException, GeneralSecurityException { String content = Files.toString(keyFile, US_ASCII); Matcher matcher = KEY_PATTERN.matcher(content); if (!matcher.find()) { throw new KeyStoreException("found no private key: " + keyFile); } byte[] encodedKey = base64Decode(matcher.group(1)); if (!keyPassword.isPresent()) { return new PKCS8EncodedKeySpec(encodedKey); } EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(encodedKey); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName()); SecretKey secretKey = keyFactory.generateSecret(new PBEKeySpec(keyPassword.get().toCharArray())); Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName()); cipher.init(DECRYPT_MODE, secretKey, encryptedPrivateKeyInfo.getAlgParameters()); return encryptedPrivateKeyInfo.getKeySpec(cipher); }
/** * The test case scenario implemented in the method: - create my own secret * Key2 as an instance of a class implements PBEKey - spoil the key (set * iteration count to 0, for example) - try to translate key - * InvalidKeyException is expected. */ public void translateSpoiledKey(byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException { // derive the key SecretKey key1 = getMyOwnSecretKey(salt); // spoil the key ((MyPBKDF2SecretKey) key1).spoil(); // translate key SecretKeyFactory skf = SecretKeyFactory.getInstance(algoForTest); try { skf.translateKey(key1); throw new RuntimeException( "translateSpoiledKey test case failed, should throw" + " InvalidKeyException when spoil the key"); } catch (InvalidKeyException ike) { out.println("Expected exception when spoil the key"); } }
public void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Exception { DESKeySpec dks = new DESKeySpec(key.getBytes()); SecretKeyFactory skf = SecretKeyFactory.getInstance("DES"); SecretKey desKey = skf.generateSecret(dks); Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for // SunJCE if (mode == Cipher.ENCRYPT_MODE) { cipher.init(Cipher.ENCRYPT_MODE, desKey); CipherInputStream cis = new CipherInputStream(is, cipher); doCopy(cis, os); } else if (mode == Cipher.DECRYPT_MODE) { cipher.init(Cipher.DECRYPT_MODE, desKey); CipherOutputStream cos = new CipherOutputStream(os, cipher); doCopy(is, cos); } }
/** * Description 根据键值进行解密 * * @param data * @param key 加密键byte数组 * @return * @throws Exception */ private static byte[] desDecrypt(byte[] key, byte[] data) throws Exception { // 生成一个可信任的随机数源 SecureRandom sr = new SecureRandom(); // 从原始密钥数据创建DESKeySpec对象 DESKeySpec dks = new DESKeySpec(key); // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks); // Cipher对象实际完成解密操作 Cipher cipher = Cipher.getInstance(DES); // 用密钥初始化Cipher对象 cipher.init(Cipher.DECRYPT_MODE, securekey, sr); return cipher.doFinal(data); }
/** * 加密 * * @param src 数据源 * @param key 密钥,长度必须是8的倍数 * @return 返回加密后的数据 * @throws Exception */ public static byte[] encrypt(byte[] src, byte[] key) throws Exception { // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom(); // 从原始密匙数据创建DESKeySpec对象 DESKeySpec dks = new DESKeySpec(key); // 创建一个密匙工厂,然后用它把DESKeySpec转换成 // 一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks); // Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance(DES); // 用密匙初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, securekey, sr); // 现在,获取数据并加密 // 正式执行加密操作 return cipher.doFinal(src); }
/** * DES解密 * * @param src * @param key * @return * @throws Exception */ public static byte[] decrypt(byte[] src, byte[] key) throws Exception { // DES算法要求有一个可信任的随机数源 SecureRandom sr = new SecureRandom(); // 从原始密匙数据创建一个DESKeySpec对象 DESKeySpec dks = new DESKeySpec(key); // 创建一个密匙工厂,然后用它把DESKeySpec对象转换成 // 一个SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks); // Cipher对象实际完成解密操作 Cipher cipher = Cipher.getInstance(DES); // 用密匙初始化Cipher对象 cipher.init(Cipher.DECRYPT_MODE, securekey, sr); // 现在,获取数据并解密 // 正式执行解密操作 return cipher.doFinal(src); }
/** * Initiate the Cipher object for PBKDF2 algorithm using given "mode". * * @param mode Cipher mode: encrypt or decrypt * @return Cipher object for PBKDF2 algorithm * @throws GeneralSecurityException all security exceptions are thrown. */ @Override protected Cipher initCipher(int mode) throws GeneralSecurityException { Provider provider = Security.getProvider("SunJCE"); if (provider == null) { throw new RuntimeException("SunJCE provider does not exist."); } // Generate secret key PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), salt, DEFAULT_ITERATION, PKDF2_DEFAULT_KEY_LEN); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(baseAlgo); SecretKey key = keyFactory.generateSecret(pbeKeySpec); // get Cipher instance Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION, provider); cipher.init(mode, new SecretKeySpec(key.getEncoded(),KEY_ALGORITHM), new IvParameterSpec(iv)); return cipher; }
protected Key getSecretKey(KeyInformation keyInformation) throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException { byte[] keyData = keyInformation.getKeyData(); if(keyData == null) { if(keyInformation.getKeyAlgorithm().equals("DESede")) { // no key data provided, generate key data automatically keyData = generateKeyData(); } else { throw new AlfrescoRuntimeException("Unable to generate secret key: key algorithm is not DESede and no keyData provided"); } } DESedeKeySpec keySpec = new DESedeKeySpec(keyData); SecretKeyFactory kf = SecretKeyFactory.getInstance(keyInformation.getKeyAlgorithm()); SecretKey secretKey = kf.generateSecret(keySpec); return secretKey; }
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException { // TODO This code is demo as the passphrase is hardcoded. SystemInfo info = new SystemInfo(); String salt = info.getHardware().getProcessor().getProcessorID() + info.getOperatingSystem().getFileSystem().getFileStores()[0].getUUID(); String passPhrase = "Rudy"; // PBKDF2WithHmacSHA1 available on Java 7 and Java 8. Must match value used on LocalSecretFactory. // TODO possible usage scenario. using theis local secret, the end user can create the OfflineToken with a Web application (where he needs to authenticate himself // in order to create a correct OfflineToken instance for the user. byte[] secret = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret( new PBEKeySpec(passPhrase.toCharArray(), salt.getBytes(), 1024, 256)).getEncoded(); String secret64 = Base64Codec.encodeToString(secret, true); System.out.println("Local secret value is " + secret64); }
/** * The test case scenario implemented in the method: - derive PBKDF2 key * using the given algorithm; - translate the key - check if the translated * and original keys have the same key value. * * @return true if the test case passed; false - otherwise. * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws InvalidKeyException */ public boolean generateAndTranslateKey() throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException { // derive PBKDF2 key SecretKey key1 = getSecretKeyForPBKDF2(algoToTest); // translate key SecretKeyFactory skf = SecretKeyFactory.getInstance(algoToTest); SecretKey key2 = skf.translateKey(key1); // check if it still the same after translation if (!Arrays.equals(key1.getEncoded(), key2.getEncoded())) { System.err.println("generateAndTranslateKey test case failed: the " + "key1 and key2 values in its primary encoding format are " + "not the same for " + algoToTest + "algorithm."); return false; } return true; }
public String getEncryptedPassword(String password, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException { // PBKDF2 with SHA-1 as the hashing algorithm. Note that the NIST // specifically names SHA-1 as an acceptable hashing algorithm for PBKDF2 String algorithm = "PBKDF2WithHmacSHA1"; // SHA-1 generates 160 bit hashes, so that's what makes sense here int derivedKeyLength = 160; // Pick an iteration count that works for you. The NIST recommends at // least 1,000 iterations: // http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf // iOS 4.x reportedly uses 10,000: // http://blog.crackpassword.com/2010/09/smartphone-forensics-cracking-blackberry-backup-passwords/ int iterations = 20000; char[] pwd = new String(password).toCharArray(); KeySpec spec = new PBEKeySpec(pwd, Base64.getDecoder().decode(salt), iterations, derivedKeyLength); SecretKeyFactory f = SecretKeyFactory.getInstance(algorithm); byte[] bytes = f.generateSecret(spec).getEncoded(); return Base64.getEncoder().encodeToString(bytes); }
/** * The key is generating by SecretKeyFactory and its value just copying in * the key field of MySecretKey class. So, this is real key derived using * the given algorithm. * * @param passPhrase some string intended to be a password * @param algo PBKDF2 algorithm * @param salt slat for PBKDF2 * @param iterationCount iteration count * @param keySize key size in bits * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException */ public MyPBKDF2SecretKey(String passPhrase, String algo, byte[] salt, int iterationCount, int keySize) throws InvalidKeySpecException, NoSuchAlgorithmException { this.algorithm = algo; this.salt = salt; this.itereationCount = iterationCount; this.keySize = keySize; this.pass = passPhrase; PBEKeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), this.salt, iterationCount, this.keySize); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algo); SecretKey realKey = keyFactory.generateSecret(spec); this.keyLength = realKey.getEncoded().length; this.key = new byte[this.keyLength]; System.arraycopy(realKey.getEncoded(), 0, this.key, 0, this.keyLength); }
public static boolean validatePassword( String originalPassword, String storedPassword ) throws NoSuchAlgorithmException, InvalidKeySpecException { String[] parts = storedPassword.split(":"); int iterations = Integer.parseInt(parts[0]); byte[] salt = fromHex(parts[1]); byte[] hash = fromHex(parts[2]); PBEKeySpec spec = new PBEKeySpec(originalPassword.toCharArray(), salt, iterations, hash.length * 8); SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); byte[] testHash = skf.generateSecret(spec).getEncoded(); int diff = hash.length ^ testHash.length; for(int i = 0; i < hash.length && i < testHash.length; i++) { diff |= hash[i] ^ testHash[i]; } return diff == 0; }
/** * Reads the private key from an encrypted PKCS#8 file and returns it as an ECPrivateKey instance. * * @param A PKCS#8 (.key) file containing the private key with value "s" * @return The private key as an ECPrivateKey instance */ public static ECPrivateKey getPrivateKey(String keyFilePath) { Path fileLocation = Paths.get(keyFilePath); byte[] pkcs8ByteArray; try { pkcs8ByteArray = Files.readAllBytes(fileLocation); // The DER encoded private key is password-based encrypted and provided in PKCS#8. So we need to decrypt it first PBEKeySpec pbeKeySpec = new PBEKeySpec(GlobalValues.PASSPHRASE_FOR_CERTIFICATES_AND_KEYS.toString().toCharArray()); EncryptedPrivateKeyInfo encryptedPrivKeyInfo = new EncryptedPrivateKeyInfo(pkcs8ByteArray); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(encryptedPrivKeyInfo.getAlgName()); Key secret = secretKeyFactory.generateSecret(pbeKeySpec); PKCS8EncodedKeySpec pkcs8PrivKeySpec = encryptedPrivKeyInfo.getKeySpec(secret); ECPrivateKey privateKey = (ECPrivateKey) KeyFactory.getInstance("EC").generatePrivate(pkcs8PrivKeySpec); return privateKey; } catch (IOException | InvalidKeySpecException | NoSuchAlgorithmException | InvalidKeyException e) { getLogger().error(e.getClass().getSimpleName() + " occurred while trying to access private key at " + "location '" + keyFilePath + "'"); return null; } }
public static void main(String[] argv) throws Exception { EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo( Base64.getMimeDecoder().decode(PKCS8PrivateKey)); PBEKeySpec pks = new PBEKeySpec(password.toCharArray()); SecretKeyFactory skf = SecretKeyFactory.getInstance(epki.getAlgName()); SecretKey sk = skf.generateSecret(pks); PKCS8EncodedKeySpec keySpec = epki.getKeySpec(sk); // Get the key algorithm and make sure it's what we expect String alg = keySpec.getAlgorithm(); if (!alg.equals(keyAlg)) { throw new Exception("Expected: " + keyAlg + ", Got: " + alg); } System.out.println("Test passed"); }
/** * 3-DES加密 * * @param byte[] * src 要进行3-DES加密的byte[] * @param byte[] * enKey 3-DES加密密钥 * @return byte[] 3-DES加密后的byte[] */ public byte[] Encrypt(byte[] src, byte[] enKey) { byte[] encryptedData = null; try { DESedeKeySpec dks = new DESedeKeySpec(enKey); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); SecretKey key = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance("DESede"); cipher.init(Cipher.ENCRYPT_MODE, key); encryptedData = cipher.doFinal(src); } catch (Exception e) { e.printStackTrace(); } return encryptedData; }
/** * The test case scenario implemented in the method: - create my own secret * Key2 as an instance of a class implements PBEKey - spoil the key (set * iteration count to 0, for example) - try to translate key - * InvalidKeyException is expected. * * @return true if InvalidKeyException occurred; false - otherwise. * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ public boolean translateSpoiledKey() throws NoSuchAlgorithmException, InvalidKeySpecException { // derive the key SecretKey key1 = getMyOwnSecretKey(); // spoil the key ((MyPBKDF2SecretKey) key1).spoil(); // translate key SecretKeyFactory skf = SecretKeyFactory.getInstance(algoToTest); try { SecretKey key2 = skf.translateKey(key1); } catch (InvalidKeyException ike) { // this is expected return true; } return false; }
/** * This method will hash the password and salt combination. Be careful, this method will erase the password after hashed it. * You must be sure that you do not need it after using this method. * * @param password the password who needs to be hashed * @param salt some list of <code>byte</code> which will be included in the password * @return a hash of the password and salting combination. */ public static byte[] hash(char[] password, byte[] salt) { final PBEKeySpec spec = new PBEKeySpec(password, salt, SecurityUtils.ITERATIONS, SecurityUtils.KEY_LENGTH); try { SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SecurityUtils.ALGORITHM); SecretKey key = secretKeyFactory.generateSecret(spec); return key.getEncoded(); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { LOGGER.debug(e.getMessage(), e); throw new SecurityException(e); } finally { // erase the password in the char array in order to not retrieve it in the java memory spec.clearPassword(); } }
/** * 转换秘钥 * * @param key * @return * @throws Exception */ private static Key toKey(byte[] key) throws Exception { DESKeySpec dks = new DESKeySpec(key); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(Algorithm.DES.getType()); SecretKey secretKey = keyFactory.generateSecret(dks); return secretKey; }
public PBECipherWrapper( Provider p, String algo, String passwd, PrintStream out) throws Exception { super(algo, SecretKeyFactory.getInstance( new StringTokenizer(algo, "/").nextToken(), p).generateSecret( new PBEKeySpec(passwd.toCharArray())), Cipher.getInstance(algo, p), out); int SALT_SIZE = 8; aps = new PBEParameterSpec(generateSalt(SALT_SIZE), ITERATION_COUNT); }
private String generateEncryptString(String key, String data) throws Exception { EncryptInner locala = new EncryptInner(this, key, data, null); Cipher localCipher = Cipher.getInstance("DES/ECB/NoPadding"); SecretKeyFactory localSecretKeyFactory = SecretKeyFactory .getInstance("DES"); localCipher.init(1, localSecretKeyFactory .generateSecret(new DESKeySpec(EncryptInner.getKeyHexIntByteArray(locala)))); return convertByteArray2HexString( localCipher.doFinal(EncryptInner.getDataHexIntByteArray(locala))).toUpperCase(); }
private static Key getKey(String password) { try { // ��Կ���� PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray()); // ��Կ���� SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM); // ������Կ SecretKey secretKey = keyFactory.generateSecret(keySpec); return secretKey; } catch (Exception e) { e.printStackTrace(); return null; } }
protected String decrypt(String value){ try { final byte[] bytes = value!=null ? Base64Support.decode(value,Base64Support.DEFAULT) : new byte[0]; SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT)); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec( Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID).getBytes(UTF8), 20)); return new String(pbeCipher.doFinal(bytes),UTF8); } catch( Exception e) { Log.e(this.getClass().getName(), "Warning, could not decrypt the value. It may be stored in plaintext. "+e.getMessage()); value = "error"; return value; } }
/** * Get SecretKey for the given PBKDF2 algorithm. * * @param thePBKDF2Algorithm - PBKDF2 algorithm * @return SecretKey according to thePBKDF2Algorithm * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ protected SecretKey getSecretKey(String thePBKDF2Algorithm) throws NoSuchAlgorithmException, InvalidKeySpecException { // Prepare salt byte[] salt = new byte[64]; // PKCS #5 v2.1 recommendation new SecureRandom().nextBytes(salt); // Generate secret key PBEKeySpec pbeKeySpec = new PBEKeySpec( "A #pwd# implied to be hidden!".toCharArray(), salt, 1000, 128); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(thePBKDF2Algorithm); return keyFactory.generateSecret(pbeKeySpec); }
private SecretKey getPBEKey(char[] password) throws IOException { SecretKey skey = null; try { PBEKeySpec keySpec = new PBEKeySpec(password); SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE"); skey = skFac.generateSecret(keySpec); keySpec.clearPassword(); } catch (Exception e) { throw new IOException("getSecretKey failed: " + e.getMessage(), e); } return skey; }
protected String decrypt(String value){ try { final byte[] bytes = value!=null ? Base64.decode(value, Base64.DEFAULT) : new byte[0]; SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT)); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(Secure.getString(context.getContentResolver(), Secure.ANDROID_ID).getBytes(UTF8), 20)); return new String(pbeCipher.doFinal(bytes),UTF8); } catch( Exception e) { Log.e(this.getClass().getName(), "Warning, could not decrypt the value. It may be stored in plaintext. "+e.getMessage()); return value; } }