com.floreantpos.license.FiveStarPOSLicenseGenerator.java Source code

Java tutorial

Introduction

Here is the source code for com.floreantpos.license.FiveStarPOSLicenseGenerator.java

Source

package com.floreantpos.license;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.Properties;

import org.apache.commons.io.IOUtils;

/**
 * @author Dali Freire - dalifreire@gmail.com
 */
public class FiveStarPOSLicenseGenerator {

    public static String generateLicense(Properties templateProperties, InputStream privateKeyInputStream,
            File licenseFile) throws FileNotFoundException, NoSuchAlgorithmException, InvalidKeySpecException,
            IOException, InvalidKeyException, SignatureException {

        PrivateKey privateKey = readPrivateKey(privateKeyInputStream);
        String encoded = templateProperties.toString();
        String signature = FiveStarPOSLicenseGenerator.sign(encoded.getBytes(), privateKey);

        OutputStream output = new FileOutputStream(licenseFile);
        Properties licenseProperties = new OrderedProperties();
        licenseProperties.putAll(templateProperties);
        licenseProperties.setProperty(License.SIGNATURE, signature);
        licenseProperties.store(output, "License file");
        output.close();

        return signature;
    }

    private static PrivateKey readPrivateKey(InputStream privateKey)
            throws FileNotFoundException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(IOUtils.toByteArray(privateKey));
        KeyFactory keyFactory = KeyFactory.getInstance("DSA");
        PrivateKey key = keyFactory.generatePrivate(keySpec);
        return key;
    }

    private static String sign(byte[] message, PrivateKey privateKey)
            throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {

        Signature dsa = Signature.getInstance("SHA/DSA");
        dsa.initSign(privateKey);
        dsa.update(message);

        byte[] signature = dsa.sign();
        return Base64.getEncoder().encodeToString(signature);
    }

}