工具类--用户名的加密&解密

加密解密工具类:

public class MyTools {


/**

 * 获取加密密钥Key

 * 

 * @param keyString

 * @return

 */

public static Key getKey(String keyString) {

byte[] keyStringByte = keyString.getBytes();

byte[] keyByte = new byte[8];

for (int i = 0; i < keyStringByte.length && i < keyByte.length; i++) {

keyByte[i] = keyStringByte[i];

}

Key key = new SecretKeySpec(keyByte, "DES");

return key;

}


/**

 * 将byte数组转换成16进制String

 * 

 * @param bytes

 * @return

 * @throws Exception

 */

public static String byteArr2HexStr(byte[] bytes) throws Exception {

StringBuffer sb = new StringBuffer(bytes.length * 2);

for (int i = 0; i < bytes.length; i++) {

if ((bytes[i] & 0xFF) < 0x10)

sb.append("0");

sb.append(Integer.toHexString(bytes[i] & 0xFF));

}

return sb.toString();

}


/**

 * 将16进制string转换成byte数组

 * 

 * @param str

 * @return

 * @throws Exception

 */

public static byte[] hexStr2ByteArr(String str) throws Exception {


byte[] bytes = str.getBytes();


int len = bytes.length;

byte[] arr = new byte[len / 2];

for (int i = 0; i < len; i = i + 2) {

String tmp = new String(bytes, i, 2);

arr[i / 2] = (byte) Integer.parseInt(tmp, 16);

}

return arr;

}


/**

 * 对字符串进行DES加密

 * 

 * @param val

 *            原始字符串

 * @param key

 *            加密使用的key

 * @return

 * @throws Exception

 */

public static String getDES(String val, String key) throws Exception {

if (val == null || key == null)

return null;


Cipher encryptCipher = Cipher.getInstance("DES");

encryptCipher.init(Cipher.ENCRYPT_MODE, getKey(key));

byte[] cipherByte = encryptCipher.doFinal(val.getBytes());


return byteArr2HexStr(cipherByte);

}


/**

 * 对DES加密后的16进制字符串进行解密

 * 

 * @param val

 * @param key

 * @return

 * @throws Exception

 */

public static String getDESOri(String val, String key) throws Exception {

if (val == null || key == null)

return null;


Cipher decryptCipher = Cipher.getInstance("DES");

decryptCipher.init(Cipher.DECRYPT_MODE, getKey(key));

byte[] originalByte = decryptCipher.doFinal(hexStr2ByteArr(val));


return new String(originalByte);

}

}

数据调用&设置:

//部分初始化

private EditText et_username;

et_username = (EditText) findViewById(R.id.et_username);

String userName = et_username.getText().toString().trim();

private String key = "JiaMi";//密钥

。。。

String getStr = MyTools.getDES(userName, key);//加密

。。。

String getoldStr = MyTools.getDESOri(getStr, key);//解密

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值