欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 加密解密字符串详解

程序员文章站 2023-10-19 13:41:23
加密和解密的字符串:复制代码 代码如下:package eoe.demo; import java.security.securerandom; import javax....
加密和解密的字符串:
复制代码 代码如下:

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));
}
}