当前位置: 移动技术网 > IT编程>移动开发>Android > Android 加密解密字符串详解

Android 加密解密字符串详解

2019年07月24日  | 移动技术网IT编程  | 我要评论

北苑家园车祸,黛塔范提斯,银行承兑汇票贴现

加密和解密的字符串:
复制代码 代码如下:

package eoe.demo;
import java.security.securerandom;
import javax.crypto.cipher;
import javax.crypto.keygenerator;
import javax.crypto.secretkey;
import javax.crypto.spec.secretkeyspec;
/**
* usage:
* <pre>
* string crypto = simplecrypto.encrypt(masterpassword, cleartext)
* ...
* string cleartext = simplecrypto.decrypt(masterpassword, crypto)
* </pre>
* @author ferenc.hechler
*/
public class simplecrypto {
public static string encrypt(string seed, string cleartext) throws exception {
byte[] rawkey = getrawkey(seed.getbytes());
byte[] result = encrypt(rawkey, cleartext.getbytes());
return tohex(result);
}
public static string decrypt(string seed, string encrypted) throws exception {
byte[] rawkey = getrawkey(seed.getbytes());
byte[] enc = tobyte(encrypted);
byte[] result = decrypt(rawkey, enc);
return new string(result);
}
private static byte[] getrawkey(byte[] seed) throws exception {
keygenerator kgen = keygenerator.getinstance("aes");
securerandom sr = securerandom.getinstance("sha1prng");
sr.setseed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
secretkey skey = kgen.generatekey();
byte[] raw = skey.getencoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws exception {
secretkeyspec skeyspec = new secretkeyspec(raw, "aes");
cipher cipher = cipher.getinstance("aes");
cipher.init(cipher.encrypt_mode, skeyspec);
byte[] encrypted = cipher.dofinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws exception {
secretkeyspec skeyspec = new secretkeyspec(raw, "aes");
cipher cipher = cipher.getinstance("aes");
cipher.init(cipher.decrypt_mode, skeyspec);
byte[] decrypted = cipher.dofinal(encrypted);
return decrypted;
}
public static string tohex(string txt) {
return tohex(txt.getbytes());
}
public static string fromhex(string hex) {
return new string(tobyte(hex));
}
public static byte[] tobyte(string hexstring) {
int len = hexstring.length()/2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = integer.valueof(hexstring.substring(2*i, 2*i+2), 16).bytevalue();
return result;
}
public static string tohex(byte[] buf) {
if (buf == null)
return "";
stringbuffer result = new stringbuffer(2*buf.length);
for (int i = 0; i < buf.length; i++) {
appendhex(result, buf[i]);
}
return result.tostring();
}
private final static string hex = "0123456789abcdef";
private static void appendhex(stringbuffer sb, byte b) {
sb.append(hex.charat((b>>4)&0x0f)).append(hex.charat(b&0x0f));
}
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网