Java 加解密算法

目前加密算法中分两种

一种是对称加密,一种是非对称加密

那么什么是对称加密呢?对称加密可以理解为加密和解密用的是一个钥匙。

而非对称加密,加锁用的是一个钥匙,而解锁用的是另外一个钥匙。

目前市面上用的比较多的对称加密,比如Md5,SHA,AES下面就直接上代码

 

所需要引入的包为:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.LinkedHashMap;
import java.util.Map;

 

写代码之前,要写一个工具类Base64,为什么要这个类呢?因为我们不管 是对称加密

还是非对称加密,他加密后返回的默认都是二进制字节类型的。这种数据我们拿到也看不懂

所以,一般有两种解决方案第一种就是通过Base64把二进制字节转为字符串,另一种就是转为16进制字符串

这里我就以Base64作为转换,在写一个解码的。因为某些加密算法需要传入的 是二进制字节

 

public class Base64Util {
//转换为Base64
public static String base64Enc(byte[] msg) {
return Base64.getEncoder().encodeToString(msg);
}
//解码
public static byte[] base64Dec(String msg) {
return Base64.getDecoder().decode(msg);
}
}

 

-----------------Md5加密代码

 public class EncryptUtil {

public static final String SHA1 = "SHA-1";
public static final String SHA256 = "SHA-256";
public static final String SHA512 = "SHA-512";
public static final String ENCODING = "UTF-8";

//公钥
public static final String PUBKEY = "publicKey";
//私钥
public static final String PRIKEY = "privateKey";

public static String md5Enc(String msg) {
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(msg.getBytes(ENCODING));
return new BigInteger(1, digest.digest()).toString(16);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}    

-------------------SHA加密代码,参数是一个 SHA类型,目前有 1,256,521.z还有一个需要加密的字符串

具体代码为:

 

public static String SHAEnc(String type, String msg) {
try {
MessageDigest digest = MessageDigest.getInstance(type);
digest.update(msg.getBytes(ENCODING));
return new BigInteger(1, digest.digest()).toString(16);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

测试结果

 

------------------------------AES 加密算法。 这个是需要密钥生成器的。自己可以保管密钥。如果下要破解,必须

知道加密方式和密钥。相对前面两个安全级别要高许多

 

public static byte[] createAESKey() {
try {
// 创建秘钥生成器
KeyGenerator generator = KeyGenerator.getInstance("AES");
// 完成秘钥初始化 AES的128
generator.init(128);
// 生成秘钥
SecretKey key = generator.generateKey();
return key.getEncoded();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

 

// AES加密 返回值base64
public static String AESEnc(byte[] key, String msg) {
// 转换秘钥
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
try {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] r = cipher.doFinal(msg.getBytes(ENCODING));
return Base64Util.base64Enc(r);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// AES解密
public static String AESDec(byte[] key, String msg) {
// 转换秘钥
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
try {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] r = cipher.doFinal(Base64Util.base64Dec(msg));
return new String(r, ENCODING);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

 

继续测试

 

 

 以上的加密方式都是对称加密。只要拿到密钥就会有风险。

 

下面介绍一款号称最安全的加密方式 就是RSA加密 公钥加密  私钥解密

或者私钥加密 公钥解密。一般来说都是私钥加密 ,公钥解密 不废话直接上代码

 

// RSA
// 创建秘钥
// 创建秘钥 1024
public static Map<String, String> createRSAKey() {
try {
// 创建秘钥生成器
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
// 完成秘钥初始化
generator.initialize(1024);
// 生成秘钥
KeyPair keyPair = generator.generateKeyPair();

Map<String, String> map = new LinkedHashMap<String, String>();
// 获取公钥
map.put(PUBKEY, Base64Util.base64Enc(keyPair.getPublic().getEncoded()));
// 获取私钥
map.put(PRIKEY, Base64Util.base64Enc(keyPair.getPrivate().getEncoded()));
return map;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// 获取公钥
public static PublicKey getPubKey(String key) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64Util.base64Dec(key));
return (PublicKey) keyFactory.generatePublic(keySpec);
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
// 获取私钥
public static PrivateKey getPriKey(String key) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64Util.base64Dec(key));
return (PrivateKey) keyFactory.generatePrivate(keySpec);
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
// RSA 私钥加密 返回值base64
public static String RSAEnc(String key, String msg) {
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, getPriKey(key));
byte[] r = cipher.doFinal(msg.getBytes(ENCODING));
return Base64Util.base64Enc(r);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// RSA解密
public static String RSADec(String key, String msg) {
// 转换秘钥
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, getPubKey(key));
byte[] r = cipher.doFinal(Base64Util.base64Dec(msg));
return new String(r,ENCODING);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;

 

 

测试!!!!

 

 

 

 

几种加密方式都可以使用

 

看具体公司需求而定。

 

!!!!!!!!!!!!!!!  小风Q769104932 转发请留言 坚持每天学习 加油!!!!

 


}

转载于:https://www.cnblogs.com/jiaowoxiaofeng/p/10582304.html

文件加密解密算法(Java源码) java,file,算法,加密解密,java源码 package com.crypto.encrypt; import java.security.SecureRandom; import java.io.*; import javax.crypto.spec.DESKeySpec; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.Cipher; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import javax.crypto.NoSuchPaddingException; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import java.lang.reflect.Constructor; import java.security.spec.KeySpec; import java.lang.reflect.InvocationTargetException; public class EncryptData { private String keyfile=null; public EncryptData() { } public EncryptData(String keyfile) { this.keyfile=keyfile; } /** * 加密文件 * @param filename String 源路径 * @param filenamekey String 加密后的路径 */ public void createEncryptData(String filename,String filenamekey) throws IllegalStateException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, IOException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException, IllegalStateException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, IOException { //验证keyfile if(keyfile==null || keyfile.equals("")) { throw new NullPointerException("无效的key文件路径"); } encryptData(filename,filenamekey); } /** * 加密类文件 * @param filename String 原始的类文件 * @param encryptfile String 加密后的类文件 * @throws IOException * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException * @throws BadPaddingException * @throws IllegalBlockSizeException * @throws IllegalStateException */ private void encryptData(String filename,String encryptfile) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, IllegalStateException, ClassNotFoundException, SecurityException, NoSuchMethodException, InvocationTargetException, IllegalArgumentException, IllegalAccessException, InstantiationException { byte data[]=Util.readFile(filename); // 执行加密操作 byte encryptedClassData[] = getencryptData(data); // 保存加密后的文件,覆盖原有的类文件。 Util.writeFile(encryptedClassData,encryptfile); } /** * 直接获得加密数据 * @param bytes byte[] * @throws IllegalStateException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws InvalidKeyException * @throws NoSuchPaddingException * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException * @throws InstantiationException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException * @throws NoSuchMethodException * @throws SecurityException * @throws ClassNotFoundException * @throws IOException * @return byte[] */ public byte[] createEncryptData(byte[] bytes) throws IllegalStateException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException, IOException { bytes=getencryptData(bytes); return bytes; } private byte[] getencryptData(byte[] bytes) throws IOException, ClassNotFoundException, SecurityException, NoSuchMethodException, InvocationTargetException, IllegalArgumentException, IllegalAccessException, InstantiationException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IllegalStateException { // 产生一个可信任的随机数源 SecureRandom sr = new SecureRandom(); //从密钥文件key Filename中得到密钥数据 byte[] rawKeyData = Util.readFile(keyfile); // 从原始密钥数据创建DESKeySpec对象 Class classkeyspec=Class.forName(Util.getValue("keyspec")); Constructor constructor = classkeyspec.getConstructor(new Class[]{byte[].class}); KeySpec dks = (KeySpec) constructor.newInstance(new Object[]{rawKeyData}); // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(Util.getAlgorithm()); SecretKey key = keyFactory.generateSecret(dks); // Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance(Util.getAlgorithm()); // 用密钥初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, key, sr); // 执行加密操作 bytes = cipher.doFinal(bytes); // 返回字节数组 return bytes; } /** * 设置key文件路径 * @param keyfile String */ public void setKeyFile(String keyfile) { this.keyfile=keyfile; } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值