How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?
我想加密一个字符串,然后把它放在一个文件中。还想在我想要的时候解密它。我不需要非常强大的安全保障。我只想让别人更难获得我的数据。
我试过几种方法。这是这些。
MD5加密:
如何在Android中散列字符串?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public static final String md5(final String toEncrypt) { try { final MessageDigest digest = MessageDigest.getInstance("md5"); digest.update(toEncrypt.getBytes()); final byte[] bytes = digest.digest(); final StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { sb.append(String.format("%02X", bytes[i])); } return sb.toString().toLowerCase(); } catch (Exception exc) { return""; // Impossibru! } } |
我尝试了这个函数,并且能够加密一个字符串,但是我不能从中解密数据。所以这不是解决办法。
DES加密:
用Java加密和解密字符串
这里的密码是自动生成的。始终使用相同的密码吗?那我的保安呢?所以这也不是我的解决方案。
AES加密:
如何用另一个字符串作为密码加密/解密字符串?
我也从这个链接中尝试了AES。这里的键也是自动生成的?
还有别的办法吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | package com.example; import java.security.Key; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class StrongAES { public void run() { try { String text ="Hello World"; String key ="Bar12345Bar12345"; // 128 bit key // Create key and cipher Key aesKey = new SecretKeySpec(key.getBytes(),"AES"); Cipher cipher = Cipher.getInstance("AES"); // encrypt the text cipher.init(Cipher.ENCRYPT_MODE, aesKey); byte[] encrypted = cipher.doFinal(text.getBytes()); System.err.println(new String(encrypted)); // decrypt the text cipher.init(Cipher.DECRYPT_MODE, aesKey); String decrypted = new String(cipher.doFinal(encrypted)); System.err.println(decrypted); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) { StrongAES app = new StrongAES(); app.run(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | package com.ezeon.util.gen; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import javax.crypto.*; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEParameterSpec; /*** Encryption and Decryption of String data; PBE(Password Based Encryption and Decryption) * @author Vikram */ public class CryptoUtil { Cipher ecipher; Cipher dcipher; // 8-byte Salt byte[] salt={ (byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32, (byte) 0x56, (byte) 0x35, (byte) 0xE3, (byte) 0x03 }; // Iteration count int iterationCount = 19; public CryptoUtil() { } /** * * @param secretKey Key used to encrypt data * @param plainText Text input to be encrypted * @return Returns encrypted text * @throws java.security.NoSuchAlgorithmException * @throws java.security.spec.InvalidKeySpecException * @throws javax.crypto.NoSuchPaddingException * @throws java.security.InvalidKeyException * @throws java.security.InvalidAlgorithmParameterException * @throws java.io.UnsupportedEncodingException * @throws javax.crypto.IllegalBlockSizeException * @throws javax.crypto.BadPaddingException * */ public String encrypt(String secretKey, String plainText) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException { //Key generation for enc and desc KeySpec keySpec = new PBEKeySpec(secretKey.toCharArray(), salt, iterationCount); SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec); // Prepare the parameter to the ciphers AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount); //Enc process ecipher = Cipher.getInstance(key.getAlgorithm()); ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); String charSet ="UTF-8"; byte[] in = plainText.getBytes(charSet); byte[] out = ecipher.doFinal(in); String encStr = new String(Base64.getEncoder().encode(out)); return encStr; } /** * @param secretKey Key used to decrypt data * @param encryptedText encrypted text input to decrypt * @return Returns plain text after decryption * @throws java.security.NoSuchAlgorithmException * @throws java.security.spec.InvalidKeySpecException * @throws javax.crypto.NoSuchPaddingException * @throws java.security.InvalidKeyException * @throws java.security.InvalidAlgorithmParameterException * @throws java.io.UnsupportedEncodingException * @throws javax.crypto.IllegalBlockSizeException * @throws javax.crypto.BadPaddingException */ public String decrypt(String secretKey, String encryptedText) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, IOException { //Key generation for enc and desc KeySpec keySpec = new PBEKeySpec(secretKey.toCharArray(), salt, iterationCount); SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec); // Prepare the parameter to the ciphers AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount); //Decryption process; same key will be used for decr dcipher = Cipher.getInstance(key.getAlgorithm()); dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec); byte[] enc = Base64.getDecoder().decode(encryptedText); byte[] utf8 = dcipher.doFinal(enc); String charSet ="UTF-8"; String plainStr = new String(utf8, charSet); return plainStr; } public static void main(String[] args) throws Exception { CryptoUtil cryptoUtil=new CryptoUtil(); String key="ezeon8547"; String plain="This is an important message"; String enc=cryptoUtil.encrypt(key, plain); System.out.println("Original text:"+plain); System.out.println("Encrypted text:"+enc); String plainAfter=cryptoUtil.decrypt(key, enc); System.out.println("Original text after decryption:"+plainAfter); } } |
vignesh好的答案,谢谢!
我只是想说,如果你想添加"字符串加密的字节数组的店,然后检索和解密它,它经常被obfuscation数据库值的方法:你可以使用这个)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | import java.security.Key; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class StrongAES { public void run() { try { String text ="Hello World"; String key ="Bar12345Bar12345"; // 128 bit key // Create key and cipher Key aesKey = new SecretKeySpec(key.getBytes(),"AES"); Cipher cipher = Cipher.getInstance("AES"); // encrypt the text cipher.init(Cipher.ENCRYPT_MODE, aesKey); byte[] encrypted = cipher.doFinal(text.getBytes()); StringBuilder sb = new StringBuilder(); for (byte b: encrypted) { sb.append((char)b); } // the encrypted String String enc = sb.toString(); System.out.println("encrypted:" + enc); // now convert the string to byte array // for decryption byte[] bb = new byte[enc.length()]; for (int i=0; i<enc.length(); i++) { bb[i] = (byte) enc.charAt(i); } // decrypt the text cipher.init(Cipher.DECRYPT_MODE, aesKey); String decrypted = new String(cipher.doFinal(bb)); System.err.println("decrypted:" + decrypted); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) { StrongAES app = new StrongAES(); app.run(); } } |
该代码标记的解决方案没有为我工作。这是我的解决方案。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | /* * http://www.java2s.com/Code/Java/Security/EncryptingaStringwithDES.htm * https://stackoverflow.com/questions/23561104/how-to-encrypt-and-decrypt-string-with-my-passphrase-in-java-pc-not-mobile-plat */ package encryptiondemo; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * * @author zchumager */ public class EncryptionDemo { Cipher ecipher; Cipher dcipher; EncryptionDemo(SecretKey key) throws Exception { ecipher = Cipher.getInstance("AES"); dcipher = Cipher.getInstance("AES"); ecipher.init(Cipher.ENCRYPT_MODE, key); dcipher.init(Cipher.DECRYPT_MODE, key); } public String encrypt(String str) throws Exception { // Encode the string into bytes using utf-8 byte[] utf8 = str.getBytes("UTF8"); // Encrypt byte[] enc = ecipher.doFinal(utf8); // Encode bytes to base64 to get a string return new sun.misc.BASE64Encoder().encode(enc); } public String decrypt(String str) throws Exception { // Decode base64 to get bytes byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str); byte[] utf8 = dcipher.doFinal(dec); // Decode using utf-8 return new String(utf8,"UTF8"); } public static void main(String args []) throws Exception { String data ="Don't tell anybody!"; String k ="Bar12345Bar12345"; //SecretKey key = KeyGenerator.getInstance("AES").generateKey(); SecretKey key = new SecretKeySpec(k.getBytes(),"AES"); EncryptionDemo encrypter = new EncryptionDemo(key); System.out.println("Original String:" + data); String encrypted = encrypter.encrypt(data); System.out.println("Encrypted String:" + encrypted); String decrypted = encrypter.decrypt(encrypted); System.out.println("Decrypted String:" + decrypted); } } |
加密:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public static String encrypt(String strClearText,String strKey) throws Exception{ String strData=""; try { SecretKeySpec skeyspec=new SecretKeySpec(strKey.getBytes(),"Blowfish"); Cipher cipher=Cipher.getInstance("Blowfish"); cipher.init(Cipher.ENCRYPT_MODE, skeyspec); byte[] encrypted=cipher.doFinal(strClearText.getBytes()); strData=new String(encrypted); } catch (Exception e) { e.printStackTrace(); throw new Exception(e); } return strData; } |
解密:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public static String decrypt(String strEncrypted,String strKey) throws Exception{ String strData=""; try { SecretKeySpec skeyspec=new SecretKeySpec(strKey.getBytes(),"Blowfish"); Cipher cipher=Cipher.getInstance("Blowfish"); cipher.init(Cipher.DECRYPT_MODE, skeyspec); byte[] decrypted=cipher.doFinal(strEncrypted.getBytes()); strData=new String(decrypted); } catch (Exception e) { e.printStackTrace(); throw new Exception(e); } return strData; } |
如何轻松地加密和解密的源文本在Java
这肯定会使用这个工作的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEParameterSpec; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; public class ProtectedConfigFile { private static final char[] PASSWORD ="enfldsgbnlsngdlksdsgm".toCharArray(); private static final byte[] Salt={ (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12, (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12, }; public static void main(String[] args) throws Exception { String originalPassword ="Aman"; System.out.println("Original password:" + originalPassword); String encryptedPassword = encrypt(originalPassword); System.out.println("Encrypted password:" + encryptedPassword); String decryptedPassword = decrypt(encryptedPassword); System.out.println("Decrypted password:" + decryptedPassword); } private 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"))); } private static String base64Encode(byte[] bytes) { // NB: This class is internal, and you probably should use another impl return new BASE64Encoder().encode(bytes); } private static String decrypt(String property) throws GeneralSecurityException, IOException { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD)); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20)); return new String(pbeCipher.doFinal(base64Decode(property)),"UTF-8"); } private static byte[] base64Decode(String property) throws IOException { // NB: This class is internal, and you probably should use another impl return new BASE64Decoder().decodeBuffer(property); } } |