com.jinhe.tss.framework.license.LicenseFactory.java Source code

Java tutorial

Introduction

Here is the source code for com.jinhe.tss.framework.license.LicenseFactory.java

Source

package com.jinhe.tss.framework.license;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jinhe.tss.util.EasyUtils;
import com.jinhe.tss.util.FileHelper;
import com.jinhe.tss.util.URLUtil;

public class LicenseFactory {

    private final static Log log = LogFactory.getLog(LicenseFactory.class);

    static String LICENSE_DIR = URLUtil.getClassesPath().getPath();
    static String PRIVATE_KEY_FILE = LICENSE_DIR + "/private.key";
    static String PUBLIC_KEY_FILE = LICENSE_DIR + "/public.key";

    //   
    public static final String KEY_ALGORITHM = "DSA";

    // ? 
    public static final String SIGN_ALGORITHM = "SHA1withDSA";

    /**
     * ?license???
     * @param license
     * @throws Exception
     */
    public static synchronized void sign(License license) throws Exception {
        String privateKey = FileHelper.readFile(new File(PRIVATE_KEY_FILE));
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(EasyUtils.decodeHex(privateKey.trim()));
        PrivateKey privKey = keyFactory.generatePrivate(privKeySpec);

        Signature sig = Signature.getInstance(SIGN_ALGORITHM);
        sig.initSign(privKey);
        sig.update(license.getFingerprint());

        license.licenseSignature = EasyUtils.encodeHex(sig.sign());
    }

    /**
     * ???
     * ????hacker??license
     * @throws Exception
     */
    public static void generateKey() throws Exception {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyGen.initialize(1024, new SecureRandom());
        KeyPair pair = keyGen.generateKeyPair();
        PrivateKey priv = pair.getPrivate();
        PublicKey pub = pair.getPublic();

        log.info("?");
        DataOutputStream out = new DataOutputStream(new FileOutputStream(PUBLIC_KEY_FILE));
        out.writeBytes(EasyUtils.encodeHex(pub.getEncoded()));
        out.close();
        log.info("??" + PUBLIC_KEY_FILE);

        out = new DataOutputStream(new FileOutputStream(PRIVATE_KEY_FILE));
        out.writeBytes(EasyUtils.encodeHex(priv.getEncoded()));
        out.close();
        log.info("??" + PRIVATE_KEY_FILE);
    }

}