Use truelicense to protect our Java software products

Source: Internet
Author: User

Use truelicense to protect our Java software products
Our Java software products sometimes need to restrict illegal users and can only be used by users who have purchased the license. Therefore, we can implement it through truelicense.

First, use the keytool to generate the private key Library:

Keytool-genkey-alias privatekey-keystore privatekeys. Store
Then, export the public key in the private key library to a file:

Keytool-export-alias privatekey-file certfile. cer-keystore privatekeys. Store
Then import the Certificate file to the public key database:

Keytool-import-alias publiccert-file certfile. cer-keystore publiccerts. Store

The server uses the private key library to create the license code example:

Package Licen; import de. schlichtherle. license. *; import Java. io. *; import Java. util. *; import javax. security. auth. x500.x500principal; import Java. util. prefs. preferences;/***** <p> title: cmvp value-added media business platform </P> ** <p> description: cmvp general media value-added business platform </P> ** <p> copyright: Copyright (c) 2005 </P> ** <p> company: source-ware.com Inc. </P> ** @ author * @ version 2.0 */public class swlicensemanager {public swlicense Manager () {} licensecontent verifylicensekey (licenseparam parameter) {// create a configured License Manager. licensemanager manager = new licensemanager (parameter); try {// verify the previously installed current license certificate. return manager. verify ();} catch (exception exc) {system. err. println ("cocould not verify license key"); EXC. printstacktrace (); return NULL ;}} void installlicense Key (licenseparam parameter, file Keyfile) {// create a configured License Manager. licensemanager manager = new licensemanager (parameter); try {// load the license key, verify and install it as the current license key. manager. install (Keyfile);} catch (exception exc) {system. err. println ("cocould not install license certificate"); EXC. printstacktrace () ;}} void createlicensekey (licenseparam para Meter, licensecontent content) {// create a configured License Manager. licensemanager manager = new licensemanager (parameter); try {// create the license key from the license content and save it to a file. manager. store (content, new file ("license. LIC ");} catch (exception exc) {system. err. println ("cocould not save license key"); EXC. printstacktrace () ;}/// customizable global properties./ // ** The product ID of your software */public static final string product_id = "cmvp20 "; // product_id/*** the subject for the License Manager and also the alias of the private * key entry in the keystore. */public static final string subject = "privatekey"; // Customize/** the Resource Name of your private keystore file. */public static final string keystore_resource = "privatekeys. store "; // Private Key library file name/** the password for the keystore. */public static final string keystore_store_pwd = "a8a8a8"; // Private Key library password/* the password for the private key entry in the keystore. */public static final string keystore_key_pwd = "a8a8a8"; // password of the private key database primary key/** the password to encrypt the generated license key file. */public static final string cipher_key_pwd = "a8a8a8"; // The license password to be generated/*** the filename Be displayed for the generated binary key file when * delivered. please note that this is not used to write to a file of * this name. */public static final string display_filename = "license. LIC "; // license. LIC /// the rest of this key generator does not need to get customized. /// ** the MIME type of the generated binary key file. */public static final string mime_type = "application/octet- Stream "; // possible key generator exit codes // *** return <code> erc_success </code> On succesful creation of a textual key. * Note that this example creates a binary key and thus this constant is not * used here * // public static final int erc_success = 00; /*** return <code> erc_success_bin </code> On succesful creation of a binary * key. (which cocould contain text as well, if the content ty PE is specified * as <code> text/plain </code>) */public static final int erc_success_bin = 01; /*** return <code> erc_error </code> for general errors. */public static final int erc_error = 10;/*** return <code> erc_memory </code> If memory allocation fails. */public static final int erc_memory = 11;/*** return <code> erc_file_io </code> On ioexception */public static final int erc_file_io = 12; /*** Return <code> erc_bad_args </code> If the command line parameters are * Bad. */public static final int erc_bad_args = 13;/*** return <code> erc_bad_input </code> If a participant input value is * missing or has a bad value. don't forget to supply a meaningful Error * message naming the exact cause of the error. */public static final int erc_bad_input = 14;/*** return <code> erc_expired </COD E> if this generator is expired. this can * be used to limit the lifetime of this generator. * // public static final int erc_expired = 15;/*** return <code> erc_internal </code> If an unhandled exception occurs. ** @ see Java. lang. exception * // public static final int erc_internal = 16;/** encoding keys in properties. */public static final string encoding_key = "encoding"; public static final String product_id_key = "product_id"; public static final string purchase_id_key = "purchase_id"; public static final string Signature = "running_no"; public static final string purchase_date_key = "purchase_date "; public static final string incluage_id_key = "incluage_id"; public static final string quantity_key = "quantity"; public static final string reg_name_key = "reg_name"; Public stati C Final string additional1_key = "additional1"; public static final string region = "additional"; public static final string reseller_key = "reseller"; public static final string lastname_key = "lastname "; public static final string firstname_key = "firstname"; public static final string company_key = "company"; public static final string email_key = "email"; public static final string P Hone_key = "phone"; public static final string fax_key = "fax"; public static final string street_key = "street"; public static final string zip_key = "Zip "; public static final string city_key = "city"; public static final string state_key = "state"; public static final string country_key = "country";/** default encoding for properties. */public static final string encoding_properties = "ISO-88 59-1 ";/** default share-It encoding if key not present in properties. */public static final string encoding_default = encoding_properties; protected static final licensemanager manager = new licensemanager (New defaultlicenseparam (subject, preferences. userroot (), new defaultkeystoreparam (swlicensemanager. class, // customize keystore_resource, subject, keystore_store_pwd, keystore_key_pwd), new Defaultcipherparam (cipher_key_pwd);/*** validates the properties and generates a license certificate file. */Private Static void generatelicense (properties props, file certfile) throws exception {// check for supported product ID. final string productid = props. getproperty (product_id_key); If (! Product_id.equals (productid) {Throw new badinputexception ("bad product ID:" + productid);} final stringbuffer DN = new stringbuffer (); addattrition (DN, "cn", props. getproperty (firstname_key) + ''+ props. getproperty (lastname_key); If (DN. length () = 0) {addattribute (DN, "cn", props, reg_name_key);} addattribute (DN, "O", props, company_key); addattribute (DN, "street", props, street_key); add Attribute (DN, "L", props. getproperty (zip_key) + ''+ props. getproperty (city_key); addattribute (DN, "St", props, state_key); addattribute (DN, "C", props, country_key ); final x500principal holder = new x500principal (DN. tostring (); Final x500principal issuer = new x500principal ("ou = Share-it !, O = element 5 AG, street = vogelsanger Strasse 78, L = 50823 k \ u00f6ln, St = Nordrhein-Westfalen, c = de "); Final licensecontent content = new licensecontent (); content. setholder (holder); content. setissuer (issuer); content. setconsumertype ("user"); content. setconsumeramount (1); content. setinfo (props. tostring (); content. setsubject (subject); Java. util. calendar Cal = Java. util. calendar. getinstance (); Cal. set (2011,10, 10); content. setnotafter (Cal. gettime (); manager. store (content, certfile);} Private Static final void addattribute (final stringbuffer DN, final string OID, final properties props, final string key) {addattribute (DN, OID, props. getproperty (key);} Private Static void addattribute (final stringbuffer DN, final string OID, string value) {If (value = NULL) {return;} final string trimmedvalue = Value. Trim (); If ("". Equals (trimmedvalue) {return;} // see http://www.ietf.org/rfc/rfc2253.txt Boolean quote = false; If (! Value. equals (trimmedvalue) {quote = true;} else if (value. matches (". * [+,; <> \ "]. * ") {;}quote = true; If (DN. length ()! = 0) {DN. append (',');} DN. append (OID); DN. append ('='); If (quote) {DN. append ('"');} // replace every single backslash with two backslashes // whereas both parameters are expressed as regular expressions. value = value. replaceall ("\\\\","\\\\\\\\"); // replace every single quote with an escaped quote // whereas both parameters are expressed as regular expressions. value = value. replaceall ("\"", "\\\\\" "); DN. append (value); If (quote) {DN. append ('"') ;}} Private Static Properties readinput (string pathname) throws ioexception {properties props = new encodedproperties (); inputstream in = new fileinputstream (pathname ); try {props. load (in);} catch (illegalargumentexception IAE) {Throw new badinputexception (IAE);} finally {In. close ();} return props;}/*** this is the main entry poi NT for Java key generators. it processes the * command line arguments, loads and parses the input file, callthe key * Generator and writes output files. ** Java exceptions are handled and transformed into key generator error * codes. exception messages will be written to <code> ARGs [1] </code> and * display on the error console. */public static int keymain (string ARGs []) {ARGs = new string [3]; ARGs [0] = "license. properties"; ARGs [1] = "license. status"; ARGs [2] = "license. Lic"; if (ARGs. length! = 3) {system. err. println ("Usage: <input> <output1> <output2>"); Return erc_bad_args;} int errorcode = erc_error; printwriter out = new printwriter (system. err); try {// read input and get encoding final properties props = readinput (ARGs [0]); final string encoding = props. getproperty (encoding_key, encoding_default); // setup real output with encoding read from input file. out = new printwriter (New outputstreamwriter (New fileoutputstream (ARGs [1]), encoding); // validate input and generate key file. generatelicense (props, new file (ARGs [2]); // write status. out. write (mime_type + ":" + display_filename);} catch (badinputexception BIE) {errorcode = erc_bad_input; throw BIE;} catch (ioexception IOE) {errorcode = erc_file_io; throw IOE ;} catch (outofmemoryerror Oome) {errorcode = erc_memory; throw Oome ;}} catch (throwable t) {out. println ("Error #" + errorcode); T. printstacktrace (out); Return errorcode;} finally {out. close ();} return erc_success_bin;}/*** Note: This main () method is never called by the actual key server. it is * just useful for debugging the key generator. */public static final void main (string ARGs []) {keymain (ARGs);/* try {manager. install (New Java. io. file ("swutil. log "); system. out. println ("subject =" + manager. verify (). getsubject (); system. exit (0);} catch (exception ex) {ex. printstacktrace ();} */} public static class encodedproperties extends properties {public encodedproperties () {This (new properties ());} /*** @ throws nullpointerexception If <tt> defaults </tt> is <tt> null </tt>. */Public encodedproperties (properties defaults) {super (defaults); // make sure we have a proper default for the encoding. defaults. setproperty (encoding_key, encoding_default);} public void load (inputstream instream) throws ioexception {super. load (instream); string encoding = super. getproperty (encoding_key); If (encoding_properties.equals (encoding) {return ;}// convert properties try {map. entry [] entries = new map. entry [entryset (). size ()]; entryset (). toarray (entries); For (INT I = entries. length; -- I> = 0;) {map. entry entry = entries [I]; string value = (string) entry. getvalue (); value = new string (value. getbytes (encoding_properties), encoding); setproperty (string) entry. getkey (), value) ;}} catch (unsupportedencodingexception ignored) {}} public static class badinputexception extends ioexception {public badinputexception (string message) {super (Message );} public badinputexception (throwable cause) {initcause (cause );}}}

Code for installing the license and verifying the validity of the license in the client program:
Security Warning
Do not copy the private key Library to the client, but just copy the Public Key library. Otherwise, hackers can use your private key library to generate many licenses.

Package COM. sourceware. cmvp. license; import de. schlichtherle. license. *; import Java. io. *; import Java. util. *; import javax. security. auth. x500.x500principal; import Java. util. prefs. preferences;/***** <p> title: cmvp value-added media business platform </P> ** <p> description: cmvp general media value-added business platform </P> ** <p> copyright: Copyright (c) 2005 </P> ** <p> company: source-ware.com Inc. </P> ** @ author * @ version 2.0 */public class cmvplicensemanager {public cmvplicensemanager () {}/** the product ID of your software */public static final string product_id = "cmvp20 "; // Customize/*** the subject for the License Manager and also the alias of the private * key entry in the keystore. */public static final string subject = "alias"; // Customize/** the Resource Name of your private keystore file. */public static final string keystore_resource = "Public Key library file name"; // Customize/** the password for the keystore. */public static final string keystore_store_pwd = "Public Key Database Password"; // Customize/** the password to encrypt the generated license key file. */public static final string cipher_key_pwd = "license file Password"; // customize protected static final licensemanager manager = new licensemanager (New defaultlicenseparam (subject, preferences. usernodeforpackage (cmvplicensemanager. class), new defakeykeystoreparam (cmvplicensemanager. class, // customize keystore_resource, subject, keystore_store_pwd, null), // It must be null new defaultcipherparam (cipher_key_pwd);/*** Note: This main () method is never called by the actual key server. it is * just useful for debugging the key generator. */public static final void main (string ARGs []) {try {manager. install (New Java. io. file ("license. LIC "); string subject = manager. verify (). getsubject (); system. out. println ("Subject =======" + subject);} catch (exception ex) {ex. printstacktrace ();}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.