/** * Generate a new MWK * * @param desBytes byte array of the DES key (24 bytes) * @return Hex String of the new encrypted MWK ready for transmission to ValueLink */ public byte[] generateMwk(byte[] desBytes) { if (debug) { Debug.logInfo( "DES Key : " + StringUtil.toHexString(desBytes) + " / " + desBytes.length, module); } SecretKeyFactory skf1 = null; SecretKey mwk = null; try { skf1 = SecretKeyFactory.getInstance("DESede"); } catch (NoSuchAlgorithmException e) { Debug.logError(e, module); } DESedeKeySpec desedeSpec2 = null; try { desedeSpec2 = new DESedeKeySpec(desBytes); } catch (InvalidKeyException e) { Debug.logError(e, module); } if (skf1 != null && desedeSpec2 != null) { try { mwk = skf1.generateSecret(desedeSpec2); } catch (InvalidKeySpecException e) { Debug.logError(e, module); } } if (mwk != null) { return generateMwk(mwk); } else { return null; } }
/** * 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); }
/** * 加密(使用DES算法) * * @param txt 需要加密的文本 * @param key 密钥 * @return 成功加密的文本 * @throws InvalidKeySpecException * @throws InvalidKeyException * @throws NoSuchPaddingException * @throws IllegalBlockSizeException * @throws BadPaddingException */ private static String enCrypto(String txt, String key) throws InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { StringBuffer sb = new StringBuffer(); DESKeySpec desKeySpec = new DESKeySpec(key.getBytes()); SecretKeyFactory skeyFactory = null; Cipher cipher = null; try { skeyFactory = SecretKeyFactory.getInstance("DES"); cipher = Cipher.getInstance("DES"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } SecretKey deskey = skeyFactory != null ? skeyFactory.generateSecret(desKeySpec) : null; if (cipher != null) { cipher.init(Cipher.ENCRYPT_MODE, deskey); } byte[] cipherText = cipher != null ? cipher.doFinal(txt.getBytes()) : new byte[0]; for (int n = 0; n < cipherText.length; n++) { String stmp = (java.lang.Integer.toHexString(cipherText[n] & 0XFF)); if (stmp.length() == 1) { sb.append("0" + stmp); } else { sb.append(stmp); } } return sb.toString().toUpperCase(); }
/** * Encode password using DES encryption with given challenge. * * @param challenge a random set of bytes. * @param password a password * @return DES hash of password and challenge */ public ByteBuffer encodePassword(ByteBuffer challenge, String password) { if (challenge.length != 16) throw new RuntimeException("Challenge must be exactly 16 bytes long."); // VNC password consist of up to eight ASCII characters. byte[] key = {0, 0, 0, 0, 0, 0, 0, 0}; // Padding byte[] passwordAsciiBytes = password.getBytes(RfbConstants.US_ASCII_CHARSET); System.arraycopy(passwordAsciiBytes, 0, key, 0, Math.min(password.length(), 8)); // Flip bytes (reverse bits) in key for (int i = 0; i < key.length; i++) { key[i] = flipByte(key[i]); } try { KeySpec desKeySpec = new DESKeySpec(key); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec); Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); ByteBuffer buf = new ByteBuffer(cipher.doFinal(challenge.data, challenge.offset, challenge.length)); return buf; } catch (Exception e) { throw new RuntimeException("Cannot encode password.", e); } }
public static String encrypt(String originalText, String password) { String enc = ""; try { // cara penggunaan JCE u/ melakukan enkripsi berdasarkan metode enkripsi PBE, yg dipilih // (tidak // mesti PBEWithMD5AndDES PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(METHOD); SecretKey secretKey = keyFactory.generateSecret(keySpec); PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterationCount); cipher = Cipher.getInstance(METHOD); cipher.init(Cipher.ENCRYPT_MODE, secretKey, parameterSpec); outputArray = originalText.getBytes(encoding); cryptedText = new ByteArrayOutputStream(); CipherOutputStream out = new CipherOutputStream(cryptedText, cipher); out.write(outputArray); out.flush(); out.close(); return cryptedText.toString(); } catch (IOException ex) { Logger.getLogger(EncDec.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidKeyException ex) { Logger.getLogger(EncDec.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidAlgorithmParameterException ex) { Logger.getLogger(EncDec.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchPaddingException ex) { Logger.getLogger(EncDec.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidKeySpecException ex) { Logger.getLogger(EncDec.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(EncDec.class.getName()).log(Level.SEVERE, null, ex); } return "error"; }
/** * Get a hashed password ready for storage or comparison. * * @param password The password to hash * @param NaCl The salt to use in the hashing process * @return A string array with the password in the 0 position and the salt in the 1 position */ private static String[] getSecurePassword(String password, String NaCl) { int iterations = 1000; char[] chars = password.toCharArray(); System.out.println("-----------------------------------------"); System.out.println(NaCl); byte[] salt = NaCl.getBytes(); PBEKeySpec spec = new PBEKeySpec(chars, salt, iterations, 64 * 8); SecretKeyFactory skf; byte[] hash = null; try { skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512"); hash = skf.generateSecret(spec).getEncoded(); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { e.printStackTrace(); } String[] ret = new String[0]; try { ret = new String[] {(new String(hash, "UTF-8")), (new String(salt, "UTF-8"))}; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return ret; }
/** * Decrypt an encrypted PKCS 8 format private key. * * <p>Based on ghstark's post on Aug 6, 2006 at * http://forums.sun.com/thread.jspa?threadID=758133&messageID=4330949 * * @param encryptedPrivateKey The raw data of the private key * @param keyFile The file containing the private key */ private KeySpec decryptPrivateKey(byte[] encryptedPrivateKey, String keyPassword) throws GeneralSecurityException { EncryptedPrivateKeyInfo epkInfo; try { epkInfo = new EncryptedPrivateKeyInfo(encryptedPrivateKey); } catch (IOException ex) { // Probably not an encrypted key. return null; } char[] keyPasswd = keyPassword.toCharArray(); SecretKeyFactory skFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName()); Key key = skFactory.generateSecret(new PBEKeySpec(keyPasswd)); Cipher cipher = Cipher.getInstance(epkInfo.getAlgName()); cipher.init(Cipher.DECRYPT_MODE, key, epkInfo.getAlgParameters()); try { return epkInfo.getKeySpec(cipher); } catch (InvalidKeySpecException ex) { getLogger().error("signapk: Password for private key may be bad."); throw ex; } }
private void testCipherNameWithWrap(String name, String simpleName) throws Exception { KeyGenerator kg = KeyGenerator.getInstance("AES"); kg.init(new SecureRandom()); SecretKey key = kg.generateKey(); byte[] salt = { (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c, (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 }; char[] password = {'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20); PBEKeySpec pbeKeySpec = new PBEKeySpec(password); SecretKeyFactory keyFac = SecretKeyFactory.getInstance(name); SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); Cipher pbeEncryptCipher = Cipher.getInstance(name, "SC"); pbeEncryptCipher.init(Cipher.WRAP_MODE, pbeKey, pbeParamSpec); byte[] symKeyBytes = pbeEncryptCipher.wrap(key); Cipher simpleCipher = Cipher.getInstance(simpleName, "SC"); simpleCipher.init(Cipher.UNWRAP_MODE, pbeKey, pbeParamSpec); SecretKey unwrappedKey = (SecretKey) simpleCipher.unwrap(symKeyBytes, "AES", Cipher.SECRET_KEY); if (!Arrays.areEqual(unwrappedKey.getEncoded(), key.getEncoded())) { fail("key mismatch on unwrapping"); } }
/** * 转换密钥<br> * * @param password * @return * @throws Exception */ private static Key toKey(String password) throws Exception { PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM); SecretKey secretKey = keyFactory.generateSecret(keySpec); return secretKey; }
private static int generateIterationCount(String passphrase, byte[] salt) { int TARGET_ITERATION_TIME = 50; // ms int MINIMUM_ITERATION_COUNT = 100; // default for low-end devices int BENCHMARK_ITERATION_COUNT = 10000; // baseline starting iteration count try { PBEKeySpec keyspec = new PBEKeySpec(passphrase.toCharArray(), salt, BENCHMARK_ITERATION_COUNT); SecretKeyFactory skf = SecretKeyFactory.getInstance("PBEWITHSHA1AND128BITAES-CBC-BC"); long startTime = System.currentTimeMillis(); skf.generateSecret(keyspec); long finishTime = System.currentTimeMillis(); int scaledIterationTarget = (int) (((double) BENCHMARK_ITERATION_COUNT / (double) (finishTime - startTime)) * TARGET_ITERATION_TIME); if (scaledIterationTarget < MINIMUM_ITERATION_COUNT) return MINIMUM_ITERATION_COUNT; else return scaledIterationTarget; } catch (NoSuchAlgorithmException e) { Log.w("MasterSecretUtil", e); return MINIMUM_ITERATION_COUNT; } catch (InvalidKeySpecException e) { Log.w("MasterSecretUtil", e); return MINIMUM_ITERATION_COUNT; } }
EncryptStrings(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); System.out.println(ecipher.doFinal()); } catch (java.security.InvalidAlgorithmParameterException e) { } catch (java.security.spec.InvalidKeySpecException e) { } catch (javax.crypto.NoSuchPaddingException e) { } catch (java.security.NoSuchAlgorithmException e) { } catch (java.security.InvalidKeyException e) { } catch (IllegalBlockSizeException ex) { Logger.getLogger(EncryptStrings.class.getName()).log(Level.SEVERE, null, ex); } catch (BadPaddingException ex) { Logger.getLogger(EncryptStrings.class.getName()).log(Level.SEVERE, null, ex); } }
public static String encrypt(String property) throws GeneralSecurityException { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(getPassword())); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20)); return ENCODING_MODE_1 + base64Encode(pbeCipher.doFinal(property.getBytes())); }
/** * @param p * @throws java.security.InvalidKeyException * @throws java.io.UnsupportedEncodingException * @throws java.security.spec.InvalidKeySpecException * @throws java.security.NoSuchAlgorithmException * @throws javax.crypto.NoSuchPaddingException */ public void setPassword(String p) throws FacesException { byte[] s = { (byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32, (byte) 0x56, (byte) 0x34, (byte) 0xE3, (byte) 0x03 }; try { KeySpec keySpec = new DESKeySpec(p.getBytes("UTF8")); SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec); e = Cipher.getInstance(key.getAlgorithm()); d = Cipher.getInstance(key.getAlgorithm()); // Prepare the parameters to the cipthers // AlgorithmParameterSpec paramSpec = new IvParameterSpec(s); e.init(Cipher.ENCRYPT_MODE, key); d.init(Cipher.DECRYPT_MODE, key); } catch (Exception e) { throw new FacesException("Error set encryption key", e); } }
protected SecretKey getDesEdeKey(byte[] rawKey) { SecretKeyFactory skf = null; try { skf = SecretKeyFactory.getInstance("DESede"); } catch (NoSuchAlgorithmException e) { // should never happen since DESede is a standard algorithm Debug.logError(e, module); return null; } // load the raw key if (rawKey.length > 0) { DESedeKeySpec desedeSpec1 = null; try { desedeSpec1 = new DESedeKeySpec(rawKey); } catch (InvalidKeyException e) { Debug.logError(e, "Not a valid DESede key", module); return null; } // create the SecretKey Object SecretKey key = null; try { key = skf.generateSecret(desedeSpec1); } catch (InvalidKeySpecException e) { Debug.logError(e, module); } return key; } else { throw new RuntimeException("No valid DESede key available"); } }
/** * Constructor specifying scheme and key * * @param encryptionScheme Encryption scheme to use * @param encryptionKey Encryption key to use * @throws EncryptionException */ public StringEncrypter(final String encryptionScheme, final String encryptionKey) throws EncryptionException { if (encryptionKey == null) { throw new IllegalArgumentException("encryption key was null"); } if (encryptionKey.trim().length() < 24) { throw new IllegalArgumentException("encryption key was less than 24 characters"); } try { final byte[] keyAsBytes = encryptionKey.getBytes(StringEncrypter.UNICODE_FORMAT); if (encryptionScheme.equalsIgnoreCase(StringEncrypter.DESEDE_ENCRYPTION_SCHEME)) { keySpec = new DESedeKeySpec(keyAsBytes); } else if (encryptionScheme.equalsIgnoreCase(StringEncrypter.DES_ENCRYPTION_SCHEME)) { keySpec = new DESKeySpec(keyAsBytes); } else { throw new IllegalArgumentException("Encryption scheme not supported: " + encryptionScheme); } keyFactory = SecretKeyFactory.getInstance(encryptionScheme); cipher = Cipher.getInstance(encryptionScheme); } catch (final InvalidKeyException e) { throw new EncryptionException(e); } catch (final UnsupportedEncodingException e) { throw new EncryptionException(e); } catch (final NoSuchAlgorithmException e) { throw new EncryptionException(e); } catch (final NoSuchPaddingException e) { throw new EncryptionException(e); } }
public static void main(String args[]) throws Exception { byte key[] = password.getBytes(); DESKeySpec desKeySpec = new DESKeySpec(key); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); // Create cipher mode Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); desCipher.init(Cipher.DECRYPT_MODE, secretKey); // Create stream FileInputStream fis = new FileInputStream("out.txt"); BufferedInputStream bis = new BufferedInputStream(fis); CipherInputStream cis = new CipherInputStream(bis, desCipher); ObjectInputStream ois = new ObjectInputStream(cis); // Read String plaintext2 = ois.readUTF(); ois.close(); // Compare System.out.println(plaintext); System.out.println(plaintext2); System.out.println("Identical? " + (plaintext.equals(plaintext2))); }
public static final void main(String[] args) throws Exception { // Generate a PBE key SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE"); SecretKey skey = skFac.generateSecret(new PBEKeySpec("test123".toCharArray())); // Initialize the PBE cipher Cipher cipher = Cipher.getInstance(ALGO); cipher.init(Cipher.ENCRYPT_MODE, skey); // Permit access to the Cipher.spi field (a CipherSpi object) Field spi = Cipher.class.getDeclaredField("spi"); spi.setAccessible(true); Object value = spi.get(cipher); // Permit access to the CipherSpi.engineGetKeySize method Method engineGetKeySize = PKCS12PBECipherCore$PBEWithSHA1AndDESede.class.getDeclaredMethod( "engineGetKeySize", Key.class); engineGetKeySize.setAccessible(true); // Check the key size int keySize = (int) engineGetKeySize.invoke(value, skey); if (keySize == KEYSIZE) { System.out.println(ALGO + ".engineGetKeySize returns " + keySize + " bits, as expected"); System.out.println("OK"); } else { throw new Exception("ERROR: " + ALGO + " key size is incorrect"); } }
public static String encode(String input) { if (input == null) { throw new IllegalArgumentException(); } try { KeySpec keySpec = new PBEKeySpec(null, SALT, ITERATION_COUNT); AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT, ITERATION_COUNT); SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec); Cipher ecipher = Cipher.getInstance(key.getAlgorithm()); ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); byte[] enc = ecipher.doFinal(input.getBytes()); String res = new String(Base64.encodeBase64(enc)); // escapes for url res = res.replace('+', '-').replace('/', '_').replace("%", "%25").replace("\n", "%0A"); return res; } catch (Exception e) { } return ""; }
public Key getDesEncryptionKey() throws PropertyManagerException { try { // get the key string String keyStr = getPropertyObject(DES_ENCRYPTION_KEY).getValue(); // create a DES key spec DESKeySpec ks = new DESKeySpec(new sun.misc.BASE64Decoder().decodeBuffer(keyStr)); // generate the key from the DES key spec return SecretKeyFactory.getInstance(DESPasswordEncoder.PASSWORD_ENCRYPTION_ALGORITHM) .generateSecret(ks); } catch (NoSuchAlgorithmException e) { throw new PropertyManagerException(e.getMessage(), e); } catch (IOException e) { throw new PropertyManagerException(e.getMessage(), e); } catch (ObjectNotFoundException e) { throw new PropertyManagerException(e.getMessage(), e); } catch (InvalidKeyException e) { throw new PropertyManagerException(e.getMessage(), e); } catch (InvalidKeySpecException e) { throw new PropertyManagerException(e.getMessage(), e); } }
public static String decode(String token) { if (token == null) { return null; } try { String input = token.replace("%0A", "\n").replace("%25", "%").replace('_', '/').replace('-', '+'); byte[] dec = Base64.decodeBase64(input.getBytes()); KeySpec keySpec = new PBEKeySpec(null, SALT, ITERATION_COUNT); AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT, ITERATION_COUNT); SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec); Cipher dcipher = Cipher.getInstance(key.getAlgorithm()); dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec); byte[] decoded = dcipher.doFinal(dec); String result = new String(decoded); return result; } catch (Exception e) { // use logger in production code e.printStackTrace(); } return null; }
private static byte[] encryptPassword(byte[] password, byte[] salt) { try { byte[] encryptedPassword = 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.ENCRYPT_MODE, secretKey, pbeParameterSpec); encryptedPassword = cipher.doFinal(password); return encryptedPassword; } 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; }
/** * @param s * @return * @throws GeneralSecurityException * @throws UnsupportedEncodingException */ public static String decrypt(final String s) throws GeneralSecurityException, UnsupportedEncodingException { String decrypted = null; try { if (s != null) { final SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); final SecretKey secretKey = secretKeyFactory.generateSecret(new PBEKeySpec(secret.toCharArray())); final Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES"); cipher.init(Cipher.DECRYPT_MODE, secretKey, new PBEParameterSpec(SALT, 20)); final byte[] stringBytes = s.getBytes("UTF-8"); final byte[] decodedBytes = Base64.decode(stringBytes, Base64.DEFAULT); final byte[] decryptedBytes = cipher.doFinal(decodedBytes); decrypted = new String(decryptedBytes, "UTF-8"); } } catch (GeneralSecurityException x) { throw x; } catch (UnsupportedEncodingException x) { throw x; } catch (Exception x) { DBG.m(x); } return decrypted; }
private DESedeEncryptor() { try { // 检测是否有 TripleDES 加密的供应程序 // 如无,明确地安装SunJCE 供应程序 try { Cipher.getInstance(DESEDE); } catch (Exception e) { logger.error("Installling SunJCE provider."); Provider sunjce = new com.sun.crypto.provider.SunJCE(); Security.addProvider(sunjce); } // 得到 DESSede keys keyFactory = SecretKeyFactory.getInstance(DESEDE); // 创建一个 DESede 密码 encryptCipher = Cipher.getInstance(DESEDE); decryptCipher = Cipher.getInstance(DESEDE); // 为 CBC 模式创建一个用于初始化的 vector 对象 // IvParameters = new IvParameterSpec(new byte[] { 12, 34, 56, // 78, 90, // 87, 65, 43 }); } catch (Exception e) { // 记录加密或解密操作错误 logger.error("It's not support DESede encrypt arithmetic in this system!", e); } }
/** * Loads the PBE secret key. * * @throws Exception if an error ocurrs when loading the PBE key. */ private void loadPBESecretKey() throws Exception { // Create the PBE secret key cipherSpec = new PBEParameterSpec(salt, iterationCount); PBEKeySpec keySpec = new PBEKeySpec(keyStorePassword); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEwithMD5andDES"); cipherKey = factory.generateSecret(keySpec); }
public static byte[] decrypt(PrivateKey privKey, Message message) throws CryptoException { try { Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); rsaCipher.init(Cipher.DECRYPT_MODE, privKey); byte[] secretKeyBytes = rsaCipher.doFinal(message.sessionKey); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("AES"); KeySpec ks = new SecretKeySpec(secretKeyBytes, "AES"); SecretKey secretKey = keyFactory.generateSecret(ks); Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); aesCipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(message.iv)); byte[] messageBytes = aesCipher.doFinal(message.ciphertext); return messageBytes; } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | InvalidKeySpecException | InvalidAlgorithmParameterException e) { throw new CryptoException(e); } }
/** * Method TDESECB. * * @param plaintext byte[] * @param key byte[] * @param opmode int * @return byte[] */ public static byte[] TDESECB(byte[] plaintext, byte[] key, int opmode) { byte[] ciphertext = null; try { // 2KTDEA key is encountered, expand to 192 bit byte[] _key; if (key.length == 16) { if (debug) { System.out.println("Expanding from 128 to 192"); } byte[] ekey = new byte[24]; System.arraycopy(key, 0, ekey, 0, key.length); System.arraycopy(key, 0, ekey, key.length, key.length / 2); _key = ekey; } else { _key = key; } if (debug) { System.out.println("Key: " + DataUtil.byteArrayToString(_key)); } DESedeKeySpec ks = new DESedeKeySpec(_key); SecretKeyFactory kf = SecretKeyFactory.getInstance("DESede"); SecretKey sk = kf.generateSecret(ks); Cipher c = Cipher.getInstance("DESede/ECB/NoPadding"); c.init(opmode, sk); ciphertext = c.doFinal(plaintext); } catch (Throwable e) { e.printStackTrace(); } return ciphertext; }
private static void bcDES() throws Exception { Security.addProvider(new BouncyCastleProvider()); // Key convert DESKeySpec desKeySpec = new DESKeySpec(bytesKey); SecretKeyFactory factory = SecretKeyFactory.getInstance("DES", "BC"); SecretKey desKey = factory.generateSecret(desKeySpec); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, desKey); System.out.println("BC" + cipher.getProvider()); byte[] result = cipher.doFinal("ABC".getBytes()); String hexResult = Hex.encodeHexString(result); System.out.println(hexResult); cipher.init(Cipher.DECRYPT_MODE, desKey); result = cipher.doFinal( Hex.decodeHex(hexResult.toCharArray()) // result ); System.out.println(new String(result)); }
/** * Defautl constructor for creating a DES encrypt/decryption mechanism. * * @param passPhrase */ private claves(String passPhrase) { try { // Create the key KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), SALT, iterationCount); SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec); enryptCipher = Cipher.getInstance(key.getAlgorithm()); decriptCipher = Cipher.getInstance(key.getAlgorithm()); // Prepare the parameter to the ciphers AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT, iterationCount); // Create the ciphers enryptCipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); decriptCipher.init(Cipher.DECRYPT_MODE, key, paramSpec); } catch (java.security.InvalidAlgorithmParameterException e) { encrypter = null; } catch (java.security.spec.InvalidKeySpecException e) { encrypter = null; } catch (javax.crypto.NoSuchPaddingException e) { encrypter = null; } catch (java.security.NoSuchAlgorithmException e) { encrypter = null; } catch (java.security.InvalidKeyException e) { encrypter = null; } }
// Creates a PBKDF2 hash of the password string using the random salted // provided private byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes) throws NoSuchAlgorithmException, InvalidKeySpecException { PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8); SecretKeyFactory skf = SecretKeyFactory.getInstance(ReadProperties.getProperty("pbkdf2_algo")); return skf.generateSecret(spec).getEncoded(); }
public static String decryptIt(String value) { try { DESKeySpec keySpec = new DESKeySpec(cryptoPass.getBytes("UTF8")); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(keySpec); byte[] encrypedPwdBytes = Base64.decode(value, Base64.DEFAULT); // cipher is not thread safe Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, key); byte[] decrypedValueBytes = (cipher.doFinal(encrypedPwdBytes)); String decrypedValue = new String(decrypedValueBytes); Log.d(TAG, "Decrypted: " + value + " -> " + decrypedValue); return decrypedValue; } catch (InvalidKeyException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } return value; }