java 加解密算法_Java常用加解密算法

本文详细介绍了Java中常见的几种加密解密算法,包括非对称加密算法RSA和对称加密算法如BASE64、MD5、SHA以及DES。RSA用于公钥私钥加密,MD5和SHA用于信息摘要,而DES则是一种对称加密算法。文章还涵盖了这些算法的加密、解密、签名验证等操作的实现代码。
摘要由CSDN通过智能技术生成

1、BASE64

BASE64严格地说,应该说是属于编码格式,而非加密算法。

加解密:

/**

* 加密

*/

public static String encryptBASE64(byte[] data) {

BASE64Encoder encoder = new BASE64Encoder();

return encoder.encode(data);

}

/**

* 解密

*/

public static byte[] decryptBASE64(String cipher) {

BASE64Decoder decoder = new BASE64Decoder();

byte[] bytes = null;

try {

bytes = decoder.decodeBuffer(cipher);

} catch (IOException e) {

e.printStackTrace();

}

return bytes;

}

2、MD5和SHA

MD5(Message Digest algorithm 5,信息摘要算法),常用于文件校验。

SHA(Secure Hash Algorithm,安全散列算法),同样属于非可逆的算法,作用与MD5相类似。

MD5输出是128位的,SHA输出是160位的。SHA相较于MD5而言更加安全,当然加密花费时间也更长一点。

先设置常量

private final static String KEY_SHA = "SHA";

private final static String KEY_MD5 = "MD5";

加密

/**

* MD5加密

*/

public static String encryptMD5(byte[] data) {

String cipher = null;

try {

MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);

md5.update(data);

cipher = encryptBASE64(md5.digest());

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

}

return cipher;

}

/**

* SHA加密

*/

public static String encryptSHA(byte[] data) {

String cipher = null;

try {

MessageDigest sha = MessageDigest.getInstance(KEY_SHA);

sha.update(data);

cipher = encryptBASE64(sha.digest());

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

}

return cipher;

}

3、RSA

RSA算法是一种非对称密码算法。详情见[RSA算法]({{ post.url }}/blog/2015/02/11/RSA-Algorithm.html)

设置需要用到常量,RSA_INIT_LENGTH为密钥的初始化长度,密钥的长度越长,安全性就越好,但是加密解密所用的时间就会越多。一次能加密的密文长度为:密钥的长度/8-11。所以1024bit长度的密钥一次可以加密的密文为1024/8-11=117bit。所以非对称加密一般都用于加密对称加密算法的密钥,而不是直接加密内容。对于小文件可以使用RSA加密,但加密过程仍可能会使用分段加密。

private final static String KEY_RSA = "RSA";

private final static int RSA_INIT_LENGTH = 1024;

3.1、java中初始化生成公钥和私钥

/**

* 初始化

*/

public static String[] initRSAKey() {

String[] keys = null;

try {

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_RSA);

keyPairGenerator.initialize(RSA_INIT_LENGTH);

KeyPair keyPair = keyPairGenerator.generateKeyPair();

// 公钥

RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

// 私钥

RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

keys = new String[]{encryptBASE64(publicKey.getEncoded()), encryptBASE64(privateKey.getEncoded())};

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

}

return keys;

}

3.2、加解密

RSA有两个密钥,所以加解密方式也有两种,一种是“私钥加密-公钥解密”,另一种就是“公钥加密-私钥解密”,加解密的实现如下:

/**

* 私钥加密

*/

public static byte[] encryptByPrivateKey(byte[] data, String key) {

try {

byte[] keyBytes = decryptBASE64(key);

// 获得私钥

PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);

KeyFactory keyFactory = KeyFactory.getInstance(KEY_RSA);

Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

// 对数据加密

Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

cipher.init(Cipher.ENCRYPT_MODE, privateKey);

return cipher.doFinal(data);

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

/**

* 公钥解密

*/

public static byte[] decryptByPublicKey(byte[] data, String key) {

try {

// 对私钥解密

byte[] keyBytes = decryptBASE64(key);

X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);

KeyFactory keyFactory = KeyFactory.getInstance(KEY_RSA);

Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

// 对数据解密

Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

cipher.init(Cipher.DECRYPT_MODE, publicKey);

return cipher.doFinal(data);

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

/**

* 公钥加密

*/

public static byte[] encryptByPublicKey(byte[] data, String key) {

try {

// 对公钥解密

byte[] keyBytes = decryptBASE64(key);

// 取公钥

X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);

KeyFactory keyFactory = KeyFactory.getInstance(KEY_RSA);

Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

// 对数据解密

Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

cipher.init(Cipher.ENCRYPT_MODE, publicKey);

return cipher.doFinal(data);

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

/**

* 私钥解密

*/

public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception {

try {

// 对私钥解密

byte[] keyBytes = decryptBASE64(key);

PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);

KeyFactory keyFactory = KeyFactory.getInstance(KEY_RSA);

Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

// 对数据解密

Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

cipher.init(Cipher.DECRYPT_MODE, privateKey);

return cipher.doFinal(data);

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

3.3 签名验证

使用RSA进行签名验证。数字签名技术是将摘要信息用发送者的私钥加密,与原文一起传送给接收者。接收者只有用发送者的公钥才能解密被加密的摘要信息,然后用对收到的原文产生一个摘要信息,与解密的摘要信息对比。如果相同,则说明收到的信息是完整的,在传输过程中没有被修改,否则说明信息被修改过,因此数字签名能够验证信息的完整性。

该方法可行有两个的条件:

1、通过公钥推算出私钥的做法不可能实现

2、即使传输数据的过程被拦截,因为拦截者没有私钥,改动数据就会导致签名的不一致。(这里需要注意,拦截者还是可以使用公钥对数据进行解密,看到传输的数据的)

定义常量

private final static String RSA_MD5 = "MD5withRSA";

签名和签名验证

/**

* 私钥签名

*/

public static String signByPrivateKey(byte[] data, String privateKey) {

try {

// 解密私钥

byte[] keyBytes = decryptBASE64(privateKey);

// 构造PKCS8EncodedKeySpec对象

PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);

// 指定加密算法

KeyFactory keyFactory = KeyFactory.getInstance(KEY_RSA);

// 取私钥匙对象

PrivateKey privateKey2 = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

// 用私钥对信息生成数字签名

Signature signature = Signature.getInstance(RSA_MD5);

signature.initSign(privateKey2);

signature.update(data);

return encryptBASE64(signature.sign());

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

/**

* 公钥验证

*/

public static boolean verifyByPublicKey(byte[] data, String publicKey, String sign) {

try {

// 解密公钥

byte[] keyBytes = decryptBASE64(publicKey);

// 构造X509EncodedKeySpec对象

X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);

// 指定加密算法

KeyFactory keyFactory = KeyFactory.getInstance(KEY_RSA);

// 取公钥匙对象

PublicKey publicKey2 = keyFactory.generatePublic(x509EncodedKeySpec);

Signature signature = Signature.getInstance(RSA_MD5);

signature.initVerify(publicKey2);

signature.update(data);

// 验证签名是否正常

return signature.verify(decryptBASE64(sign));

} catch (Exception e) {

e.printStackTrace();

}

return false;

}

4、DES

DES(全称为DataEncryption Standard,即数据加密标准),是一种对称加密算法!

定义常量

private final static String KEY_DES = "DES";

加解密,其中key是8位的密码

/**

* 加密

*/

public static byte[] encryptDES(byte[] data, String key) {

try {

SecureRandom random = new SecureRandom();

DESKeySpec desKey = new DESKeySpec(key.getBytes());

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_DES);

SecretKey secureKey = keyFactory.generateSecret(desKey);

Cipher cipher = Cipher.getInstance(KEY_DES);

cipher.init(Cipher.ENCRYPT_MODE, secureKey, random);

return cipher.doFinal(data);

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

/**

* 解密

*/

public static byte[] decryptDES(byte[] data, String key) {

try {

SecureRandom random = new SecureRandom();

DESKeySpec desKey = new DESKeySpec(key.getBytes());

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_DES);

SecretKey secureKey = keyFactory.generateSecret(desKey);

Cipher cipher = Cipher.getInstance(KEY_DES);

cipher.init(Cipher.DECRYPT_MODE, secureKey, random);

return cipher.doFinal(data);

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

文件加密解密算法(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、付费专栏及课程。

余额充值