Java加密与解密(by quqi99)
作者:张华 发表于:2009-12-31
版权声明:可以任意转载,转载时请务必以超链接形式标明文章原始出处和作者信息及本版权声明
1)base64算法
加密:new BASE64Encoder().encode(byte[] b)
解密: new BASE64Decoder().decode(byte[] b)
2) MD5或SHA摘要
MessageDigest digest = MessageDigest.getInstance("SHA"); //若是md5就 "MD5"
digest.update(byte[] b);
sha.degest();
3) 字节与16进制互换。
String strDigits = "0123456789ABCDEF";
String strDigitArr = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
public String byte2Hex(byte[] bytes){
String hs = "";
String stmp = "";
for(int =0;n<bytes.length;n++){
stmp = (Integer.toHexString(bytes[n] & 0XFF));
if(stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
}
return hs.toUpperCase();
}
public byte[] hex2Str(String hexStr){
char[] hexs = hexStr.toCharArray();
byte[] bytes = new byte[hexStr.length()/2];
int n;
for(int i=0;i<bytes.length;i++){
n = strDigits.indexOf(hexs[2*i]) * 16;
n += strDigits.indexOf(hexs[2*i + 1]);
bytes[i] = (byte)(n & 0xff);
}
}
4) RSA有公钥与密钥
生成密钥对:
private KeyPair generateKeyPair(){
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
gen.initialize(1024,new SecureRandom());
KeyPari key = gen.genKeyPair();
return key;
}
//从公钥字节恢复公钥
//从密钥字节恢复密钥与这差不多,只不过将public字眼换成private
private RSAPublicKey recoverRSAPublicKey(byte[] modulus, byte[] publicExponent){
RSAPublicKeySpec spec = new RSAPublicKeySpec(new BigInteger(modulus),new BigInteger(publicExponent));
KeyFactory fac = KeyFacotry.getInstance("RSA");
RSAPublicKey key = (RSAPublicKey)fac.generatePublic(spec);
return key;
}
//RSA加解密
private byte[] rsaTrans(int mode,Key key,byte[] data){
if(mode != Cipher.ENCRYPT_MODE && mode!=Cipher.DECRYPT_MODE)
throw new Exception("");
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(mode,key,new SecureRandom());
return cipher.doFinal(data);
}
使用上述的方法:
KeyPair keyPair = generateKeyPair();
RSAPublicKey pubKey = (RSAPublicKey)keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();
byte[] pubModulusBytes = pubKey.getModulus().toByteArray();
byte[] publicExponentBytes = pubKey.getPublicExponent().toByteArray();
byte[] privateModulusBytes = privateKey.getModulus().toByteArray();
byte[]privateExponentBytes = privateKey.getPrivateExponent().toByteArray();
pubKey = recoverRSAPublicKey(pubModulusBytes,publicExponentBytes); //恢复公钥,恢复密钥类似
//用私钥加密
byte[] encryptData = rsaTran(Cipher.ENCRYPT_MODE,privateKey,bytes));
//用公钥解密
encryptData = rsaTran(Cipher.DECRYPT_MODE,privateKey,bytes));
5) DES为单钥加密机制,加密过程与RSA差不多。
步骤1:生成一个安全密匙。在加密或解密任何数据之前需要有一个密匙。密匙是随同被加密的应用一起发布的一小段数据
import java.security.SecureRandom;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class GenerateKey
{
static public void main( String args[] ) throws Exception {
String keyFilename = "key.data";
String algorithm = "DES";
// 生成密匙
SecureRandom sr = new SecureRandom();
KeyGenerator kg = KeyGenerator.getInstance( algorithm );
kg.init( sr );
SecretKey key = kg.generateKey();//[-68, -68, -57, -71, 42, -125, 32, 13]
// 把密匙数据保存到文件
Util.writeFile( keyFilename, key.getEncoded() );
}
}
步骤2:加密数据。得到密匙之后,接下来就可以用它加密数据。
// DES算法要求有一个可信任的随机数源
SecureRandom sr = new SecureRandom();
byte rawKeyData[] = /* 用某种方法获得密匙数据 */;
// 从原始密匙数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec( rawKeyData );
// 创建一个密匙工厂,然后用它把DESKeySpec转换
// 一个SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance( "DES" );
SecretKey key = keyFactory.generateSecret( dks );
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance( "DES" );
// 用密匙初始化Cipher对象
cipher.init( Cipher.ENCRYPT_MODE, key, sr )
// 现在,获取数据并加密
byte data[] = /* 用某种方法获取数据 */
// 正式执行加密操作
byte encryptedData[] = cipher.doFinal( data );
// 进一步处理加密后的数据
步骤3:解密数据。
在上述加密数据将
cipher.init( Cipher.ENCRYPT_MODE, key, sr );
一句换成
cipher.init( Cipher.DECRYPT_MODE, key, sr );
doSomething( encryptedData );
下面附一个练习的例子,写的一个License,代码如下:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
/**
* @version 0.10 2010-2-28
* @author Zhang Hua
* 利用license机制来保护Java软件产品的安全
*/
public class License {
private static final String licensePath = "license.dat";
private static final String keyFilename = "key.data";
private static SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd"); //yyyy-MM-dd HH:mm:ss
//Product.title , AppServer
private String title = "AppServer";
//Product.sku, J2EE/CORBA
private String sku = "J2EE/CORBA";
//Serial.number, MAC Address
private byte[] serialNumber;
//Platform, all
private String platform = "";
//Trial.license
private boolean isTrial;
//License.expiry, 2010-05-12
private String expiry = "";
//Test
public static void main(String[] args){
//为用户生成license,并email给他
License om = new License();
om.setTitle("AppServer");
om.setSku("J2EE/CORBA");
String mac = getMACAddress();
om.setPlatform("Windows");
om.setTrial(false);
om.setExpiry("2010-05-12");
License.generateLicense(om,mac);
//在程序中校验license
License.validate();
}
//为用户生成license, 也就是将serialNumber字段的MAC加密
public static License generateLicense(License om,String mac){
try{
//密匙不存在,则生成密匙
if(! new File(keyFilename).exists()){
generateKey();
}
//用密匙加密数据
byte rawKeyData[] = readFile(keyFilename); //用某种方法获得密匙数据
DESKeySpec dks = new DESKeySpec( rawKeyData ); //从原始密匙数据创建DESKeySpec对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); //创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象
SecretKey key = keyFactory.generateSecret( dks );
Cipher cipher = Cipher.getInstance( "DES" ); //Cipher对象实际完成加密操作
SecureRandom sr = new SecureRandom(); //DES算法要求有一个可信任的随机数源
cipher.init(Cipher.ENCRYPT_MODE, key, sr ); //用密匙初始化Cipher对象
byte data[] = mac.getBytes(); //用某种方法获取数据
byte encryptedData[] = cipher.doFinal( data ); //正式执行加密操作
System.out.println("加密后的数据:" + encryptedData);
om.setSerialNumber(encryptedData);
//输出license
write(om);
}catch(Exception e){
e.printStackTrace();
}
return om;
}
//生成密匙
private static boolean generateKey(){
boolean result = false'
String algorithm = "DES";
try{
SecureRandom sr = new SecureRandom(); //DES算法要求有一个可信任的随机数源
KeyGenerator kg = KeyGenerator.getInstance(algorithm);
kg.init( sr );
SecretKey key = kg.generateKey(); //[-68, -68, -57, -71, 42, -125, 32, 13]
result = writeFile(keyFilename, key.getEncoded()); //把密匙数据保存到文件
}catch(Exception e){
e.printStackTrace();
}
return result;
}
public static boolean validate(){
boolean result = false;
try{
License om = read()'
String os = System.getProperty("os.name");
if (os.toLowerCase().startsWith(om.getPlatform().toLowerCase()) || "all".equals(om.getPlatform())) {
Date expireDate = sdf.parse(om.getExpiry());
if(expireDate.getTime() - new Date().getTime() < 0){
System.err.println("License过期了");
result = false'
}else{
if(om.isTrial()){
System.out.println("试用License有效");
result = true;
}else{
String mac = getMACAddress();
//用密匙解密数据
byte rawKeyData[] = readFile(keyFilename); //用某种方法获得密匙数据
DESKeySpec dks = new DESKeySpec( rawKeyData ); //从原始密匙数据创建DESKeySpec对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); //创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象
SecretKey key = keyFactory.generateSecret( dks );
Cipher cipher = Cipher.getInstance( "DES" ); //Cipher对象实际完成加密操作
SecureRandom sr = new SecureRandom(); //DES算法要求有一个可信任的随机数源
cipher.init(Cipher.DECRYPT_MODE, key, sr ); //用密匙初始化Cipher对象
byte data[] = om.getSerialNumber(); //用某种方法获取数据
byte encryptedData[] = cipher.doFinal(data); //正式执行加密操作
String tmp = new String(encryptedData);
System.out.println("解密后的数据:" + tmp);
if(mac.equals(tmp)){
System.out.println("License有效");
result = true;
}else{
System.err.println("License无效");
result = false;
}
}
}
}else{
System.err.println("License的平台无效");
result = false;
}
}catch(Exception e){
e.printStackTrace();
}
return result;
}
public static License read(){
License om = null;
try{
om = new License();
ObjectInputStream in = new ObjectInputStream(new FileInputStream(licensePath));
om.setTitle((String)in.readObject());
om.setSku((String)in.readObject());
om.setPlatform((String)in.readObject());
om.setTrial(in.readBoolean());
om.setExpiry((String)in.readObject());
om.setSerialNumber((byte[])in.readObject());
in.close();
}catch(Exception e){
e.printStackTrace();
}
return om;
}
public static boolean write(License om){
boolean result;
try{
File f = new File(licensePath);
if(f.exists())
f.delete();
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
out.writeObject(om.getTitle());
out.writeObject(om.getSku());
out.writeObject(om.getPlatform());
out.writeBoolean(om.isTrial());
out.writeObject(om.getExpiry());
out.writeObject(om.getSerialNumber());
out.close();
result = true;
}catch(Exception e){
e.printStackTrace();
result = false;
}
return result;
}
public static boolean writeFile(String path, byte[] bytes){
boolean result = false;
try {
FileOutputStream fos = new FileOutputStream(path);
fos.write(bytes);
fos.close();
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static byte[] readFile(String path){
byte[] bytes = null;
try {
FileInputStream fin = new FileInputStream(path);
bytes = new byte[fin.available()];
fin.read(bytes);
fin.close();
} catch (Exception e) {
e.printStackTrace();
}
return bytes;
}
public static String getMACAddress() {
String address = "";
String os = System.getProperty("os.name");
if (os.startsWith("Windows")) {
try {
String command = "cmd.exe /c ipconfig /all";
Process p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
if (line.indexOf("Physical Address") > 0) {
int index = line.indexOf(":");
index += 2;
address = line.substring(index);
break;
}
}
br.close();
return address.trim();
} catch (IOException e) {
e.printStackTrace();
}
} else if (os.startsWith("Linux")) {
String command = "/bin/sh -c ifconfig -a";
Process p;
try {
p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(p
.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
if (line.indexOf("HWaddr") > 0) {
int index = line.indexOf("HWaddr") + "HWaddr".length();
address = line.substring(index);
break;
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
address = address.trim();
return address;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public byte[] getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(byte[] serialNumber) {
this.serialNumber = serialNumber;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public boolean isTrial() {
return isTrial;
}
public void setTrial(boolean isTrial) {
this.isTrial = isTrial;
}
public String getExpiry() {
return expiry;
}
public void setExpiry(String expiry) {
this.expiry = expiry;
}
}
关于license的生成,还想说几点:
1)无论是生成二进制license,还是文件的,最好带上指纹校验。
2)无论是用什么加密算法无所谓,问题的关键不在里,在于JAVA容易被反编译,反编译之后很容易看到你的加密算法,人家可以
把这块替掉或者删除掉。另外,人家也可以在主程序调用license处的地方反编译之后直接返回true。
有网友说,对JAR包加密,然后自定义classloader解密,我看也是不行的,因为你自定义的classloader也是很容易被
反编译的,那样你的解密过程也就都清楚了。
所以,我认为,JAVA的东西就应用是开源的。当然,我们可以用混淆工具进行一定程度的混淆,算是给反编译增中一点困难的。
3)我试用了混淆工具proguard,觉得混淆工具有点不满足我的需求。
它默认是都混淆,但可以通过-keep参数指定某些类某些方法不混淆。
而我的需求是大多数类我不想混淆,我只想对少数几个类混淆,而且我的程序非常大,如果按照它的通过-keep参数指定
我不想混淆的类是不是有点太麻烦了。
下面是一个我测试过程中算是比较通用的配置my.conf,它对public,protected都不进行混淆,
用java -cp .;test.jar -jar proguard.jar @E:/workspace/test/my.conf 可执行混淆操作,my.conf文件如下:
-injars E:/workspace/test/test.jar
-outjars E:/workspace/test/test_out.jar
-libraryjars <java.home>/lib/rt.jar
-libraryjars E:/workspace/test/lib/mail.jar
-printmapping proguard.map
-renamesourcefileattribute SourceFile
-keepattributes Exceptions,InnerClasses,Signature,Deprecated,
SourceFile,LineNumberTable,*Annotation*,EnclosingMethod
-keep public class org.**
-keep public class * {
public protected *;
}
-keepclassmembernames class * {
java.lang.Class class$(java.lang.String);
java.lang.Class class$(java.lang.String, boolean);
}
-keepclasseswithmembernames class * {
native <methods>;
}
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
-keepclassmembers class * implements java.io.Serializable {
static final long serialVersionUID;
private void writeObject(java.io.ObjectOutputStream);
private void readObject(java.io.ObjectInputStream);
java.lang.Object writeReplace();
java.lang.Object readResolve();
}
一、密码学上常用的概念