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
- import java.io.ByteArrayOutputStream;
- import java.security.Key;
- import java.security.KeyFactory;
- import java.security.KeyPair;
- import java.security.KeyPairGenerator;
- import java.security.PrivateKey;
- import java.security.PublicKey;
- import java.security.Signature;
- import java.security.interfaces.RSAPrivateKey;
- import java.security.interfaces.RSAPublicKey;
- import java.security.spec.PKCS8EncodedKeySpec;
- import java.security.spec.X509EncodedKeySpec;
- import java.util.HashMap;
- import java.util.Map;
- import javax.crypto.Cipher;
- /** *//**
- * <p>
- * RSA Public Key/Private Key/Signature Toolkit
- * </p>
- * <p>
- * Ron [R]ivest, Adi [S]hamir and Leonard [A]dleman
- * </p>
- * <p>
- * The key in string format is BASE64 encoding format < br/> without special description.
- * Because of the extremely slow speed of asymmetric encryption, ordinary files do not use it to encrypt but use symmetric encryption, <br/>.
- * Asymmetric encryption algorithm can be used to encrypt symmetric encryption keys, so as to ensure the security of the key and data security.
- * </p>
- *
- * @author IceWee
- * @date 2012-4-26
- * @version 1.0
- */
- public class RSAUtils {
- /** *//**
- * Encryption algorithm RSA
- */
- public static final String KEY_ALGORITHM = "RSA";
- /** *//**
- * signature algorithm
- */
- public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
- /** *//**
- * The key to obtain the public key
- */
- private static final String PUBLIC_KEY = "RSAPublicKey";
- /** *//**
- * Key to get the private key
- */
- private static final String PRIVATE_KEY = "RSAPrivateKey";
- /** *//**
- * RSA Maximum Encrypted Plaintext Size
- */
- private static final int MAX_ENCRYPT_BLOCK = 117;
- /** *//**
- * RSA Maximum decrypted ciphertext size
- */
- private static final int MAX_DECRYPT_BLOCK = 128;
- /** *//**
- * <p>
- * Generate key pairs (public and private keys)
- * </p>
- *
- * @return
- * @throws Exception
- */
- public static Map<String, Object> genKeyPair() throws Exception {
- KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
- keyPairGen.initialize(1024);
- KeyPair keyPair = keyPairGen.generateKeyPair();
- RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
- RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
- Map<String, Object> keyMap = new HashMap<String, Object>(2);
- keyMap.put(PUBLIC_KEY, publicKey);
- keyMap.put(PRIVATE_KEY, privateKey);
- return keyMap;
- }
- /** *//**
- * <p>
- * Generating Digital Signature with Private Key Pair Information
- * </p>
- *
- * @param data Encrypted data
- * @param privateKey Private key (BASE64 encoding)
- *
- * @return
- * @throws Exception
- */
- public static String sign(byte[] data, String privateKey) throws Exception {
- byte[] keyBytes = Base64Utils.decode(privateKey);
- PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
- KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
- PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
- Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
- signature.initSign(privateK);
- signature.update(data);
- return Base64Utils.encode(signature.sign());
- }
- /** *//**
- * <p>
- * Check Digital Signature
- * </p>
- *
- * @param data Encrypted data
- * @param publicKey Public key (BASE64 encoding)
- * @param sign digital signature
- *
- * @return
- * @throws Exception
- *
- */
- public static boolean verify(byte[] data, String publicKey, String sign)
- throws Exception {
- byte[] keyBytes = Base64Utils.decode(publicKey);
- X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
- KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
- PublicKey publicK = keyFactory.generatePublic(keySpec);
- Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
- signature.initVerify(publicK);
- signature.update(data);
- return signature.verify(Base64Utils.decode(sign));
- }
- /** *//**
- * <P>
- * Private key decryption
- * </p>
- *
- * @param encryptedData Encrypted data
- * @param privateKey Private key (BASE64 encoding)
- * @return
- * @throws Exception
- */
- public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)
- throws Exception {
- byte[] keyBytes = Base64Utils.decode(privateKey);
- PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
- KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
- Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
- Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
- cipher.init(Cipher.DECRYPT_MODE, privateK);
- int inputLen = encryptedData.length;
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- int offSet = 0;
- byte[] cache;
- int i = 0;
- //Sectional decryption of data
- while (inputLen - offSet > 0) {
- if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
- cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
- } else {
- cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
- }
- out.write(cache, 0, cache.length);
- i++;
- offSet = i * MAX_DECRYPT_BLOCK;
- }
- byte[] decryptedData = out.toByteArray();
- out.close();
- return decryptedData;
- }
- /** *//**
- * <p>
- * Public key decryption
- * </p>
- *
- * @param encryptedData Encrypted data
- * @param publicKey Public key (BASE64 encoding)
- * @return
- * @throws Exception
- */
- public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)
- throws Exception {
- byte[] keyBytes = Base64Utils.decode(publicKey);
- X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
- KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
- Key publicK = keyFactory.generatePublic(x509KeySpec);
- Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
- cipher.init(Cipher.DECRYPT_MODE, publicK);
- int inputLen = encryptedData.length;
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- int offSet = 0;
- byte[] cache;
- int i = 0;
- //Sectional decryption of data
- while (inputLen - offSet > 0) {
- if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
- cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
- } else {
- cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
- }
- out.write(cache, 0, cache.length);
- i++;
- offSet = i * MAX_DECRYPT_BLOCK;
- }
- byte[] decryptedData = out.toByteArray();
- out.close();
- return decryptedData;
- }
- /** *//**
- * <p>
- * Public Key Encryption
- * </p>
- *
- * @param data source data
- * @param publicKey Public key (BASE64 encoding)
- * @return
- * @throws Exception
- */
- public static byte[] encryptByPublicKey(byte[] data, String publicKey)
- throws Exception {
- byte[] keyBytes = Base64Utils.decode(publicKey);
- X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
- KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
- Key publicK = keyFactory.generatePublic(x509KeySpec);
- //Encryption of data
- Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
- cipher.init(Cipher.ENCRYPT_MODE, publicK);
- int inputLen = data.length;
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- int offSet = 0;
- byte[] cache;
- int i = 0;
- //Sectional Encryption of Data
- while (inputLen - offSet > 0) {
- if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
- cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
- } else {
- cache = cipher.doFinal(data, offSet, inputLen - offSet);
- }
- out.write(cache, 0, cache.length);
- i++;
- offSet = i * MAX_ENCRYPT_BLOCK;
- }
- byte[] encryptedData = out.toByteArray();
- out.close();
- return encryptedData;
- }
- /** *//**
- * <p>
- * secret key encryption
- * </p>
- *
- * @param data source data
- * @param privateKey Private key (BASE64 encoding)
- * @return
- * @throws Exception
- */
- public static byte[] encryptByPrivateKey(byte[] data, String privateKey)
- throws Exception {
- byte[] keyBytes = Base64Utils.decode(privateKey);
- PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
- KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
- Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
- Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
- cipher.init(Cipher.ENCRYPT_MODE, privateK);
- int inputLen = data.length;
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- int offSet = 0;
- byte[] cache;
- int i = 0;
- //Sectional Encryption of Data
- while (inputLen - offSet > 0) {
- if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
- cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
- } else {
- cache = cipher.doFinal(data, offSet, inputLen - offSet);
- }
- out.write(cache, 0, cache.length);
- i++;
- offSet = i * MAX_ENCRYPT_BLOCK;
- }
- byte[] encryptedData = out.toByteArray();
- out.close();
- return encryptedData;
- }
- /** *//**
- * <p>
- * Get the private key
- * </p>
- *
- * @param keyMap Key pair
- * @return
- * @throws Exception
- */
- public static String getPrivateKey(Map<String, Object> keyMap)
- throws Exception {
- Key key = (Key) keyMap.get(PRIVATE_KEY);
- return Base64Utils.encode(key.getEncoded());
- }
- /** *//**
- * <p>
- * Get the public key
- * </p>
- *
- * @param keyMap Key pair
- * @return
- * @throws Exception
- */
- public static String getPublicKey(Map<String, Object> keyMap)
- throws Exception {
- Key key = (Key) keyMap.get(PUBLIC_KEY);
- return Base64Utils.encode(key.getEncoded());
- }
- }
Base64Utils.java
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.InputStream;
- import java.io.OutputStream;
- //import it.sauronsoftware.base64.Base64;
- import sun.misc.BASE64Decoder;
- import sun.misc.BASE64Encoder;
- //If an error is reported, the compilation path removes jdk and adds jdk
- /** *//**
- * <p>
- * BASE64 Coding and Decoding Toolkit
- * </p>
- * <p>
- * Dependent on javabase64-1.3.1.jar or common-codec
- * </p>
- *
- * @author IceWee
- * @date 2012-5-19
- * @version 1.0
- */
- public class Base64Utils {
- /** *//**
- * File Read Buffer Size
- */
- private static final int CACHE_SIZE = 1024;
- /** *//**
- * <p>
- * BASE64 String decoding to binary data
- * </p>
- *
- * @param base64
- * @return
- * @throws Exception
- */
- public static byte[] decode(String base64) throws Exception {
- //return Base64.decode(base64.getBytes());
- return new BASE64Decoder().decodeBuffer(base64);
- }
- /** *//**
- * <p>
- * Binary data is encoded as BASE64 string
- * </p>
- *
- * @param bytes
- * @return
- * @throws Exception
- */
- public static String encode(byte[] bytes) throws Exception {
- //return new String(Base64.encode(bytes));
- return new BASE64Encoder().encode(bytes);
- }
- /** *//**
- * <p>
- * Code the file as a BASE64 string
- * </p>
- * <p>
- * Cautious use of large files may lead to memory overflow
- * </p>
- *
- * @param filePath File absolute path
- * @return
- * @throws Exception
- */
- public static String encodeFile(String filePath) throws Exception {
- byte[] bytes = fileToByte(filePath);
- return encode(bytes);
- }
- /** *//**
- * <p>
- * BASE64 String Return to File
- * </p>
- *
- * @param filePath File absolute path
- * @param base64 Coded string
- * @throws Exception
- */
- public static void decodeToFile(String filePath, String base64) throws Exception {
- byte[] bytes = decode(base64);
- byteArrayToFile(bytes, filePath);
- }
- /** *//**
- * <p>
- * Converting files to binary arrays
- * </p>
- *
- * @param filePath File path
- * @return
- * @throws Exception
- */
- public static byte[] fileToByte(String filePath) throws Exception {
- byte[] data = new byte[0];
- File file = new File(filePath);
- if (file.exists()) {
- FileInputStream in = new FileInputStream(file);
- ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
- byte[] cache = new byte[CACHE_SIZE];
- int nRead = 0;
- while ((nRead = in.read(cache)) != -1) {
- out.write(cache, 0, nRead);
- out.flush();
- }
- out.close();
- in.close();
- data = out.toByteArray();
- }
- return data;
- }
- /** *//**
- * <p>
- * Binary Data Write File
- * </p>
- *
- * @param bytes binary data
- * @param filePath File Generation Directory
- */
- public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
- InputStream in = new ByteArrayInputStream(bytes);
- File destFile = new File(filePath);
- // if (!destFile.getParentFile().exists()) {
- // destFile.getParentFile().mkdirs();
- // }
- destFile.createNewFile();
- OutputStream out = new FileOutputStream(destFile);
- byte[] cache = new byte[CACHE_SIZE];
- int nRead = 0;
- while ((nRead = in.read(cache)) != -1) {
- out.write(cache, 0, nRead);
- out.flush();
- }
- out.close();
- in.close();
- }
- }
RSATester.java
- import java.util.Map;
- public class RSATester {
- static String publicKey;
- static String privateKey;
- static {
- try {
- Map<String, Object> keyMap = RSAUtils.genKeyPair();
- publicKey = RSAUtils.getPublicKey(keyMap);
- privateKey = RSAUtils.getPrivateKey(keyMap);
- System.err.println("public key: \n\r" + publicKey);
- System.err.println("Private key: \n\r" + privateKey);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static void main(String[] args) throws Exception {
- test();
- testSign();
- }
- static void test() throws Exception {
- System.err.println("Public Key Encryption-Private Key Decryption");
- String source = "It's a line of meaningless words. You can't read it after you've read it, can't you?";
- System.out.println("\r Pre-encrypted text:\r\n" + source);
- byte[] data = source.getBytes();
- byte[] encodedData = RSAUtils.encryptByPublicKey(data, publicKey);
- System.out.println("Encrypted text:\r\n" + new String(encodedData));
- byte[] decodedData = RSAUtils.decryptByPrivateKey(encodedData, privateKey);
- String target = new String(decodedData);
- System.out.println("Decrypted text: \r\n" + target);
- }
- static void testSign() throws Exception {
- System.err.println("Private Key Encryption-Public Key Decryption");
- String source = "This is a one-line test. RSA Meaningless text of digital signature";
- System.out.println("Original text:\r\n" + source);
- byte[] data = source.getBytes();
- byte[] encodedData = RSAUtils.encryptByPrivateKey(data, privateKey);
- System.out.println("After encryption:\r\n" + new String(encodedData));
- byte[] decodedData = RSAUtils.decryptByPublicKey(encodedData, publicKey);
- String target = new String(decodedData);
- System.out.println("After decryption: \r\n" + target);
- System.err.println("Private Key Signature-Public Key Verification Signature");
- String sign = RSAUtils.sign(encodedData, privateKey);
- System.err.println("autograph:\r" + sign);
- boolean status = RSAUtils.verify(encodedData, publicKey, sign);
- System.err.println("Verification results:\r" + status);
- }
- }
Running such a generated license
LicenseGenerator.java
- import java.io.File;
- /**
- * Generating license
- * @author happyqing
- * 2014.6.15
- */
- public class LicenseGenerator {
- /**
- * serial: Provided by customers
- * timeEnd: Expiration time
- */
- private static String licensestatic = "serial=568b8fa5cdfd8a2623bda1d8ab7b7b34;" +
- "timeEnd=1404057600000";
- private static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCaa8y9g+ioR2OSs8njT5uCGWm0YmOA1elSu/P5\n"
- + "D3XYPCHsUPab74V5Og+NEZeTk9/LtG+jPSpKekTWm67gS2lQYWoygTwnoWsr4woaqNXmWw7L8Ty0\n"
- + "LQFTojZgyynvu2RSIJp4c76z6SV/khiP/ireGtt8uzXPswPO5uaPU38tQQIDAQAB";
- /**
- * RSA algorithm
- * The public key and the private key are a pair. Here, only the private key is used for encryption.
- */
- public static final String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJprzL2D6KhHY5KzyeNPm4IZabRi\n"
- + "Y4DV6VK78/kPddg8IexQ9pvvhXk6D40Rl5OT38u0b6M9Kkp6RNabruBLaVBhajKBPCehayvjChqo\n"
- + "1eZbDsvxPLQtAVOiNmDLKe+7ZFIgmnhzvrPpJX+SGI/+Kt4a23y7Nc+zA87m5o9Tfy1BAgMBAAEC\n"
- + "gYAVnlfohEoTHQN0q1TtTNzRhutEhK23gLsMiSGr0Z1G64w4QFF2HT9LbHR25GqbD426QAWNDegY\n"
- + "yytN/DesUQJqNXx8vuEuqs7+MQDgKgJqpAx+Fg3Iwsk/SVjq7meaSVGCgPKhtWHJk5oXoRMpsrlT\n"
- + "AwUjpdpAZXIIKW3mrqkW0QJBANq4INw6lZlqRFtxT4uzYQYtzmB/nxMnCbL2SQ4ZQ/4CWlQpOnR/\n"
- + "mH2JxIBCVtTADFlPM0DWF4aoqykYs9tu2X0CQQC0vgEk8DpkQbh1kgIyBGWCqYSKISTSXia0rbYo\n"
- + "FPnzdldgtZVirNGNmiJGL8RPz0YKpZNOg9FLHq/oYXSNFI4VAkAJ4OcbC0pWc4ZC2wtMs/1d2hPI\n"
- + "J/t3UfwOKTGDgYCgqFqMEpChUmIAyYgmgtiJI2NrZThbZVAKtPOGF6eH8anBAkAbxkL4wS3H8E1/\n"
- + "S7OoqgJLZO9oJpW4+hzqkPM4D5klb58Xzm+pXTNKllAEBx0cwpZZ1n3fh+Qmrg2MIUW+1FTNAkBt\n"
- + "WECowLUqW014M96WsFpiof7kjteOBNOjFyxhIbx2eT7//bnrADfq2Xu1/mSedUKrjGr/O+FRi7PO\n"
- + "u7WhF6C9";
- public static void generator() throws Exception {
- System.err.println("Private Key Encryption-Public Key Decryption");
- //String source = "568b8fa5cdfd8a2623bda1d8ab7b7b34";
- System.out.println("Original text:\r\n" + licensestatic);
- byte[] data = licensestatic.getBytes();
- byte[] encodedData = RSAUtils.encryptByPrivateKey(data, privateKey);
- System.out.println("After encryption:\r\n" + new String(encodedData)); //Encrypted scrambling is normal
- Base64Utils.byteArrayToFile(encodedData, FileUtil.getBasePath()+File.separator+"license.dat");
- System.out.println("license.dat: \r\n" + FileUtil.getBasePath()+File.separator+"license.dat");
- //Decrypt
- byte[] decodedData = RSAUtils.decryptByPublicKey(encodedData, publicKey);
- String target = new String(decodedData);
- System.out.println("After decryption: \r\n" + target);
- }
- public static void main(String[] args) throws Exception {
- generator();
- }
- }
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
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import java.net.URLDecoder;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- /**
- * File Tool Class
- * @author happyqing
- */
- public class FileUtil {
- /**
- * Get the base path of the class, jar package can also get the path correctly
- * @return
- */
- public static String getBasePath(){
- /*
- /D:/zhao/Documents/NetBeansProjects/docCompare/build/classes/
- /D:/zhao/Documents/NetBeansProjects/docCompare/dist/bundles/docCompare/app/docCompare.jar
- */
- String filePath = FileUtil.class.getProtectionDomain().getCodeSource().getLocation().getFile();
- if (filePath.endsWith(".jar")){
- filePath = filePath.substring(0, filePath.lastIndexOf("/"));
- try {
- filePath = URLDecoder.decode(filePath, "UTF-8"); //Solve the problem of space% 20 in the path
- } catch (UnsupportedEncodingException ex) {
- }
- }
- File file = new File(filePath);
- filePath = file.getAbsolutePath();
- return filePath;
- }
- public static void main(String[] args) throws Exception {
- System.out.println(getBasePath());
- }
- }
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
- import java.security.KeyPair;
- import java.security.KeyPairGenerator;
- import java.security.interfaces.RSAPrivateKey;
- import java.security.interfaces.RSAPublicKey;
- import javax.crypto.Cipher;
- /**
- * RSA Encryption class
- */
- public class RSAEncrypt {
- public static void main(String[] args) {
- try {
- RSAEncrypt encrypt = new RSAEncrypt();
- String encryptText = "12345678";
- KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
- keyPairGen.initialize(1024);
- KeyPair keyPair = keyPairGen.generateKeyPair();
- // Generate keys
- RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); //Private key
- RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); //Public key
- byte[] e = encrypt.encrypt(publicKey, encryptText.getBytes());
- byte[] de = encrypt.decrypt(privateKey, e);
- System.out.println(encrypt.bytesToString(e));
- System.out.println();
- System.out.println(encrypt.bytesToString(de));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * byte Array to string
- * @param encrytpByte
- * @return
- */
- protected String bytesToString(byte[] encrytpByte) {
- String result = "";
- for (Byte bytes : encrytpByte) {
- result += (char) bytes.intValue();
- }
- return result;
- }
- /**
- * Encryption Method
- * @param publicKey
- * @param obj
- * @return
- */
- protected byte[] encrypt(RSAPublicKey publicKey, byte[] obj) {
- if (publicKey != null) {
- try {
- Cipher cipher = Cipher.getInstance("RSA");
- cipher.init(Cipher.ENCRYPT_MODE, publicKey);
- return cipher.doFinal(obj);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return null;
- }
- /**
- * Decryption method
- * @param privateKey
- * @param obj
- * @return
- */
- protected byte[] decrypt(RSAPrivateKey privateKey, byte[] obj) {
- if (privateKey != null) {
- try {
- Cipher cipher = Cipher.getInstance("RSA");
- cipher.init(Cipher.DECRYPT_MODE, privateKey);
- return cipher.doFinal(obj);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return null;
- }
- }
Explain:
The public key and private key should be generated by themselves and not copied by others.
Over