search
HomeJavaJavagetting StartedHow to encrypt in java

How to encrypt in java

Dec 09, 2019 pm 03:14 PM
javaencryption

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
}
}

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
}
}

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
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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software