欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java加密密码,java加密,public class

来源: javaer 分享于  点击 38916 次 点评:107

java加密密码,java加密,public class


public class CryptoUtils {  public static void main(String arg[]) {    try {      // quick way to do input from the keyboard, now deprecated...      java.io.StreamTokenizer Input=new java.io.StreamTokenizer(System.in);      //      System.out.print("Input your secret password : ");      Input.nextToken();      String secret = new String(CryptoUtils.encrypt(Input.sval));      System.out.println("the encrypted result : " + secret);      boolean ok = true;      String s = "";      while (ok) {          System.out.print("Now try to enter a password : " );          Input.nextToken();          s = new String(CryptoUtils.encrypt(Input.sval));          if (secret.equals(s)){             System.out.println("You got it!");             ok = false;             }          else             System.out.println("Wrong, try again...!");      }    }    catch (Exception e){      e.printStackTrace();    }  }  public static byte[] encrypt(String x)   throws Exception  {     java.security.MessageDigest d =null;     d = java.security.MessageDigest.getInstance("SHA-1");     d.reset();     d.update(x.getBytes());     return  d.digest();  }}

输出如下:

Input your secret password : howtothe encrypted result : ûóbf-m¦esdNow try to enter a password : HowtoWrong, try again...!Now try to enter a password : howToWrong, try again...!Now try to enter a password : howtoYou got it!

下面的代码可以简单的对字符串做base编码

sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();String encoded=encoder.encode(secret.getBytes());// encoded is a string with printable characters.

或者,我们可以简单的将字符串转为16进制数字表示方法

public class StringUtils {public static void main(String arg[]) {   byte b[] = { 7, 42, -1, -127 }; // 7, 2A, FF, 81   System.out.println(byteArrayToHexString(b));   /*      output :      072AFF81   */   b = hexStringToByteArray(byteArrayToHexString(b));   for (int i = 0; i < b.length; i++) {     System.out.println(b[i]);   }   /*   output :   7   42   -1   -127   */}public static String byteArrayToHexString(byte[] b){    StringBuffer sb = new StringBuffer(b.length * 2);    for (int i = 0; i < b.length; i++){      int v = b[i] & 0xff;      if (v < 16) {        sb.append('0');      }      sb.append(Integer.toHexString(v));    }    return sb.toString().toUpperCase();}public static byte[] hexStringToByteArray(String s) {    byte[] b = new byte[s.length() / 2];    for (int i = 0; i < b.length; i++){      int index = i * 2;      int v = Integer.parseInt(s.substring(index, index + 2), 16);      b[i] = (byte)v;    }    return b;  }}
相关栏目:

用户点评