Home > Java > Javagetting Started > body text

How to encrypt in java

爱喝马黛茶的安东尼
Release: 2019-12-09 15:15:54
Original
3625 people have browsed it

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!

Related labels:
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