Home Java Javagetting Started How to encrypt in java

How to encrypt in java

Dec 09, 2019 pm 03:14 PM
java encryption

How to encrypt in java

The first one, DES encryption and decryption

import java.security.Key;
import java.security.SecureRandom;
 
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
 
/**
 * DES是一种对称加密算法,所谓对称加密算法:加密和解密使用相同的秘钥的算法
 * @author llp
 *
 */
public class DESUtil {
private static final Logger logger = LoggerFactory.getLogger(DESUtil.class);
 
private static Key key;
//设置秘钥key
private static String KEY_STR="myKey";
private static String CHARSETNAME="UTF-8";
private static String ALGORITHM="DES";
static{
try{
//生成DES算法对象
KeyGenerator generator=KeyGenerator.getInstance(ALGORITHM);
//运用SHA1安全策略
SecureRandom secureRandom=SecureRandom.getInstance("SHA1PRNG");
//设置上密钥种子
secureRandom.setSeed(KEY_STR.getBytes());
//初始化基于SHA1的算法对象
generator.init(secureRandom);
//生成密钥对象
key=generator.generateKey();
generator=null;
}catch(Exception e){
throw new RuntimeException(e);
}
}
/**
* 获取加密的信息
* @param str
* @return
*/
public static String getEncryptString(String str){
//基于BASE64编码,接收byte[]并转换成String
BASE64Encoder base64Encoder=new BASE64Encoder();
try {
// 按UTF8编码
byte[] bytes = str.getBytes(CHARSETNAME);
// 获取加密对象
Cipher cipher = Cipher.getInstance(ALGORITHM);
// 初始化密码信息
cipher.init(Cipher.ENCRYPT_MODE, key);
// 加密
byte[] doFinal = cipher.doFinal(bytes);
// byte[]to encode好的String并返回
return base64Encoder.encode(doFinal);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 获取解密之后的信息
* 
* @param str
* @return
*/
public static String getDecryptString(String str) {
// 基于BASE64编码,接收byte[]并转换成String
BASE64Decoder base64decoder = new BASE64Decoder();
try {
// 将字符串decode成byte[]
byte[] bytes = base64decoder.decodeBuffer(str);
// 获取解密对象
Cipher cipher = Cipher.getInstance(ALGORITHM);
// 初始化解密信息
cipher.init(Cipher.DECRYPT_MODE, key);
// 解密
byte[] doFinal = cipher.doFinal(bytes);
// 返回解密之后的信息
return new String(doFinal, CHARSETNAME);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
//加密
logger.info(getEncryptString("root"));//WnplV/ietfQ=
logger.info(getEncryptString("123456"));//QAHlVoUc49w=
//解密
logger.info(getDecryptString(getEncryptString("root")));//root
logger.info(getDecryptString(getEncryptString("123456")));//123456
}
}
Copy after login

The second one, MD5 encryption

import java.security.MessageDigest;
/**
 * MD5加密
 * @author llp
 *
 */
public class MD5 {
 
/**
* 对传入的String进行MD5加密
* 
* @param s
* @return
*/
public static final String getMd5(String s) {
// 16进制数组
char hexDigits[] = { '5', '0', '5', '6', '2', '9', '6', '2', '5', 'q', 'b', 'l', 'e', 's', 's', 
'y' };
try {
char str[];
// 将传入的字符串转换成byte数组
byte strTemp[] = s.getBytes();
// 获取MD5加密对象
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
// 传入需要加密的目标数组
mdTemp.update(strTemp);
// 获取加密后的数组
byte md[] = mdTemp.digest();
int j = md.length;
str = new char[j * 2];
int k = 0;
// 将数组做位移
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
// 转换成String并返回
return new String(str);
} catch (Exception e) {
return null;
}
}
 
public static void main(String[] args) {
System.out.println(MD5.getMd5("123456"));//s05bse6q2qlb9qblls96s592y55y556s
}
}
Copy after login

PHP Chinese website has a large number of free JAVA introductory tutorials, everyone is welcome to learn!

The above is the detailed content of How to encrypt in java. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Get the gate.io installation package for free Get the gate.io installation package for free Feb 21, 2025 pm 08:21 PM

Gate.io is a popular cryptocurrency exchange that users can use by downloading its installation package and installing it on their devices. The steps to obtain the installation package are as follows: Visit the official website of Gate.io, click "Download", select the corresponding operating system (Windows, Mac or Linux), and download the installation package to your computer. It is recommended to temporarily disable antivirus software or firewall during installation to ensure smooth installation. After completion, the user needs to create a Gate.io account to start using it.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

List of top ten exchanges in the currency circle List of top ten exchanges in the currency circle Feb 21, 2025 pm 10:18 PM

The top ten exchanges in the currency circle are ranked by trading volume: Binance Ouyihuobi FTXKrakenCoinbaseGeminiBitfinexBybitGate.io

Java Made Simple: A Beginner's Guide to Programming Power Java Made Simple: A Beginner's Guide to Programming Power Oct 11, 2024 pm 06:30 PM

Java Made Simple: A Beginner's Guide to Programming Power Introduction Java is a powerful programming language used in everything from mobile applications to enterprise-level systems. For beginners, Java's syntax is simple and easy to understand, making it an ideal choice for learning programming. Basic Syntax Java uses a class-based object-oriented programming paradigm. Classes are templates that organize related data and behavior together. Here is a simple Java class example: publicclassPerson{privateStringname;privateintage;

Which of the top ten virtual currency trading apps is the best? Which of the top ten virtual currency trading apps is the most reliable Which of the top ten virtual currency trading apps is the best? Which of the top ten virtual currency trading apps is the most reliable Mar 19, 2025 pm 05:00 PM

Top 10 virtual currency trading apps rankings: 1. OKX, 2. Binance, 3. Gate.io, 4. Kraken, 5. Huobi, 6. Coinbase, 7. KuCoin, 8. Crypto.com, 9. Bitfinex, 10. Gemini. Security, liquidity, handling fees, currency selection, user interface and customer support should be considered when choosing a platform.

See all articles