java RSA Encryption Generates license and CPU Sequence Number Generates Machine Code

Keywords: Java encoding JDK codec

The license contains registration information, a string of key-value pairs.

 

Symmetric encryption:

DES, AES, encryption and decryption all use a secret key, fast speed

Asymmetric Confidentiality

RSA can encrypt and decrypt public key with private key, or decrypt public key and private key with slow speed.

Be careful:
RSA encrypts plaintext with a maximum length of 117 bytes, and decryption requires a maximum length of 128 bytes, so it needs to be partitioned in the process of encryption and decryption.
RSA encryption limits the length of plaintext. If the encrypted data is too large, an exception will be thrown:

 

Common Encryption Algorithms

DES 

DES is the abbreviation of Data Encryption Standard (Data Encryption Standard). DES algorithm is a symmetric cryptosystem in cryptosystem. It is an encryption algorithm developed by IBM. In 1977, the National Standards Bureau of the United States announced it as a data encryption standard used by non-key departments. For 20 years, it has been active on the stage of international confidential communications and played a very important role.
DES is a block encryption algorithm, which encrypts data in 64 bits. At the same time, DES is also a symmetric algorithm: encryption and decryption use the same algorithm. Its key length is 56 bits (because every eighth bit is used for parity checking), and the key can be any number of 56 bits, and can be changed at any time. A very small number of them are considered weak keys, but it's easy to avoid them. So confidentiality depends on the key.
Features: Shorter grouping, shorter key, shorter password life cycle and slower operation speed.
DES algorithm has very high security, so far, there is no more effective way to attack DES algorithm except exhaustive search method. The exhaustive space of 56-bit long keys is 256, which means that if a computer detects one million keys per second, it will take nearly 2285 years for it to search for all keys.

DES is no longer considered a secure encryption algorithm because it uses a 56-bit secret key that is too short to be cracked within 24 hours with modern computing power. Some analysis reports have also pointed out the theoretical weakness of the algorithm, although the actual situation may not appear. This standard has recently been replaced by Advanced Encryption Standard (AES).

 

AES

Advanced Encryption Standard (AES), also known as Rijndael Encryption, is a block encryption standard adopted by the Federal Government of the United States. This standard, which replaces the original DES, has been analyzed by many parties and is widely used all over the world. After five years of selection process, Advanced Encryption Standard was issued by the National Institute of Standards and Technology (NIST) in FIPS PUB 197 on November 26, 2001, and became an effective standard on May 26, 2002. In 2006, Advanced Encryption Standard has become one of the most popular algorithms in symmetric key encryption.

The block length of AES is fixed at 128 bits, and the key length can be 128, 192 or 256 bits.

 

RSA

RSA encryption algorithm is an asymmetric encryption algorithm. RSA is widely used in public key encryption standards and electronic commerce. RSA was proposed by Ron Rivest, Adi Shamir and Leonard Adleman in 1977. At that time, all three of them worked at MIT. RSA is a combination of the initial letters of their three surnames.

The reliability of RSA algorithm based on decomposition of large integers is very difficult. If someone finds a fast decomposition factor algorithm, then the reliability of information encrypted with RSA will certainly be greatly reduced. But the possibility of finding such an algorithm is very small. Today, only a short RSA key can be broken in a powerful way. Until 2008, there was no reliable way to attack RSA algorithm in the world. As long as the length of the key is long enough, the information encrypted by RSA can not actually be cracked.

RSA algorithm encrypts by multiplying two large prime numbers. Either of these two prime numbers multiplies the original file code first, and encrypts the file, which can be decrypted by multiplying another prime number. But it is very difficult to find another prime with one prime. Therefore, this pair of prime numbers is called key Pair. When encrypting applications, a user always publishes a key so that the person who needs to send the message can encrypt it with his public key and then send it to the user. Once the information is encrypted, only the private key that the user knows can be decrypted. The public key of a person with digital credential identity can be found on the Internet, and the public key can be transmitted to the other party actively when the other party sends information, so as to ensure the confidentiality and security of the information transmitted on the Internet.

 

This paper uses RSA encryption algorithm to encrypt license information. RSATester.java can be run to generate public and private keys.
RSAUtils.java

  1. import java.io.ByteArrayOutputStream;  
  2. import java.security.Key;  
  3. import java.security.KeyFactory;  
  4. import java.security.KeyPair;  
  5. import java.security.KeyPairGenerator;  
  6. import java.security.PrivateKey;  
  7. import java.security.PublicKey;  
  8. import java.security.Signature;  
  9. import java.security.interfaces.RSAPrivateKey;  
  10. import java.security.interfaces.RSAPublicKey;  
  11. import java.security.spec.PKCS8EncodedKeySpec;  
  12. import java.security.spec.X509EncodedKeySpec;  
  13. import java.util.HashMap;  
  14. import java.util.Map;  
  15.   
  16. import javax.crypto.Cipher;  
  17.   
  18. /** *//** 
  19.  * <p> 
  20.  * RSA Public Key/Private Key/Signature Toolkit 
  21.  * </p> 
  22.  * <p> 
  23.  * Ron [R]ivest, Adi [S]hamir and Leonard [A]dleman 
  24.  * </p> 
  25.  * <p> 
  26.  * The key in string format is BASE64 encoding format < br/> without special description. 
  27.  * Because of the extremely slow speed of asymmetric encryption, ordinary files do not use it to encrypt but use symmetric encryption, <br/>. 
  28.  * Asymmetric encryption algorithm can be used to encrypt symmetric encryption keys, so as to ensure the security of the key and data security. 
  29.  * </p> 
  30.  *  
  31.  * @author IceWee 
  32.  * @date 2012-4-26 
  33.  * @version 1.0 
  34.  */  
  35. public class RSAUtils {  
  36.   
  37.     /** *//** 
  38.      * Encryption algorithm RSA 
  39.      */  
  40.     public static final String KEY_ALGORITHM = "RSA";  
  41.       
  42.     /** *//** 
  43.      * signature algorithm 
  44.      */  
  45.     public static final String SIGNATURE_ALGORITHM = "MD5withRSA";  
  46.   
  47.     /** *//** 
  48.      * The key to obtain the public key 
  49.      */  
  50.     private static final String PUBLIC_KEY = "RSAPublicKey";  
  51.       
  52.     /** *//** 
  53.      * Key to get the private key 
  54.      */  
  55.     private static final String PRIVATE_KEY = "RSAPrivateKey";  
  56.       
  57.     /** *//** 
  58.      * RSA Maximum Encrypted Plaintext Size 
  59.      */  
  60.     private static final int MAX_ENCRYPT_BLOCK = 117;  
  61.       
  62.     /** *//** 
  63.      * RSA Maximum decrypted ciphertext size 
  64.      */  
  65.     private static final int MAX_DECRYPT_BLOCK = 128;  
  66.   
  67.     /** *//** 
  68.      * <p> 
  69.      * Generate key pairs (public and private keys) 
  70.      * </p> 
  71.      *  
  72.      * @return 
  73.      * @throws Exception 
  74.      */  
  75.     public static Map<String, Object> genKeyPair() throws Exception {  
  76.         KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);  
  77.         keyPairGen.initialize(1024);  
  78.         KeyPair keyPair = keyPairGen.generateKeyPair();  
  79.         RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  
  80.         RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();  
  81.         Map<String, Object> keyMap = new HashMap<String, Object>(2);  
  82.         keyMap.put(PUBLIC_KEY, publicKey);  
  83.         keyMap.put(PRIVATE_KEY, privateKey);  
  84.         return keyMap;  
  85.     }  
  86.       
  87.     /** *//** 
  88.      * <p> 
  89.      * Generating Digital Signature with Private Key Pair Information 
  90.      * </p> 
  91.      *  
  92.      * @param data Encrypted data 
  93.      * @param privateKey Private key (BASE64 encoding) 
  94.      *  
  95.      * @return 
  96.      * @throws Exception 
  97.      */  
  98.     public static String sign(byte[] data, String privateKey) throws Exception {  
  99.         byte[] keyBytes = Base64Utils.decode(privateKey);  
  100.         PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);  
  101.         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
  102.         PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);  
  103.         Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);  
  104.         signature.initSign(privateK);  
  105.         signature.update(data);  
  106.         return Base64Utils.encode(signature.sign());  
  107.     }  
  108.   
  109.     /** *//** 
  110.      * <p> 
  111.      * Check Digital Signature 
  112.      * </p> 
  113.      *  
  114.      * @param data Encrypted data 
  115.      * @param publicKey Public key (BASE64 encoding) 
  116.      * @param sign digital signature 
  117.      *  
  118.      * @return 
  119.      * @throws Exception 
  120.      *  
  121.      */  
  122.     public static boolean verify(byte[] data, String publicKey, String sign)  
  123.             throws Exception {  
  124.         byte[] keyBytes = Base64Utils.decode(publicKey);  
  125.         X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);  
  126.         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
  127.         PublicKey publicK = keyFactory.generatePublic(keySpec);  
  128.         Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);  
  129.         signature.initVerify(publicK);  
  130.         signature.update(data);  
  131.         return signature.verify(Base64Utils.decode(sign));  
  132.     }  
  133.   
  134.     /** *//** 
  135.      * <P> 
  136.      * Private key decryption 
  137.      * </p> 
  138.      *  
  139.      * @param encryptedData Encrypted data 
  140.      * @param privateKey Private key (BASE64 encoding) 
  141.      * @return 
  142.      * @throws Exception 
  143.      */  
  144.     public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)  
  145.             throws Exception {  
  146.         byte[] keyBytes = Base64Utils.decode(privateKey);  
  147.         PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);  
  148.         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
  149.         Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);  
  150.         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
  151.         cipher.init(Cipher.DECRYPT_MODE, privateK);  
  152.         int inputLen = encryptedData.length;  
  153.         ByteArrayOutputStream out = new ByteArrayOutputStream();  
  154.         int offSet = 0;  
  155.         byte[] cache;  
  156.         int i = 0;  
  157.         //Sectional decryption of data  
  158.         while (inputLen - offSet > 0) {  
  159.             if (inputLen - offSet > MAX_DECRYPT_BLOCK) {  
  160.                 cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);  
  161.             } else {  
  162.                 cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);  
  163.             }  
  164.             out.write(cache, 0, cache.length);  
  165.             i++;  
  166.             offSet = i * MAX_DECRYPT_BLOCK;  
  167.         }  
  168.         byte[] decryptedData = out.toByteArray();  
  169.         out.close();  
  170.         return decryptedData;  
  171.     }  
  172.   
  173.     /** *//** 
  174.      * <p> 
  175.      * Public key decryption 
  176.      * </p> 
  177.      *  
  178.      * @param encryptedData Encrypted data 
  179.      * @param publicKey Public key (BASE64 encoding) 
  180.      * @return 
  181.      * @throws Exception 
  182.      */  
  183.     public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)  
  184.             throws Exception {  
  185.         byte[] keyBytes = Base64Utils.decode(publicKey);  
  186.         X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);  
  187.         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
  188.         Key publicK = keyFactory.generatePublic(x509KeySpec);  
  189.         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
  190.         cipher.init(Cipher.DECRYPT_MODE, publicK);  
  191.         int inputLen = encryptedData.length;  
  192.         ByteArrayOutputStream out = new ByteArrayOutputStream();  
  193.         int offSet = 0;  
  194.         byte[] cache;  
  195.         int i = 0;  
  196.         //Sectional decryption of data  
  197.         while (inputLen - offSet > 0) {  
  198.             if (inputLen - offSet > MAX_DECRYPT_BLOCK) {  
  199.                 cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);  
  200.             } else {  
  201.                 cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);  
  202.             }  
  203.             out.write(cache, 0, cache.length);  
  204.             i++;  
  205.             offSet = i * MAX_DECRYPT_BLOCK;  
  206.         }  
  207.         byte[] decryptedData = out.toByteArray();  
  208.         out.close();  
  209.         return decryptedData;  
  210.     }  
  211.   
  212.     /** *//** 
  213.      * <p> 
  214.      * Public Key Encryption 
  215.      * </p> 
  216.      *  
  217.      * @param data source data 
  218.      * @param publicKey Public key (BASE64 encoding) 
  219.      * @return 
  220.      * @throws Exception 
  221.      */  
  222.     public static byte[] encryptByPublicKey(byte[] data, String publicKey)  
  223.             throws Exception {  
  224.         byte[] keyBytes = Base64Utils.decode(publicKey);  
  225.         X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);  
  226.         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
  227.         Key publicK = keyFactory.generatePublic(x509KeySpec);  
  228.         //Encryption of data  
  229.         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
  230.         cipher.init(Cipher.ENCRYPT_MODE, publicK);  
  231.         int inputLen = data.length;  
  232.         ByteArrayOutputStream out = new ByteArrayOutputStream();  
  233.         int offSet = 0;  
  234.         byte[] cache;  
  235.         int i = 0;  
  236.         //Sectional Encryption of Data  
  237.         while (inputLen - offSet > 0) {  
  238.             if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {  
  239.                 cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);  
  240.             } else {  
  241.                 cache = cipher.doFinal(data, offSet, inputLen - offSet);  
  242.             }  
  243.             out.write(cache, 0, cache.length);  
  244.             i++;  
  245.             offSet = i * MAX_ENCRYPT_BLOCK;  
  246.         }  
  247.         byte[] encryptedData = out.toByteArray();  
  248.         out.close();  
  249.         return encryptedData;  
  250.     }  
  251.   
  252.     /** *//** 
  253.      * <p> 
  254.      * secret key encryption 
  255.      * </p> 
  256.      *  
  257.      * @param data source data 
  258.      * @param privateKey Private key (BASE64 encoding) 
  259.      * @return 
  260.      * @throws Exception 
  261.      */  
  262.     public static byte[] encryptByPrivateKey(byte[] data, String privateKey)  
  263.             throws Exception {  
  264.         byte[] keyBytes = Base64Utils.decode(privateKey);  
  265.         PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);  
  266.         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
  267.         Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);  
  268.         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());  
  269.         cipher.init(Cipher.ENCRYPT_MODE, privateK);  
  270.         int inputLen = data.length;  
  271.         ByteArrayOutputStream out = new ByteArrayOutputStream();  
  272.         int offSet = 0;  
  273.         byte[] cache;  
  274.         int i = 0;  
  275.         //Sectional Encryption of Data  
  276.         while (inputLen - offSet > 0) {  
  277.             if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {  
  278.                 cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);  
  279.             } else {  
  280.                 cache = cipher.doFinal(data, offSet, inputLen - offSet);  
  281.             }  
  282.             out.write(cache, 0, cache.length);  
  283.             i++;  
  284.             offSet = i * MAX_ENCRYPT_BLOCK;  
  285.         }  
  286.         byte[] encryptedData = out.toByteArray();  
  287.         out.close();  
  288.         return encryptedData;  
  289.     }  
  290.   
  291.     /** *//** 
  292.      * <p> 
  293.      * Get the private key 
  294.      * </p> 
  295.      *  
  296.      * @param keyMap Key pair 
  297.      * @return 
  298.      * @throws Exception 
  299.      */  
  300.     public static String getPrivateKey(Map<String, Object> keyMap)  
  301.             throws Exception {  
  302.         Key key = (Key) keyMap.get(PRIVATE_KEY);  
  303.         return Base64Utils.encode(key.getEncoded());  
  304.     }  
  305.   
  306.     /** *//** 
  307.      * <p> 
  308.      * Get the public key 
  309.      * </p> 
  310.      *  
  311.      * @param keyMap Key pair 
  312.      * @return 
  313.      * @throws Exception 
  314.      */  
  315.     public static String getPublicKey(Map<String, Object> keyMap)  
  316.             throws Exception {  
  317.         Key key = (Key) keyMap.get(PUBLIC_KEY);  
  318.         return Base64Utils.encode(key.getEncoded());  
  319.     }  
  320.   
  321. }  

 

 Base64Utils.java

  1. import java.io.ByteArrayInputStream;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8.   
  9. //import it.sauronsoftware.base64.Base64;  
  10. import sun.misc.BASE64Decoder;  
  11. import sun.misc.BASE64Encoder;  
  12. //If an error is reported, the compilation path removes jdk and adds jdk  
  13.   
  14. /** *//** 
  15.  * <p> 
  16.  * BASE64 Coding and Decoding Toolkit 
  17.  * </p> 
  18.  * <p> 
  19.  * Dependent on javabase64-1.3.1.jar or common-codec 
  20.  * </p> 
  21.  *  
  22.  * @author IceWee 
  23.  * @date 2012-5-19 
  24.  * @version 1.0 
  25.  */  
  26. public class Base64Utils {  
  27.   
  28.     /** *//** 
  29.      * File Read Buffer Size 
  30.      */  
  31.     private static final int CACHE_SIZE = 1024;  
  32.       
  33.     /** *//** 
  34.      * <p> 
  35.      * BASE64 String decoding to binary data 
  36.      * </p> 
  37.      *  
  38.      * @param base64 
  39.      * @return 
  40.      * @throws Exception 
  41.      */  
  42.     public static byte[] decode(String base64) throws Exception {  
  43.         //return Base64.decode(base64.getBytes());  
  44.         return new BASE64Decoder().decodeBuffer(base64);  
  45.     }  
  46.       
  47.     /** *//** 
  48.      * <p> 
  49.      * Binary data is encoded as BASE64 string 
  50.      * </p> 
  51.      *  
  52.      * @param bytes 
  53.      * @return 
  54.      * @throws Exception 
  55.      */  
  56.     public static String encode(byte[] bytes) throws Exception {  
  57.         //return new String(Base64.encode(bytes));  
  58.         return new BASE64Encoder().encode(bytes);  
  59.     }  
  60.       
  61.     /** *//** 
  62.      * <p> 
  63.      * Code the file as a BASE64 string 
  64.      * </p> 
  65.      * <p> 
  66.      * Cautious use of large files may lead to memory overflow 
  67.      * </p> 
  68.      *  
  69.      * @param filePath File absolute path 
  70.      * @return 
  71.      * @throws Exception 
  72.      */  
  73.     public static String encodeFile(String filePath) throws Exception {  
  74.         byte[] bytes = fileToByte(filePath);  
  75.         return encode(bytes);  
  76.     }  
  77.       
  78.     /** *//** 
  79.      * <p> 
  80.      * BASE64 String Return to File 
  81.      * </p> 
  82.      *  
  83.      * @param filePath File absolute path 
  84.      * @param base64 Coded string 
  85.      * @throws Exception 
  86.      */  
  87.     public static void decodeToFile(String filePath, String base64) throws Exception {  
  88.         byte[] bytes = decode(base64);  
  89.         byteArrayToFile(bytes, filePath);  
  90.     }  
  91.       
  92.     /** *//** 
  93.      * <p> 
  94.      * Converting files to binary arrays 
  95.      * </p> 
  96.      *  
  97.      * @param filePath File path 
  98.      * @return 
  99.      * @throws Exception 
  100.      */  
  101.     public static byte[] fileToByte(String filePath) throws Exception {  
  102.         byte[] data = new byte[0];  
  103.         File file = new File(filePath);  
  104.         if (file.exists()) {  
  105.             FileInputStream in = new FileInputStream(file);  
  106.             ByteArrayOutputStream out = new ByteArrayOutputStream(2048);  
  107.             byte[] cache = new byte[CACHE_SIZE];  
  108.             int nRead = 0;  
  109.             while ((nRead = in.read(cache)) != -1) {  
  110.                 out.write(cache, 0, nRead);  
  111.                 out.flush();  
  112.             }  
  113.             out.close();  
  114.             in.close();  
  115.             data = out.toByteArray();  
  116.          }  
  117.         return data;  
  118.     }  
  119.       
  120.     /** *//** 
  121.      * <p> 
  122.      * Binary Data Write File 
  123.      * </p> 
  124.      *  
  125.      * @param bytes binary data 
  126.      * @param filePath File Generation Directory 
  127.      */  
  128.     public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {  
  129.         InputStream in = new ByteArrayInputStream(bytes);     
  130.         File destFile = new File(filePath);  
  131. //        if (!destFile.getParentFile().exists()) {  
  132. //            destFile.getParentFile().mkdirs();  
  133. //        }  
  134.         destFile.createNewFile();  
  135.         OutputStream out = new FileOutputStream(destFile);  
  136.         byte[] cache = new byte[CACHE_SIZE];  
  137.         int nRead = 0;  
  138.         while ((nRead = in.read(cache)) != -1) {     
  139.             out.write(cache, 0, nRead);  
  140.             out.flush();  
  141.         }  
  142.         out.close();  
  143.         in.close();  
  144.     }  
  145.       
  146.       
  147. }  

 

RSATester.java

  1. import java.util.Map;  
  2.   
  3. public class RSATester {  
  4.   
  5.     static String publicKey;  
  6.     static String privateKey;  
  7.   
  8.     static {  
  9.         try {  
  10.             Map<String, Object> keyMap = RSAUtils.genKeyPair();  
  11.             publicKey = RSAUtils.getPublicKey(keyMap);  
  12.             privateKey = RSAUtils.getPrivateKey(keyMap);  
  13.             System.err.println("public key: \n\r" + publicKey);  
  14.             System.err.println("Private key: \n\r" + privateKey);  
  15.         } catch (Exception e) {  
  16.             e.printStackTrace();  
  17.         }  
  18.     }  
  19.       
  20.     public static void main(String[] args) throws Exception {  
  21.         test();  
  22.         testSign();  
  23.     }  
  24.   
  25.     static void test() throws Exception {  
  26.         System.err.println("Public Key Encryption-Private Key Decryption");  
  27.         String source = "It's a line of meaningless words. You can't read it after you've read it, can't you?";  
  28.         System.out.println("\r Pre-encrypted text:\r\n" + source);  
  29.         byte[] data = source.getBytes();  
  30.         byte[] encodedData = RSAUtils.encryptByPublicKey(data, publicKey);  
  31.         System.out.println("Encrypted text:\r\n" + new String(encodedData));  
  32.         byte[] decodedData = RSAUtils.decryptByPrivateKey(encodedData, privateKey);  
  33.         String target = new String(decodedData);  
  34.         System.out.println("Decrypted text: \r\n" + target);  
  35.     }  
  36.   
  37.     static void testSign() throws Exception {  
  38.         System.err.println("Private Key Encryption-Public Key Decryption");  
  39.         String source = "This is a one-line test. RSA Meaningless text of digital signature";  
  40.         System.out.println("Original text:\r\n" + source);  
  41.         byte[] data = source.getBytes();  
  42.         byte[] encodedData = RSAUtils.encryptByPrivateKey(data, privateKey);  
  43.         System.out.println("After encryption:\r\n" + new String(encodedData));  
  44.         byte[] decodedData = RSAUtils.decryptByPublicKey(encodedData, publicKey);  
  45.         String target = new String(decodedData);  
  46.         System.out.println("After decryption: \r\n" + target);  
  47.         System.err.println("Private Key Signature-Public Key Verification Signature");  
  48.         String sign = RSAUtils.sign(encodedData, privateKey);  
  49.         System.err.println("autograph:\r" + sign);  
  50.         boolean status = RSAUtils.verify(encodedData, publicKey, sign);  
  51.         System.err.println("Verification results:\r" + status);  
  52.     }  
  53.       
  54. }  

 

Running such a generated license

LicenseGenerator.java

  1. import java.io.File;  
  2.   
  3. /** 
  4.  * Generating license 
  5.  * @author happyqing 
  6.  * 2014.6.15 
  7.  */  
  8. public class LicenseGenerator {  
  9.       
  10.     /** 
  11.      * serial: Provided by customers 
  12.      * timeEnd: Expiration time 
  13.      */  
  14.     private static String licensestatic = "serial=568b8fa5cdfd8a2623bda1d8ab7b7b34;" +  
  15.                                           "timeEnd=1404057600000";  
  16.       
  17.     private static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCaa8y9g+ioR2OSs8njT5uCGWm0YmOA1elSu/P5\n"  
  18.             + "D3XYPCHsUPab74V5Og+NEZeTk9/LtG+jPSpKekTWm67gS2lQYWoygTwnoWsr4woaqNXmWw7L8Ty0\n"  
  19.             + "LQFTojZgyynvu2RSIJp4c76z6SV/khiP/ireGtt8uzXPswPO5uaPU38tQQIDAQAB";  
  20.       
  21.     /** 
  22.      * RSA algorithm 
  23.      * The public key and the private key are a pair. Here, only the private key is used for encryption. 
  24.      */  
  25.     public static final String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJprzL2D6KhHY5KzyeNPm4IZabRi\n"  
  26.             + "Y4DV6VK78/kPddg8IexQ9pvvhXk6D40Rl5OT38u0b6M9Kkp6RNabruBLaVBhajKBPCehayvjChqo\n"  
  27.             + "1eZbDsvxPLQtAVOiNmDLKe+7ZFIgmnhzvrPpJX+SGI/+Kt4a23y7Nc+zA87m5o9Tfy1BAgMBAAEC\n"  
  28.             + "gYAVnlfohEoTHQN0q1TtTNzRhutEhK23gLsMiSGr0Z1G64w4QFF2HT9LbHR25GqbD426QAWNDegY\n"  
  29.             + "yytN/DesUQJqNXx8vuEuqs7+MQDgKgJqpAx+Fg3Iwsk/SVjq7meaSVGCgPKhtWHJk5oXoRMpsrlT\n"  
  30.             + "AwUjpdpAZXIIKW3mrqkW0QJBANq4INw6lZlqRFtxT4uzYQYtzmB/nxMnCbL2SQ4ZQ/4CWlQpOnR/\n"  
  31.             + "mH2JxIBCVtTADFlPM0DWF4aoqykYs9tu2X0CQQC0vgEk8DpkQbh1kgIyBGWCqYSKISTSXia0rbYo\n"  
  32.             + "FPnzdldgtZVirNGNmiJGL8RPz0YKpZNOg9FLHq/oYXSNFI4VAkAJ4OcbC0pWc4ZC2wtMs/1d2hPI\n"  
  33.             + "J/t3UfwOKTGDgYCgqFqMEpChUmIAyYgmgtiJI2NrZThbZVAKtPOGF6eH8anBAkAbxkL4wS3H8E1/\n"  
  34.             + "S7OoqgJLZO9oJpW4+hzqkPM4D5klb58Xzm+pXTNKllAEBx0cwpZZ1n3fh+Qmrg2MIUW+1FTNAkBt\n"  
  35.             + "WECowLUqW014M96WsFpiof7kjteOBNOjFyxhIbx2eT7//bnrADfq2Xu1/mSedUKrjGr/O+FRi7PO\n"  
  36.             + "u7WhF6C9";  
  37.       
  38.     public static void generator() throws Exception {  
  39.         System.err.println("Private Key Encryption-Public Key Decryption");  
  40.         //String source = "568b8fa5cdfd8a2623bda1d8ab7b7b34";  
  41.         System.out.println("Original text:\r\n" + licensestatic);  
  42.         byte[] data = licensestatic.getBytes();  
  43.         byte[] encodedData = RSAUtils.encryptByPrivateKey(data, privateKey);  
  44.         System.out.println("After encryption:\r\n" + new String(encodedData)); //Encrypted scrambling is normal  
  45.           
  46.         Base64Utils.byteArrayToFile(encodedData, FileUtil.getBasePath()+File.separator+"license.dat");  
  47.         System.out.println("license.dat: \r\n" + FileUtil.getBasePath()+File.separator+"license.dat");  
  48.           
  49.         //Decrypt  
  50.         byte[] decodedData = RSAUtils.decryptByPublicKey(encodedData, publicKey);  
  51.         String target = new String(decodedData);  
  52.         System.out.println("After decryption: \r\n" + target);  
  53.     }  
  54.       
  55.     public static void main(String[] args) throws Exception {  
  56.         generator();  
  57.     }  
  58. }  
  59.    

The decryption logic is also put here. In fact, the public key and the decryption logic should be put in the place where the software runs.


FileUtil.java

  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileNotFoundException;  
  4. import java.io.IOException;  
  5. import java.io.UnsupportedEncodingException;  
  6. import java.net.URLDecoder;  
  7. import java.util.logging.Level;  
  8. import java.util.logging.Logger;  
  9.   
  10. /** 
  11.  * File Tool Class 
  12.  * @author happyqing 
  13.  */  
  14. public class FileUtil {  
  15.       
  16.     /** 
  17.      * Get the base path of the class, jar package can also get the path correctly 
  18.      * @return  
  19.      */  
  20.     public static String getBasePath(){  
  21.         /* 
  22.         /D:/zhao/Documents/NetBeansProjects/docCompare/build/classes/ 
  23.         /D:/zhao/Documents/NetBeansProjects/docCompare/dist/bundles/docCompare/app/docCompare.jar 
  24.         */  
  25.         String filePath = FileUtil.class.getProtectionDomain().getCodeSource().getLocation().getFile();  
  26.           
  27.           
  28.         if (filePath.endsWith(".jar")){  
  29.             filePath = filePath.substring(0, filePath.lastIndexOf("/"));  
  30.             try {  
  31.                 filePath = URLDecoder.decode(filePath, "UTF-8"); //Solve the problem of space% 20 in the path  
  32.             } catch (UnsupportedEncodingException ex) {  
  33.   
  34.             }  
  35.   
  36.         }  
  37.         File file = new File(filePath);  
  38.         filePath = file.getAbsolutePath();  
  39.         return filePath;  
  40.     }  
  41.       
  42.     public static void main(String[] args) throws Exception {  
  43.         System.out.println(getBasePath());  
  44.     }  
  45. }  

 

serial is provided where the software runs.

Pure java obtains CPU serial number and generates machine code

http://happyqing.iteye.com/blog/2080402

 

Reference resources

http://www.blogjava.net/icewee/archive/2012/05/19/378570.html

 

A Simple RSA Encryption Class

http://yuncode.net/code/c_5049f78253ad762

RSAEncrypt.java

  1. import java.security.KeyPair;  
  2. import java.security.KeyPairGenerator;  
  3. import java.security.interfaces.RSAPrivateKey;  
  4. import java.security.interfaces.RSAPublicKey;  
  5. import javax.crypto.Cipher;  
  6.   
  7. /** 
  8.  * RSA Encryption class 
  9.  */  
  10. public class RSAEncrypt {  
  11.     public static void main(String[] args) {  
  12.         try {  
  13.             RSAEncrypt encrypt = new RSAEncrypt();  
  14.             String encryptText = "12345678";  
  15.             KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");  
  16.             keyPairGen.initialize(1024);  
  17.             KeyPair keyPair = keyPairGen.generateKeyPair();  
  18.               
  19.             // Generate keys  
  20.             RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); //Private key  
  21.             RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); //Public key  
  22.             byte[] e = encrypt.encrypt(publicKey, encryptText.getBytes());  
  23.             byte[] de = encrypt.decrypt(privateKey, e);  
  24.             System.out.println(encrypt.bytesToString(e));  
  25.             System.out.println();  
  26.             System.out.println(encrypt.bytesToString(de));  
  27.         } catch (Exception e) {  
  28.             e.printStackTrace();  
  29.         }  
  30.     }  
  31.   
  32.     /** 
  33.      * byte Array to string 
  34.      * @param encrytpByte 
  35.      * @return 
  36.      */  
  37.     protected String bytesToString(byte[] encrytpByte) {  
  38.         String result = "";  
  39.         for (Byte bytes : encrytpByte) {  
  40.             result += (char) bytes.intValue();  
  41.         }  
  42.         return result;  
  43.     }  
  44.   
  45.     /** 
  46.      * Encryption Method 
  47.      * @param publicKey 
  48.      * @param obj 
  49.      * @return 
  50.      */  
  51.     protected byte[] encrypt(RSAPublicKey publicKey, byte[] obj) {  
  52.         if (publicKey != null) {  
  53.             try {  
  54.                 Cipher cipher = Cipher.getInstance("RSA");  
  55.                 cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
  56.                 return cipher.doFinal(obj);  
  57.             } catch (Exception e) {  
  58.                 e.printStackTrace();  
  59.             }  
  60.         }  
  61.         return null;  
  62.     }  
  63.   
  64.     /** 
  65.      * Decryption method 
  66.      * @param privateKey 
  67.      * @param obj 
  68.      * @return 
  69.      */  
  70.     protected byte[] decrypt(RSAPrivateKey privateKey, byte[] obj) {  
  71.         if (privateKey != null) {  
  72.             try {  
  73.                 Cipher cipher = Cipher.getInstance("RSA");  
  74.                 cipher.init(Cipher.DECRYPT_MODE, privateKey);  
  75.                 return cipher.doFinal(obj);  
  76.             } catch (Exception e) {  
  77.                 e.printStackTrace();  
  78.             }  
  79.         }  
  80.         return null;  
  81.     }  
  82. }  

 

Explain:

The public key and private key should be generated by themselves and not copied by others.

Over

Posted by Kenwio on Sun, 16 Jun 2019 14:12:59 -0700