当前位置:   article > 正文

Java加密算法:MD5加密,对称加密,非对称加密_java base64加密

java base64加密

目录

Java:密码算法

1、base64加密方式

2、jdk原生api实现MD5

3、使用codec依赖实现MD5加密

4、SHA加密

5、MAC算法加密

6、对称加密

7、非对称加密


Java:密码算法

1、base64算法

  1. public class demo {
  2. //设置编码格式
  3. private static final String UTF8 = StandardCharsets.UTF_8.name();
  4. public static void main(String[] args) throws UnsupportedEncodingException {
  5. String str = "张三写java";
  6. //编码
  7. String encodedStr = Base64.getEncoder().encodeToString(str.getBytes(UTF8));
  8. System.out.println("encodedStr:" + encodedStr);
  9. //解码
  10. byte[] decode = Base64.getDecoder().decode(encodedStr.getBytes(UTF8));
  11. System.out.println("decode:"+ new String(decode,UTF8));
  12. }
  13. }

结果:

注意:Base64 不是加密算法,而是一种编码方式。Base64 主要用于将二进制数据编码成文本格式,以便在文本协议中传输,如在电子邮件、XML、JSON 等中。它并不是为了提供加密或安全性而设计的。

URL编码

  1. public class URLTest {
  2. //设置编码格式
  3. private static final String UTF8 = StandardCharsets.UTF_8.name();
  4. public static void main(String[] args) throws UnsupportedEncodingException {
  5. String str = "张三写java";
  6. //编码
  7. String encodedStr = URLEncoder.encode(str,UTF8);
  8. System.out.println("编码:"+encodedStr);
  9. //解码
  10. String decode = URLDecoder.decode(encodedStr,UTF8);
  11. System.out.println("解码后:"+decode);
  12. }
  13. }

结果:

MD5: Message-Digest Algorithm,结果占128位==>16个byte=>转成16进制字符后是32个

11111111--->ff

2、jdk原生api实现MD5

  1. public class MD5Test {
  2. //设置编码格式
  3. private static final String UTF8 = StandardCharsets.UTF_8.name();
  4. public static void main(String[] args) throws Exception {
  5. String str = "张三写java";
  6. String algorithm = "MD5";
  7. //获取消息摘要算法对象
  8. MessageDigest md = MessageDigest.getInstance(algorithm);
  9. // 获取原始内容的字节数组
  10. byte[] originalBytes = str.getBytes(UTF8);
  11. //获取到摘要结果
  12. byte[] digestBytes = md.digest(originalBytes);
  13. //当originalBytes比较大的时候,循环的进行update()
  14. //md.update(originalBytes);
  15. //md.digest();
  16. //把每一个字节转为16进制字符,最终再拼接起来这些16进制字符
  17. String hexStr = converBytes(digestBytes);
  18. System.out.println("hexStr:" + hexStr);
  19. }
  20. private static String converBytes(byte[] digestBytes) {
  21. StringBuilder sb = new StringBuilder();
  22. for (byte b : digestBytes) {
  23. //获取b的补码的后8
  24. String hex = Integer.toHexString(((int)b)&0xff);
  25. // 15-->Integer.toHexString (15&Oxff)-->f-->0f
  26. // 16-- >Integer.toHexString(16&0xff)->10
  27. if (hex.length() == 1){
  28. hex = "0" + hex;
  29. }
  30. sb.append(hex);
  31. }
  32. return sb.toString();
  33. }
  34. }

 代码封装,把上面公共部分提取出来

  1. public class HexUtils {
  2. /**
  3. * @description 把字节数组转为16进制字符串,如果一个字节转为16进制字符后不足两位,则前面补0
  4. * @author
  5. * @date 2023-02-23 21:02:13
  6. * @param digestBytes
  7. * @return {@link String}
  8. */
  9. public static String converBytes(byte[] digestBytes) {
  10. StringBuilder sb = new StringBuilder();
  11. for (byte b : digestBytes) {
  12. //获取b的补码的后8
  13. String hex = Integer.toHexString(((int)b)&0xff);
  14. // 15-->Integer.toHexString (15&Oxff)-->f-->0f
  15. // 16-- >Integer.toHexString(16&0xff)->10
  16. if (hex.length() == 1){
  17. hex = "0" + hex;
  18. }
  19. sb.append(hex);
  20. }
  21. return sb.toString();
  22. }
  23. /**
  24. * 把16进制字符串(一定是偶数位的,因为converBytes已经处理过)转为字节数组
  25. * @param hexStr 16进制字符串
  26. * @return
  27. */
  28. public static byte[] converHex2Bytes(String hexStr) {
  29. //一个字节可以转为216进制字符
  30. int length = hexStr.length() / 2;
  31. byte[] reault = new byte[length];
  32. for (int i = 0; i < length; i++) {
  33. //hexStr : abcd
  34. //Integer.parseInt :把s转为10进制数,radix指定s是什么进制的数
  35. //获取每个字节的高4位, hexStr.substring(2,3)=>c
  36. int high4 = Integer.parseInt(hexStr.substring(i * 2,i * 2 + 1),16);
  37. //获取每个字节的低4位,hexStr.substring( 3,4)=>d
  38. int low4 = Integer.parseInt(hexStr.substring(i * 2 + 1,i * 2 + 2),16);
  39. reault[i] = (byte) (high4* 16 + low4);
  40. }
  41. return reault;
  42. }
  1. public class MessageDigestUtils {
  2. //设置编码格式
  3. private static final String UTF8 = StandardCharsets.UTF_8.name();
  4. /**
  5. * @description 执行信息再要
  6. * @author
  7. * @date 2023-02-23 21:09:55
  8. * @param originContent 原始字符串
  9. * @param algorithm 算法名字,如MD5
  10. * @return {@link String}
  11. */
  12. public static String doDigest(String originContent,String algorithm){
  13. try {
  14. //获取消息摘要算法对象
  15. MessageDigest md = MessageDigest.getInstance(algorithm);
  16. // 获取原始内容的字节数组
  17. byte[] originalBytes = originContent.getBytes(UTF8);
  18. //获取到摘要结果
  19. byte[] digestBytes = md.digest(originalBytes);
  20. //当originalBytes比较大的时候,循环的进行update()
  21. //md.update(originalBytes);
  22. //md.digest();
  23. //把每一个字节转为16进制字符,最终再拼接起来这些16进制字符
  24. String hexStr = HexUtils.converBytes(digestBytes);
  25. return hexStr;
  26. }catch (Exception e){
  27. e.printStackTrace();
  28. }
  29. return null;
  30. }
  31. }

3、使用codec依赖实现MD5加密

  1. <dependency>
  2. <groupId>commons-codec</groupId>
  3. <artifactId>commons-codec</artifactId>
  4. <version>1.15</version>
  5. </dependency>
  1. public class MD5Test {
  2. //设置编码格式
  3. private static final String UTF8 = StandardCharsets.UTF_8.name();
  4. public static void main(String[] args) throws Exception {
  5. String str = "张三写java";
  6. System.out.println( "str:" + DigestUtils.md5Hex(str.getBytes(UTF8)));
  7. }
  8. }

结果: 

4、SHA加密

SHA(Secure Hash Algorithm) :安全散列算法

sha-256=>转成16进制字符后是64个

其他如sha-0,sha-1, sha-512

SHA-256加密:

  1. public class Sha256Test {
  2. //设置编码格式
  3. private static final String UTF8 = StandardCharsets.UTF_8.name();
  4. public static void main(String[] args) throws Exception {
  5. String str = "张三写java";
  6. String algorithm = "SHA-256";
  7. //封装的类进行编码
  8. String hexStr = MessageDigestUtils.doDigest(str,algorithm);
  9. System.out.println("自己封装的str:" + hexStr);
  10. System.out.println("codec的str:" + DigestUtils.sha256Hex(str.getBytes(UTF8)));
  11. }
  12. }

结果:

SHA-512

  1. public class SHA512Test {
  2. //设置编码格式
  3. private static final String UTF8 = StandardCharsets.UTF_8.name();
  4. public static void main(String[] args) throws Exception {
  5. String str = "张三写java";
  6. String algorithm = "SHA-512";
  7. //封装的类进行编码
  8. String hexStr = MessageDigestUtils.doDigest(str,algorithm);
  9. System.out.println("自己封装的str:" + hexStr);
  10. System.out.println("codec的str:" + DigestUtils.sha512Hex(str.getBytes(UTF8)));
  11. }
  12. }

5、MAC算法加密

MAC(Message Authentication Code):消息认证码,是一种带有秘钥的hash函数

使用jdk实现在添加一个方法 

  1. /**
  2. * @description 获取mac的消息摘要
  3. * @author
  4. * @date 2023-02-23 21:37:36
  5. * @param originContent 原始内容
  6. * @param algorithm mac算法的key
  7. * @param key 算法名字,例如HmacMD5
  8. * @return {@link String}
  9. */
  10. public static String doMacDigest(String originContent,String algorithm,String key){
  11. try {
  12. //获取消息摘要算法对象
  13. Mac mac = Mac.getInstance(algorithm);
  14. //
  15. SecretKey secretKey = new SecretKeySpec(key.getBytes(UTF8),algorithm);
  16. mac.init(secretKey);
  17. // 获取原始内容的字节数组
  18. byte[] originalBytes = originContent.getBytes(UTF8);
  19. //获取到摘要结果
  20. byte[] digestBytes = mac.doFinal(originalBytes);
  21. //当originalBytes比较大的时候,循环的进行update()
  22. //md.update(originalBytes);
  23. //md.digest();
  24. //把每一个字节转为16进制字符,最终再拼接起来这些16进制字符
  25. String hexStr = HexUtils.converBytes(digestBytes);
  26. return hexStr;
  27. }catch (Exception e){
  28. e.printStackTrace();
  29. }
  30. return null;
  31. }

使用自己封装的方法及使用codec实现mac加密

  1. public class MACTest {
  2. //设置编码格式
  3. private static final String UTF8 = StandardCharsets.UTF_8.name();
  4. public static void main(String[] args) throws Exception {
  5. String str = "张三写java";
  6. String algorithm1 = "HmacMD5";
  7. String algorithm2 = "HmacSHA256";
  8. String algorithm3 = "HmacSHA512";
  9. //指定秘钥, mac摘要和digest算法( md5 , sha)不同的地方就是加了盐
  10. String key = "123";
  11. //封装的类进行编码
  12. String hexStr1 = MessageDigestUtils.doMacDigest(str,algorithm1,key);
  13. String hexStr2 = MessageDigestUtils.doMacDigest(str,algorithm2,key);
  14. String hexStr3 = MessageDigestUtils.doMacDigest(str,algorithm3,key);
  15. System.out.println("HmacMD5:" + hexStr1);
  16. System.out.println("HmacMD5:" + hexStr2);
  17. System.out.println("HmacMD5:" + hexStr3);
  18. String hmacMD5HexStr = new HmacUtils(HmacAlgorithms.HMAC_MD5,key.getBytes(UTF8)).hmacHex(str.getBytes(UTF8));
  19. String hmacSHA256HexStr = new HmacUtils(HmacAlgorithms.HMAC_SHA_256,key.getBytes(UTF8)).hmacHex(str.getBytes(UTF8));
  20. String hmacSHA512HexStr = new HmacUtils(HmacAlgorithms.HMAC_SHA_512,key.getBytes(UTF8)).hmacHex(str.getBytes(UTF8));
  21. System.out.println("hmacMD5HexStr:"+ hmacMD5HexStr);
  22. System.out.println("hmacSHA256HexStr:"+ hmacSHA256HexStr);
  23. System.out.println("hmacSHA512HexStr:"+ hmacSHA512HexStr);
  24. }
  25. }

结果: 

6、对称加密

也叫单秘钥加密。所谓单秘钥,指的是加密和解密的过程使用相同的密钥,相比非对称加密,因只有一把钥匙,因而速度更快,更适合加解密大文件。

DES : data encryption standard,已经过时

AES : advanced encryption standard,替代des。
 

DES:使用Base64加密

  1. public class DesTest {
  2. //设置编码格式
  3. private static final String UTF8 = StandardCharsets.UTF_8.name();
  4. private static final String KEY = "12345678";
  5. //加密模式
  6. private static final String ALGORITHM = "DES";
  7. /**
  8. * 加密
  9. * @param text 加密内容
  10. * @return
  11. */
  12. public static String encrypt(String text) throws Exception {
  13. //获取示例
  14. Cipher cipher = Cipher.getInstance(ALGORITHM);
  15. //创建加密规则
  16. SecretKey secretKey = new SecretKeySpec(KEY.getBytes(UTF8), ALGORITHM);
  17. //加密模式规则
  18. cipher.init(Cipher.ENCRYPT_MODE,secretKey);
  19. byte[] bytes = cipher.doFinal(text.getBytes(UTF8));
  20. //1,使用Base64 2,转成16进制
  21. return Base64.encodeBase64String(bytes);
  22. }
  23. /**
  24. * 解密
  25. * @param encodedText 加密后的字符串
  26. * @return
  27. * @throws Exception
  28. */
  29. public static String decrypt(String encodedText) throws Exception {
  30. //获取示例
  31. Cipher cipher = Cipher.getInstance(ALGORITHM);
  32. //创建加密规则
  33. SecretKey secretKey = new SecretKeySpec(KEY.getBytes(UTF8), ALGORITHM);
  34. //加密模式规则
  35. cipher.init(Cipher.DECRYPT_MODE,secretKey);
  36. byte[] bytes = cipher.doFinal(Base64.decodeBase64(encodedText.getBytes(UTF8)));
  37. //1,使用Base64
  38. return new String(bytes,UTF8);
  39. }
  40. public static void main(String[] args) throws Exception {
  41. String str = "张三写java";
  42. //加密
  43. String encodedText = encrypt(str);
  44. System.out.println("base64编码加密后的结果"+encodedText);
  45. //解密
  46. String decrypt = decrypt(encodedText);
  47. System.out.println("des解密后的结果"+decrypt);
  48. }
  49. }

结果:

 AES:16进制加密模式

  1. public class AesTest {
  2. //设置编码格式
  3. private static final String UTF8 = StandardCharsets.UTF_8.name();
  4. //aes默认key的长度 162432
  5. private static final String KEY = "12345678abcdefgh";
  6. //加密模式
  7. private static final String ALGORITHM = "AES";
  8. /**
  9. * 加密
  10. * @param text 加密内容
  11. * @return
  12. */
  13. public static String encrypt(String text) throws Exception {
  14. Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, KEY);
  15. byte[] bytes = cipher.doFinal(text.getBytes(UTF8));
  16. //转成16进制
  17. return HexUtils.converBytes(bytes);
  18. }
  19. /**
  20. * 解密
  21. * @param encodedText 16进制编码后的字符串
  22. * @return
  23. * @throws Exception
  24. */
  25. public static String decrypt(String encodedText) throws Exception {
  26. byte[] bytes = HexUtils.converHex2Bytes(encodedText);
  27. Cipher cipher = getCipher(Cipher.DECRYPT_MODE, KEY);
  28. byte[] decryptedBytes = cipher.doFinal(bytes);
  29. //2,转成16进制
  30. return new String(decryptedBytes,UTF8);
  31. }
  32. /**
  33. * 获取Cipher对象
  34. * @param type 加密解密模式
  35. * @param seed 密钥
  36. * @return
  37. * @throws Exception
  38. */
  39. public static Cipher getCipher(int type,String seed) throws Exception{
  40. //获取示例
  41. Cipher cipher = Cipher.getInstance(ALGORITHM);
  42. //创建加密规则
  43. SecretKey secretKey = new SecretKeySpec(seed.getBytes(UTF8), ALGORITHM);
  44. //加密模式规则
  45. cipher.init(type,secretKey);
  46. return cipher;
  47. }
  48. public static void main(String[] args) throws Exception {
  49. String str = "张三写java";
  50. //加密
  51. String encodedText = encrypt(str);
  52. System.out.println("16进制编码aes加密后的结果"+encodedText);
  53. //解密
  54. String decrypt = decrypt(encodedText);
  55. System.out.println("aes解密后的结果"+decrypt);
  56. }
  57. }

 

AES:16进制加密模式代码优化

  1. public class AesTest {
  2. //设置编码格式
  3. private static final String UTF8 = StandardCharsets.UTF_8.name();
  4. //aes默认key的长度 162432
  5. private static final String KEY = "12345678";
  6. //加密模式
  7. private static final String ALGORITHM = "AES";
  8. /**
  9. * 加密
  10. * @param text 加密内容
  11. * @return
  12. */
  13. public static String encrypt(String text) throws Exception {
  14. Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, KEY);
  15. byte[] bytes = cipher.doFinal(text.getBytes(UTF8));
  16. //转成16进制
  17. return HexUtils.converBytes(bytes);
  18. }
  19. /**
  20. * 解密
  21. * @param encodedText 16进制编码后的字符串
  22. * @return
  23. * @throws Exception
  24. */
  25. public static String decrypt(String encodedText) throws Exception {
  26. byte[] bytes = HexUtils.converHex2Bytes(encodedText);
  27. Cipher cipher = getCipher(Cipher.DECRYPT_MODE, KEY);
  28. byte[] decryptedBytes = cipher.doFinal(bytes);
  29. //2,转成16进制
  30. return new String(decryptedBytes,UTF8);
  31. }
  32. /**
  33. * 获取Cipher对象
  34. * @param type 加密解密模式
  35. * @param seed 密钥
  36. * @return
  37. * @throws Exception
  38. */
  39. public static Cipher getCipher(int type,String seed) throws Exception{
  40. //获取示例
  41. Cipher cipher = Cipher.getInstance(ALGORITHM);
  42. //创建加密规则
  43. //创建keyGenerator对象,可以根据传入的key生成一个指定长度的key
  44. KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
  45. //初始化secureRandom,并指定生成指定长度key的算法
  46. SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
  47. secureRandom.setSeed(seed.getBytes(UTF8));
  48. keyGenerator.init(128,secureRandom);
  49. //通过keyGenerator生成新的秘钥
  50. SecretKey secretKey = keyGenerator.generateKey();
  51. //获取到新秘钥的字节数组
  52. byte[] encoded = secretKey.getEncoded();
  53. SecretKeySpec secretKeySpec = new SecretKeySpec(encoded, ALGORITHM);
  54. //加密模式规则
  55. cipher.init(type,secretKeySpec);
  56. return cipher;
  57. }
  58. public static void main(String[] args) throws Exception {
  59. String str = "张三写java";
  60. //加密
  61. String encodedText = encrypt(str);
  62. System.out.println("16进制编码aes加密后的结果"+encodedText);
  63. //解密
  64. String decrypt = decrypt(encodedText);
  65. System.out.println("aes解密后的结果"+decrypt);
  66. }
  67. }

AES:base64加密模式 

  1. public class AesBase64Test {
  2. //设置编码格式
  3. private static final String UTF8 = StandardCharsets.UTF_8.name();
  4. private static final String KEY = "12345678";
  5. //加密模式
  6. private static final String ALGORITHM = "AES";
  7. /**
  8. * 加密
  9. * @param text 加密内容
  10. * @return
  11. */
  12. public static String encrypt(String text) throws Exception {
  13. Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, KEY);
  14. byte[] bytes = cipher.doFinal(text.getBytes(UTF8));
  15. //1,使用Base64 2,转成16进制
  16. return Base64.encodeBase64String(bytes);
  17. }
  18. /**
  19. * 解密
  20. * @param encodedText 加密后的字符串
  21. * @return
  22. * @throws Exception
  23. */
  24. public static String decrypt(String encodedText) throws Exception {
  25. Cipher cipher = getCipher(Cipher.DECRYPT_MODE, KEY);
  26. byte[] bytes = cipher.doFinal(Base64.decodeBase64(encodedText.getBytes(UTF8)));
  27. //1,使用Base64 2,转成16进制
  28. return new String(bytes,UTF8);
  29. }
  30. public static Cipher getCipher(int type,String seed) throws Exception{
  31. //获取示例
  32. Cipher cipher = Cipher.getInstance(ALGORITHM);
  33. //创建加密规则
  34. //创建keyGenerator对象,可以根据传入的key生成一个指定长度的key
  35. KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
  36. //初始化secureRandom,并指定生成指定长度key的算法
  37. SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
  38. secureRandom.setSeed(seed.getBytes(UTF8));
  39. keyGenerator.init(128,secureRandom);
  40. //通过keyGenerator生成新的秘钥
  41. SecretKey secretKey = keyGenerator.generateKey();
  42. //获取到新秘钥的字节数组
  43. byte[] encoded = secretKey.getEncoded();
  44. SecretKeySpec secretKeySpec = new SecretKeySpec(encoded, ALGORITHM);
  45. //加密模式规则
  46. cipher.init(type,secretKeySpec);
  47. return cipher;
  48. }
  49. /**
  50. * 测试
  51. * @param args
  52. * @throws Exception
  53. */
  54. public static void main(String[] args) throws Exception {
  55. String str = "张三写java";
  56. //加密
  57. String encodedText = encrypt(str);
  58. System.out.println("base64编码aes加密后的结果" + encodedText);
  59. //解密
  60. String decrypt = decrypt(encodedText);
  61. System.out.println("aes解密后的结果" + decrypt);
  62. }
  63. }

7、非对称加密

定义:加密和解密使用的是两个不同的密钥(public key和private key).公钥可以给任何人,私钥总

是自己保留。

常见算法:RSA

应用场景:

1、加解密:可以使用公钥加密,对应的就是私钥解密;也可以使用私钥加密,对应的就是公钥解

密。

  1. public class RSATest2 {
  2. public static final String CHARSET = "UTF-8";
  3. public static final String RSA_ALGORITHM = "RSA";
  4. //生成密钥对,一般来说执行一次就行
  5. public static Map<String, String> createKeys(int keySize) {
  6. //为RSA算法创建一个KeyPairGenerator对象(KeyPairGenerator,密钥对生成器,用于生成公钥和私钥对)
  7. KeyPairGenerator kpg;
  8. try {
  9. kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
  10. } catch (NoSuchAlgorithmException e) {
  11. throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
  12. }
  13. //初始化KeyPairGenerator对象,密钥长度
  14. kpg.initialize(keySize);
  15. //生成密匙对
  16. KeyPair keyPair = kpg.generateKeyPair();
  17. //得到公钥
  18. Key publicKey = keyPair.getPublic();
  19. String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded()); //返回一个publicKey经过二次加密后的字符串
  20. //得到私钥
  21. Key privateKey = keyPair.getPrivate();
  22. String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded()); //返回一个privateKey经过二次加密后的字符串
  23. Map<String, String> keyPairMap = new HashMap<String, String>();
  24. keyPairMap.put("publicKey", publicKeyStr);
  25. keyPairMap.put("privateKey", privateKeyStr);
  26. return keyPairMap;
  27. }
  28. /**
  29. * 得到公钥
  30. *
  31. * @param publicKey 密钥字符串(经过base64编码)
  32. * @throws Exception
  33. */
  34. public static RSAPublicKey getPublicKey(String publicKey) throws Exception {
  35. //通过X509编码的Key指令获得公钥对象
  36. KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
  37. X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
  38. RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
  39. return key;
  40. }
  41. /**
  42. * 得到私钥
  43. *
  44. * @param privateKey 密钥字符串(经过base64编码)
  45. * @throws Exception
  46. */
  47. public static RSAPrivateKey getPrivateKey(String privateKey) throws Exception {
  48. //通过PKCS#8编码的Key指令获得私钥对象
  49. KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
  50. PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
  51. RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
  52. return key;
  53. }
  54. /**
  55. * 公钥加密
  56. *
  57. * @param data
  58. * @param publicKey
  59. * @return
  60. */
  61. public static String publicEncrypt(String data, RSAPublicKey publicKey) {
  62. try {
  63. Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
  64. cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  65. return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));
  66. } catch (Exception e) {
  67. throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
  68. }
  69. }
  70. /**
  71. * 私钥解密
  72. *
  73. * @param data
  74. * @param privateKey
  75. * @return
  76. */
  77. public static String privateDecrypt(String data, RSAPrivateKey privateKey) {
  78. try {
  79. Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
  80. cipher.init(Cipher.DECRYPT_MODE, privateKey);
  81. return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET);
  82. } catch (Exception e) {
  83. throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
  84. }
  85. }
  86. /**
  87. * 私钥加密
  88. *
  89. * @param data
  90. * @param privateKey
  91. * @return
  92. */
  93. public static String privateEncrypt(String data, RSAPrivateKey privateKey) {
  94. try {
  95. Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
  96. cipher.init(Cipher.ENCRYPT_MODE, privateKey);
  97. return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength()));
  98. } catch (Exception e) {
  99. throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
  100. }
  101. }
  102. /**
  103. * 公钥解密
  104. *
  105. * @param data
  106. * @param publicKey
  107. * @return
  108. */
  109. public static String publicDecrypt(String data, RSAPublicKey publicKey) {
  110. try {
  111. Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
  112. cipher.init(Cipher.DECRYPT_MODE, publicKey);
  113. return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), publicKey.getModulus().bitLength()), CHARSET);
  114. } catch (Exception e) {
  115. throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
  116. }
  117. }
  118. private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) {
  119. int maxBlock = 0;
  120. if (opmode == Cipher.DECRYPT_MODE) {
  121. maxBlock = keySize / 8;
  122. } else {
  123. maxBlock = keySize / 8 - 11;
  124. }
  125. ByteArrayOutputStream out = new ByteArrayOutputStream();
  126. int offSet = 0;
  127. byte[] buff;
  128. int i = 0;
  129. try {
  130. while (datas.length > offSet) {
  131. if (datas.length - offSet > maxBlock) {
  132. buff = cipher.doFinal(datas, offSet, maxBlock);
  133. } else {
  134. buff = cipher.doFinal(datas, offSet, datas.length - offSet);
  135. }
  136. out.write(buff, 0, buff.length);
  137. i++;
  138. offSet = i * maxBlock;
  139. }
  140. } catch (Exception e) {
  141. throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e);
  142. }
  143. byte[] resultDatas = out.toByteArray();
  144. IOUtils.closeQuietly(out);
  145. return resultDatas;
  146. }
  147. //测试
  148. public static void main(String[] args) throws Exception {
  149. //生成公私钥
  150. Map<String, String> keyMap = RSATest2.createKeys(512);
  151. //公钥
  152. String publicKey = keyMap.get("publicKey");
  153. //私钥
  154. String privateKey = keyMap.get("privateKey");
  155. System.out.println("公钥加密——私钥解密");
  156. String str = "法外狂徒张三";
  157. System.out.println("明文:" + str);
  158. System.out.println("明文大小:" + str.getBytes().length);
  159. //对内容进行公钥加密
  160. String encodedData = RSATest2.publicEncrypt(str, RSATest2.getPublicKey(publicKey));
  161. System.out.println("公钥加密密文:" + encodedData);
  162. //用私钥对密文进行解密
  163. String decodedData = RSATest2.privateDecrypt(encodedData, RSATest2.getPrivateKey(privateKey));
  164. System.out.println("解密后文字: " + decodedData);
  165. }
  166. }

2、数字签名

3、数字信封

4、数字证书

参考视频:密码学-java信息安全,摘要算法,对称加密(AES)/非对称加密(RSA),一应俱全_哔哩哔哩_bilibili

非对称加密参考:java实现非对称加密(RSA)_qq_1473179505的博客-CSDN博客

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/898320
推荐阅读
相关标签
  

闽ICP备14008679号