背景
公司项目准备以软件的形式卖给客户,服务器和数据库都在对方机房。老板又不希望客户拿软件包copy一下就能到别的地方用。
我们知道正常电脑的主板序列号、cpuMAC地址、磁盘序列号等都是唯一的。所以我就以这个为思路,获取客户服务器的唯一ID,然后用rsa非对称加密算法,在自己公司的程序用私钥加密,算出一个注册码传给客户。客户那边的项目输入此注册码,后台用公钥解密,然后与本机的唯一id做对比,如果相同则注册成功。系统再写个定时任务去对比注册码和本机ID是否相同。
安全性
我们知道rsa非对称加密是很难破解的,客户那边项目代码只持有公钥,私钥在自己公司,正常无法破解。
主要代码如下
以下代码是本人从网上找到并加以修改,现在完全是可用的,本人环境jdk1.8+centos7。
先是RSA工具类
import java.io.IOException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class RSAUtil {
//生成秘钥对
public static KeyPair getKeyPair() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
return keyPair;
}
//获取公钥(Base64编码)
public static String getPublicKey(KeyPair keyPair){
PublicKey publicKey = keyPair.getPublic();
byte[] bytes = publicKey.getEncoded();
return byte2Base64(bytes);
}
//获取私钥(Base64编码)
public static String getPrivateKey(KeyPair keyPair){
PrivateKey privateKey = keyPair.getPrivate();
byte[] bytes = privateKey.getEncoded();
return byte2Base64(bytes);
}
//将Base64编码后的公钥转换成PublicKey对象
public static PublicKey string2PublicKey(String pubStr) throws Exception{
byte[] keyBytes = base642Byte(pubStr);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
// //将Base64编码后的si钥转换成PublicKey对象
// public static PrivateKey string2PrivateKey(String pubStr) throws Exception{
// byte[] keyBytes = base642Byte(pubStr);
// X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
// KeyFactory keyFactory = KeyFactory.getInstance("RSA");
// PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
// return privateKey;
// }
//将Base64编码后的私钥转换成PrivateKey对象
public static PrivateKey string2PrivateKey(String priStr) throws Exception{
byte[] keyBytes = base642Byte(priStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
//公钥加密
public static byte[] publicEncrypt(byte[] content, PublicKey publicKey) throws Exception{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] bytes = cipher.doFinal(content);
return bytes;
}
//si钥加密
public static byte[] privateEncrypt(byte[] content, PrivateKey privateKey) throws Exception{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] bytes = cipher.doFinal(content);
return bytes;
}
//gong钥解密
public static byte[] publicDecrypt(byte[] content, PublicKey publicKey) throws Exception{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] bytes = cipher.doFinal(content);
return bytes;
}
//私钥解密
public static byte[] privateDecrypt(byte[] content, PrivateKey privateKey) throws Exception{
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] bytes = cipher.doFinal(content);
return bytes;
}
//字节数组转Base64编码
public static String byte2Base64(byte[] bytes){
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(bytes);
}
//Base64编码转字节数组
public static byte[] base642Byte(String base64Key) throws IOException{
BASE64Decoder decoder = new BASE64Decoder();
return decoder.decodeBuffer(base64Key);
}
}
然后是RSA密钥生成工具和解密工具。正常生产应该是只把解密工具类放在客户系统,密钥生成工具不能开放。
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
public class GenerateRSA {
public static void main(String[] args) {
try {
//===============生成公钥和私钥,公钥传给客户端,私钥服务端保留==================
//生成RSA公钥和私钥,并Base64编码
KeyPair keyPair = RSAUtil.getKeyPair();
String publicKeyStr = RSAUtil.getPublicKey(keyPair);
String privateKeyStr = RSAUtil.getPrivateKey(keyPair);
//正常应该是先生成公钥私钥,然后每个项目用固定的公私钥
/* String publicKeyStr = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnLBuszBdZHiZpM1qEZ1J2FDAi49g0j/X\n" +
"ZN4gvluRUVDYNN0QNQithtXqE/vASL37PA4vLMRUoT7yvkxqDuKZ7UIs0jBIJRGidy/vAUPQd/Bt\n" +
"hXgtmO5qIG3Xf4guFuFYAgaDytyq8TQ6QtuJwj6qtfoaEy9JlHdX0PV8jwd7r7jgFmNWkUeu4BqY\n" +
"BkEO6WchQXbw58PwZVTCu36n3XDAcU9we0+wVyCel3thXAjUXwW+lX2Eu58J5sCGlQesmbjmiJWz\n" +
"d/bFPgUntqmiMVAmBxH7W3/GbU6N6YlYEcI27sqtwPNIEUHCf9BGyqSqtK57HfYeb/VNdw3hyhIl\n" +
"LkByMQIDAQAB";
System.out.println("RSA公钥Base64编码:\n" + publicKeyStr);
System.out.println("RSA私钥Base64编码:\n" + privateKeyStr);*/
//=================服务端=================
//获取主板序列号 此为要加密的明文 正常行的数据应该是客户系统运行获取,再告诉我们
String message = GetBordId.getMainBordId();
System.out.println(message);
//将Base64编码后的公钥转换成PublicKey对象
PrivateKey privateKey = RSAUtil.string2PrivateKey(privateKeyStr);
//用私钥加密
byte[] privateEncrypt = RSAUtil.privateEncrypt(message.getBytes(), privateKey);
//加密后的内容Base64编码
String byte2Base64 = RSAUtil.byte2Base64(privateEncrypt);
System.out.println("私钥加密并Base64编码的结果:\n" + byte2Base64);
//############## 网络上传输的内容有Base64编码后的公钥 和 Base64编码后的公钥加密的内容 #################
//===================客户端================
//将Base64编码后的公钥转换成PrivateKey对象
PublicKey publicKey = RSAUtil.string2PublicKey(publicKeyStr);
//加密后的内容Base64解码
byte[] base642Byte = RSAUtil.base642Byte(byte2Base64);
//用公钥解密
byte[] publicDecrypt = RSAUtil.publicDecrypt(base642Byte, publicKey);
//解密后的明文
System.out.println("解密后的明文:\n " + new String(publicDecrypt));
} catch (Exception e) {
e.printStackTrace();
}
}
}
然后还有个获取本机主板序列号的工具类
import org.apache.commons.lang3.StringUtils;
import java.io.*;
public class GetBordId {
/**
* 获取当前操作系统名称. return 操作系统名称 例如:windows xp,linux 等.
*/
public static String getOSName() {
return System.getProperty("os.name").toLowerCase();
}
public static String getMainBordId_windows() {
String result = "";
try {
File file = File.createTempFile("realhowto", ".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);
String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
+ "Set colItems = objWMIService.ExecQuery _ \n"
+ " (\"Select * from Win32_BaseBoard\") \n"
+ "For Each objItem in colItems \n"
+ " Wscript.Echo objItem.SerialNumber \n"
+ " exit for ' do the first cpu only! \n" + "Next \n";
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec(
"cscript //NoLogo " + file.getPath());
BufferedReader input = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
result += line;
}
input.close();
} catch (Exception e) {
System.out.println("获取主板信息错误"+e);
}
return result.trim();
}
public static String getMainBordId_linux() {
String result = "";
String maniBord_cmd = "dmidecode | grep 'Serial Number' | awk '{print $3}' | tail -1";
Process p;
try {
p = Runtime.getRuntime().exec(
new String[] { "sh", "-c", maniBord_cmd });// 管道
BufferedReader br = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
result += line;
break;
}
br.close();
} catch (IOException e) {
System.out.println("获取主板信息错误"+e);
}
return result;
}
public static String getMainBordId() throws Exception {
String os = getOSName();
String mainBordId = "";
if (os.startsWith("windows")) {
mainBordId = getMainBordId_windows();
} else if (os.startsWith("linux")) {
mainBordId = getMainBordId_linux();
}
if(!StringUtils.isNotBlank(mainBordId)){
mainBordId="null";
}
return mainBordId;
}
public static void main(String[] args) throws Exception {
String mainBord = getMainBordId();
System.out.println(mainBord);
}
}
总结
主要的代码已经贴出来了。思路就是我们先生成固定的公私钥,并把公钥硬编码写在项目里,然后客户那边获取本机的主板序列号,可以用那个工具类并写一个controller的友好界面给客户,然后我们向客户拿到这串序列号,在自己公司用私钥加密,并把加密后的注册码发给客户让客户填写,填写后解密验证。