Home > Java > javaTutorial > body text

How to perform data encryption and decryption for Java function development

WBOY
Release: 2023-08-06 18:25:05
Original
1061 people have browsed it

How to perform data encryption and decryption for Java function development

Data encryption and decryption play an important role in the field of information security. In Java development, there are many ways to implement data encryption and decryption functions. This article will introduce the method of data encryption and decryption using Java programming language and provide code examples.

1. Symmetric encryption algorithm

The symmetric encryption algorithm uses the same key to encrypt and decrypt data. Commonly used symmetric encryption algorithms include DES, 3DES, AES, etc.

Code example:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

public class SymmetricEncryptionExample {
    public static void main(String[] args) throws Exception {
        String plaintext = "Hello, World!";
        String secretKey = "0123456789abcdef";
        
        // Generate Key
        SecretKey key = new SecretKeySpec(secretKey.getBytes(), "AES");

        // Create Cipher
        Cipher cipher = Cipher.getInstance("AES");
        
        // Encrypt
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes());
        String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("Encrypted Text: " + encryptedText);

        // Decrypt
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        String decryptedText = new String(decryptedBytes);
        System.out.println("Decrypted Text: " + decryptedText);
    }
}
Copy after login

2. Asymmetric encryption algorithm

The asymmetric encryption algorithm uses a pair of keys, the public key is used for encryption, and the private key is used for decryption. In Java, the commonly used asymmetric encryption algorithm is RSA.

Code example:

import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

public class AsymmetricEncryptionExample {
    public static void main(String[] args) throws Exception {
        String plaintext = "Hello, World!";

        // Generate Key Pair
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
        keyGenerator.initialize(2048);
        KeyPair keyPair = keyGenerator.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        // Create Cipher
        Cipher cipher = Cipher.getInstance("RSA");

        // Encrypt
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes());
        String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("Encrypted Text: " + encryptedText);

        // Decrypt
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        String decryptedText = new String(decryptedBytes);
        System.out.println("Decrypted Text: " + decryptedText);
    }
}
Copy after login

3. Hash algorithm

The hash algorithm can convert data of any length into a fixed-length hash value. Commonly used hash algorithms There are MD5, SHA-1, SHA-256, etc.

Code examples:

import java.security.MessageDigest;

public class HashAlgorithmExample {
    public static void main(String[] args) throws Exception {
        String plaintext = "Hello, World!";

        // Create MessageDigest
        MessageDigest md = MessageDigest.getInstance("SHA-256");

        // Hash
        byte[] hashedBytes = md.digest(plaintext.getBytes());
        StringBuilder stringBuilder = new StringBuilder();
        for (byte hashedByte : hashedBytes) {
            stringBuilder.append(Integer.toHexString(0xFF & hashedByte));
        }
        String hashedText = stringBuilder.toString();
        System.out.println("Hashed Text: " + hashedText);
    }
}
Copy after login

Summary:

This article introduces the methods and code examples of using Java to develop and implement data encryption and decryption. In actual development, appropriate encryption algorithms and key lengths are selected according to different needs to ensure data security.

The above is the detailed content of How to perform data encryption and decryption for Java function development. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template