Java data security practice of MD5, RSA and custom signature

foreword

In the modern digital world, the security and integrity of data has become even more important. In order to ensure that data is not attacked during transmission and storage, we can use various encryption and signature technologies to strengthen data security. This article will introduce how to use MD5, RSA encryption, and how to customize signature rules to protect data security. The following describes how to combine MD5, RSA encryption and custom signature rules to realize secure transmission and verification of Java data.

1. Add pom.xml dependency

<dependencies>
    <!-- Apache Commons Codec for MD5 hashing -->
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.15</version>
    </dependency>

    <!-- Bouncy Castle for RSA encryption -->
    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcprov-jdk15on</artifactId>
        <version>1.68</version>
    </dependency>
</dependencies>

2. MD5 encryption and verification of data integrity

MD5 (Message Digest Algorithm 5) is a hash function used to generate a fixed-length digest of input data. We can hash the data using MD5 and send the digest along with the original data. After receiving the data, the receiver also performs MD5 hashing, and then compares whether the digests are consistent to verify the integrity of the data. Here is an example of MD5 encryption and authentication using Java:

import org.apache.commons.codec.digest.DigestUtils;

public class MD5Example {
    
    

    public static void main(String[] args) {
    
    
        // 要进行哈希的数据
        String data = "Hello, MD5!";
        
        // 自定义的盐值
        String salt = "mySecretSalt";

        // 生成 MD5 哈希值
        String hashedData = DigestUtils.md5Hex(data + salt);
        System.out.println("Hashed Data: " + hashedData);
    }
}

3. RSA encrypts and decrypts sensitive data

RSA (Rivest–Shamir–Adleman) is an asymmetric encryption algorithm that uses a pair of public and private keys for encryption and decryption. RSA is not only used for data protection, but also for digital signatures to ensure data integrity and authentication. Here is an example of RSA encryption and decryption using Java:

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;

import javax.crypto.Cipher;

public class RSAExample {
    
    

    public static void main(String[] args) throws Exception {
    
    
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        String message = "Hello, RSA!";
        byte[] encrypted = encrypt(publicKey, message);
   		// 将字节数组转换为十六进制字符串(为了打印不乱码)
		String encryptedHex = bytesToHex(encrypted);
		System.out.println("Encrypted message: " + encryptedHex);
		
        String decrypted = decrypt(privateKey, encrypted);
        System.out.println("Decrypted message: " + decrypted);
    }
    
	/**
	 * 将字节数组转换为十六进制字符串的辅助方法
	 *
	 * @param bytes 要转换的字节数组
	 * @return 转换后的十六进制字符串
	 */
	public static String bytesToHex(byte[] bytes) {
    
    
	    StringBuilder result = new StringBuilder();
	    for (byte b : bytes) {
    
    
	        result.append(String.format("%02x", b));
	    }
	    return result.toString();
	}


    /**
     * 使用公钥加密敏感数据
     *
     * @param publicKey 用于加密的公钥
     * @param message   要加密的数据
     * @return 加密后的数据
     * @throws Exception 加密过程中的异常
     */
    public static byte[] encrypt(PublicKey publicKey, String message) throws Exception {
    
    
        // 使用 RSA/ECB/PKCS1Padding 和 Bouncy Castle 提供的加密方式
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(message.getBytes());
    }

    /**
     * 使用私钥解密加密的数据
     *
     * @param privateKey 用于解密的私钥
     * @param encrypted  加密的数据
     * @return 解密后的数据
     * @throws Exception 解密过程中的异常
     */
    public static String decrypt(PrivateKey privateKey, byte[] encrypted) throws Exception {
    
    
        // 使用 RSA/ECB/PKCS1Padding 和 Bouncy Castle 提供的加密方式
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(encrypted);
        return new String(decryptedBytes);
    }
}

Please add a picture description

4. Customize signature rules to strengthen data verification

In addition to MD5 and RSA, we can also use custom signature rules to strengthen data verification. By adding secret information (salt) to the data and generating a signature, we can verify the integrity of the data and the legitimacy of the sender. Here is a simple example:

import org.apache.commons.codec.digest.DigestUtils;

public class CustomSignatureExample {
    
    

    public static void main(String[] args) {
    
    
        String data = "Hello, Custom Signature!";
        String salt = "myCustomSalt";

        // 生成签名
        String signature = generateSignature(data, salt);
        System.out.println("Generated Signature: " + signature);

        // 验证签名
        boolean isValid = verifySignature(data, salt, signature);
        System.out.println("Signature Verification: " + isValid);
    }

    /**
     * 生成自定义签名
     *
     * @param data 要签名的数据
     * @param salt 自定义盐值
     * @return 生成的签名
     */
    public static String generateSignature(String data, String salt) {
    
    
        // 使用 Apache Commons Codec 库中的 md5Hex 方法计算 MD5 散列
        return DigestUtils.md5Hex(data + salt);
    }

    /**
     * 验证自定义签名
     *
     * @param data      原始数据
     * @param salt      自定义盐值
     * @param signature 要验证的签名
     * @return 是否验证通过
     */
    public static boolean verifySignature(String data, String salt, String signature) {
    
    
        // 重新生成签名,并与传入的签名比较
        String generatedSignature = generateSignature(data, salt);
        return generatedSignature.equals(signature);
    }
}

5. Comprehensive examples of data security

In practical applications, we can comprehensively use the above technologies to achieve secure data transmission. For example, you can use RSA to encrypt sensitive data, then use MD5 to generate a digest of the encrypted data, and use a custom signature rule to sign the data. Such a combination ensures data confidentiality while protecting data integrity. Comprehensive sample code:

import java.security.*;
import javax.crypto.Cipher;
import org.apache.commons.codec.digest.DigestUtils;

public class DataSecurityExample {
    
    

    public static void main(String[] args) throws Exception {
    
    
        // 生成 RSA 密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        // 使用 RSA 加密数据
        String sensitiveData = "This is a secret message!";
        byte[] encryptedData = encrypt(publicKey, sensitiveData);

        // 生成加密数据的 MD5 哈希
        String md5Hash = DigestUtils.md5Hex(encryptedData);

        // 生成自定义签名
        String salt = "mySecretSalt";
        String signature = generateSignature(md5Hash, salt);

        // 模拟数据传输和验证
        boolean isValid = verifySignature(md5Hash, salt, signature);
        if (isValid) {
    
    
            String decryptedData = decrypt(privateKey, encryptedData);
            System.out.println("Decrypted Data: " + decryptedData);
        } else {
    
    
            System.out.println("Data integrity compromised!");
        }
    }

    /**
     * 使用公钥加密数据
     */
    public static byte[] encrypt(PublicKey publicKey, String data) throws Exception {
    
    
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data.getBytes());
    }

    /**
     * 使用私钥解密数据
     */
    public static String decrypt(PrivateKey privateKey, byte[] encryptedData) throws Exception {
    
    
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(encryptedData);
        return new String(decryptedBytes);
    }

    /**
     * 生成自定义签名
     */
    public static String generateSignature(String data, String salt) {
    
    
        return DigestUtils.md5Hex(data + salt);
    }

    /**
     * 验证自定义签名
     */
    public static boolean verifySignature(String data, String salt, String signature) {
    
    
        String generatedSignature = generateSignature(data, salt);
        return generatedSignature.equals(signature);
    }
}

Through the comprehensive use of MD5, RSA encryption and custom signature rules, we can achieve secure data transmission and verification. These technologies play an important role in modern data communication, protecting the privacy and integrity of data. In practical applications, according to the needs of specific scenarios, we can choose the appropriate encryption and signature methods to achieve the optimal data security effect.

Summarize

This article introduces how to combine MD5, RSA encryption and custom signature rules to realize secure transmission and verification of Java data. By using MD5 hashing to ensure data integrity, RSA encryption to ensure the confidentiality of sensitive data, and custom signature rules to enhance data verification, we can build a powerful and flexible data security mechanism.

In actual development, different scenarios and requirements may require different data security solutions. Therefore, when choosing an appropriate encryption and signature method, factors such as data protection level, performance requirements, and implementation complexity need to be considered comprehensively.

With the sample code and explanations provided in this article, you can start applying MD5, RSA, and custom signature technologies in your Java applications to ensure that your data is adequately protected during transmission and storage. Whether it is data transmission during communication or data storage on the server, reasonable data security measures can be taken to deal with potential risks and ensure data security and reliability.

Guess you like

Origin blog.csdn.net/Da_zhenzai/article/details/132333038