Java加密

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
 
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Base64;
 
/**
 * @author binfirechen
 * @version 1.0
 * @date 2022/8/10 10:44
 */
public class EncryptTest {
 
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
 
    private String AESEncrypt(String source,String encrypKey) throws Exception{
        byte[] sourceByptes=source.getBytes("utf-8");
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encrypKey.getBytes(), "AES"));
        byte[] bytes = cipher.doFinal(sourceByptes);
        return Base64.getEncoder().encodeToString(bytes);
    }
 
    private String AESDecrypt(String source,String deencrypKey) throws Exception{
        byte[] bytes = decryptByBytes(Base64.getDecoder().decode(source), deencrypKey);
        return new String(bytes,"utf-8");
    }
 
    private byte[] decryptByBytes(byte[] encryptBytes, String deencrypKey) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(deencrypKey.getBytes(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return decryptBytes;
    }
 
    public static String getSHA256Str(String str) throws Exception {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        byte[] hash = messageDigest.digest(str.getBytes("UTF-8"));
        return Hex.encodeHexString(hash);
    }
 
    public static String encrypt(String content) throws UnsupportedEncodingException {
        String value =  DigestUtils.md5Hex(content.getBytes("UTF-8"));
        return value.toUpperCase();
 
    }
}

  

posted @   mick0802  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示