2011-03-15 113 views

回答

0

嘗試這樣的事情對數據進行加密。

MessageDigest md = MessageDigest.getInstance("MD5"); 


...... 


synchronized (md) { 

md.reset(); 
byte[] hash = md.digest(plainTextPassword.getBytes("CP1252")); 

StringBuffer sb = new StringBuffer(); 
for (int i = 0; i < hash.length; ++i) { 
sb.append(Integer.toHexString((hash[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3)); 
} 

String password = sb.toString(); 
} 
+0

-1建議使用快速散列函數。見http://security.stackexchange.com/a/242/5501 – 2012-06-28 14:39:58

-1

你也可以使用類似下面的東西。下面是一個加密方法,它接受一個字符串輸入並返回並加密字符串。您可以將密碼傳遞給此方法。

public static String crypt(String str) { 
    if (str == null || str.length() == 0) { 
     throw new IllegalArgumentException(
       "String to encrypt cannot be null or zero length"); 
    } 

    StringBuffer hexString = new StringBuffer(); 

    try { 
     MessageDigest md = MessageDigest.getInstance("MD5"); 
     md.update(str.getBytes()); 
     byte[] hash = md.digest(); 

     for (int i = 0; i < hash.length; i++) { 
      if ((0xff & hash[i]) < 0x10) { 
       hexString.append("0" 
         + Integer.toHexString((0xFF & hash[i]))); 
      } else { 
       hexString.append(Integer.toHexString(0xFF & hash[i])); 
      } 
     } 
    } catch (NoSuchAlgorithmException e) { 

    } 

    return hexString.toString(); 
} 
+0

-1建議使用快速散列函數。見http://security.stackexchange.com/a/242/5501 – 2012-06-28 14:38:22

+0

@Andrey Botalov。好的有效的點。感謝您的有用鏈接。 – ashishjmeshram 2012-06-28 14:49:56

8

自寫算法是一種安全風險,並且很難維護。
MD5是not secure

使用bcrypt算法,通過jBcrypt(開放源代碼)提供:

// Hash a password 
String hashed = BCrypt.hashpw(password, BCrypt.gensalt()); 

// Check that an unencrypted password matches or not 
if (BCrypt.checkpw(candidate, hashed)) 
    System.out.println("It matches"); 
else 
    System.out.println("It does not match"); 

如果你使用Maven,你可以在你的pom.xml 插入下面的依賴使該庫(如果新版本可以請讓我知道)

<dependency> 
    <groupId>de.svenkubiak</groupId> 
    <artifactId>jBCrypt</artifactId> 
    <version>0.4.1</version> 
</dependency> 
+0

如何在我的代碼中使用它 – 2017-02-28 11:05:42

+0

@VedPrakash:我添加了一段關於從Maven獲取它的段落,這有幫助嗎? – 2017-03-01 03:10:19

+0

@Nicolass拉烏爾謝謝主席先生 – 2017-03-01 06:28:25

相關問題