2011-03-15 104 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

相关问题