掃二維碼與項目經(jīng)理溝通
我們在微信上24小時期待你的聲音
解答本文疑問/技術(shù)咨詢/運營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流
前段時間再看關(guān)于JDK算法相關(guān)的知識時,看到很多與jdk中security包下的模塊有一定關(guān)聯(lián),之前對這塊一直沒有關(guān)注,趁此機會先做個簡單的了解。

本文旨在深入探討Java的Security技術(shù),包括其核心概念、關(guān)鍵模塊以及具體應(yīng)用。通過詳細分析,希望幫助讀者更好地理解如何在Java應(yīng)用程序中實現(xiàn)安全防護,提高系統(tǒng)的可靠性和穩(wěn)定性。
主要功能包括授權(quán)、訪問控制、數(shù)據(jù)加密、身份驗證等。
Java提供了對敏感信息的訪問控制功能,比如本地文件,類方法等的訪問約束,以此來組建安全的代碼框架
先看一個文件寫入的示例:
(1) 定義policy
grant {
permission com.sucl.blog.security.jdk.control.UserResourcePermission "read";
}(2) 編寫測試類
public class FileAccessController {
static {
// -Djava.security.manager
System.setSecurityManager( new SecurityManager() );
}
public static void main(String[] args) throws IOException {
SecurityManager securityManager = System.getSecurityManager();
if( securityManager == null ){
System.out.println("執(zhí)行文件寫入1");
writeHello("hello");
}else{
System.out.println("執(zhí)行文件寫入2");
AccessController.doPrivileged(new PrivilegedAction(3) 測試 cd 到target/classes
java -D"java.security.policy=path\file.policy" com.sucl.blog.security.jdk.control.file.FileAccessController上面的例子中如果沒有定義policy時,如果調(diào)用文件寫入方法,此時會拋出異常
java.security.AccessControlException: access denied ("java.io.FilePermission" "e:\home\file.txt" "write")這樣通過自定義polic編寫權(quán)限策略,則可以實現(xiàn)對資源訪問控制的效果。
如果看spring的源代碼,你會發(fā)現(xiàn)有很多類似AccessController.doPrivileged這樣的寫法,不知道當(dāng)時有沒考慮過其目的,雖然在調(diào)試時發(fā)現(xiàn)其根本沒有執(zhí)行
Java Security API提供了可互操作的算法和安全服務(wù)的實現(xiàn)。服務(wù)以provider的形式實現(xiàn),可以以插件的形式植入應(yīng)用程序中。 程序員可以透明地使用這些服務(wù),如此使得程序員可以集中精力在如何把安全組件集成到自己的應(yīng)用程序中,而不是去實現(xiàn)這些安全功能。 此外,除了Java提供的安全服務(wù)外,用戶可以編寫自定義的security provider,按需擴展Java的security平臺。
Java內(nèi)置的Provider提供了許多通用的密碼算法,比如:RSA, DSA, ECDSA等簽名算法、DES, AES, ARCFOUR等加密算法、MD5, SHA-1, SHA-256等 信息摘要算法、還有Diffie-Hellman和ECDH這樣的密鑰協(xié)商算法。下面簡單的實現(xiàn)了MD5、DES、RSA幾個我們常用的算法
(1) MD5
public class MD5 {
private static final Charset DEFAULT_CHARSET = Charset.defaultCharset();
static MessageDigest messageDigest;
static {
try {
messageDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}(2) DES
public class DES {
private static final String DES = "DES";
private static final int DEFAULT_ENCRYPT_CHUNK = 245;
private static final int DEFAULT_DECRYPT_CHUNK = 256;
private String salt;
private SecretKey secretKey;
public DES(String salt){
this.salt = salt;
initKey();
}
public void initKey(){
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance(DES);
SecureRandom secureRandom = new SecureRandom(salt.getBytes());
keyGenerator.init(secureRandom);
this.secretKey = keyGenerator.generateKey();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
public String encrypt(String text){
try {
Cipher cipher = Cipher.getInstance(DES);
cipher.init(Cipher.ENCRYPT_MODE, this.secretKey);
byte[] codes = text.getBytes();
int length = codes.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int check = 0;
byte[] cache ;
while (check < length){
int chunk = Math.min(DEFAULT_ENCRYPT_CHUNK, length-check);
cache = cipher.doFinal(codes, check, chunk);
check += chunk;
out.write(cache, 0, cache.length);
}
return Base64.getEncoder().encodeToString(out.toByteArray());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public String decrypt(String text){
try {
Cipher cipher = Cipher.getInstance(DES);
cipher.init(Cipher.DECRYPT_MODE, this.secretKey);
byte[] base64Text = Base64.getDecoder().decode(text);
int length = base64Text.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int check = 0;
byte[] cache ;
while (check < length){
int chunk = Math.min(DEFAULT_DECRYPT_CHUNK, length-check);
cache = cipher.doFinal(base64Text, check, chunk);
check += chunk;
out.write(cache, 0, cache.length);
}
return new String(out.toByteArray());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}(3) RSA
@Slf4j
public class RSA {
private static final String KEY_ALGORITHM = "RSA";
private static final int KEY_PAIR_SIZE = 2048;
/**
* 不大于245
*/
private static final int DEFAULT_ENCRYPT_CHUNK = 245;
/**
* 不大于256,改成其他值時:Decryption error
*/
private static final int DEFAULT_DECRYPT_CHUNK = 256;
/**
* NONEwithRSA
* MD5withRSA
* SHA256withRSA
*/
private static final String SIGN_ALGORITHM = "SHA256withRSA";
private static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";
private KeyPair keyPair;
public RSA() {
this.keyPair = getKeyPair();
}
/**
* 生成公鑰、私鑰
* @param key
* @return
*/
private KeyPair getKeyPair(){
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(KEY_PAIR_SIZE);
return keyPairGen.generateKeyPair();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 獲取公鑰
* @param base64PublicKey base64編碼的值 基于KeyPair公鑰
* @return
*/
private PublicKey getPublicKey(String base64PublicKey){
try {
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
KeySpec keySpec = new X509EncodedKeySpec(hexToBytes(base64PublicKey)); //
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 獲取私鑰
* @param base64PrivateKey base64編碼的值 基于KeyPair私鑰
* @return
*/
private PrivateKey getPrivateKey(String base64PrivateKey){
try {
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
// Security.addProvider(BouncyCastleProviderSingleton.getInstance());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(hexToBytes(base64PrivateKey));
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public String getPublicKey(){
return bytesToHex(keyPair.getPublic().getEncoded());
}
public String getPrivateKey(){
return bytesToHex(keyPair.getPrivate().getEncoded());
}
/**
* 通過私鑰簽名
* @param data
* @param privateKeyStr
* @return
*/
public String sign(byte[] data){
PrivateKey privateKey = getPrivateKey(getPrivateKey());
try {
Signature sig = Signature.getInstance(SIGN_ALGORITHM);
sig.initSign(privateKey);
sig.update(data);
return bytesToHex(sig.sign());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 校驗簽名
* @param data
* @param sign
* @param publicKeyStr
* @return
*/
public boolean verify(byte[] data, String sign){
PublicKey publicKey = getPublicKey(getPublicKey());
try {
Signature sig = Signature.getInstance(SIGN_ALGORITHM);
sig.initVerify(publicKey);
sig.update(data);
return sig.verify(hexToBytes(sign));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 通過公鑰加密
* @param text
* @param publicKey
* @return
*/
public String encrypt(String text){
byte[] codes = text.getBytes();
PublicKey publicKey = getPublicKey(getPublicKey());
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int length = codes.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int check = 0;
byte[] cache ;
while (check < length){
int chunk = Math.min(DEFAULT_ENCRYPT_CHUNK, length-check);
cache = cipher.doFinal(codes, check, chunk);
check += chunk;
out.write(cache, 0, cache.length);
}
return bytesToHex(out.toByteArray());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 通過私鑰解密
* @param text 加密內(nèi)容
* @param privateKeyStr
* @return
*/
public String decrypt(String text){
PrivateKey privateKey = getPrivateKey(getPrivateKey());
try {
byte[] base64Text = hexToBytes(text);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
int length = base64Text.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int check = 0;
byte[] cache ;
while (check < length){
int chunk = Math.min(DEFAULT_DECRYPT_CHUNK, length-check);
cache = cipher.doFinal(base64Text, check, chunk);
check += chunk;
out.write(cache, 0, cache.length);
}
return new String(out.toByteArray());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public byte[] hexToBytes(String str){
return Base64.getDecoder().decode(str);
}
public String bytesToHex(byte[] bytes){
return Base64.getEncoder().encodeToString(bytes);
}
}客戶端向服務(wù)器發(fā)送身份驗證請求。 服務(wù)器隨機生成一個挑戰(zhàn)參數(shù),發(fā)送給客戶端。 客戶端使用挑戰(zhàn)參數(shù)和密碼計算出響應(yīng)參數(shù),并將響應(yīng)參數(shù)發(fā)送給服務(wù)器。 服務(wù)器使用挑戰(zhàn)參數(shù)、用戶名和密碼計算出期望的響應(yīng)參數(shù),并將其與客戶端發(fā)送的響應(yīng)參數(shù)進行比較,以驗證客戶端的身份。
身份認證:
import javax.security.auth.login.LoginContext;
public class App {
public static void main(String[] args) {
URL url = ClassLoader.getSystemClassLoader().getResource("jaas.config");
System.setProperty("java.security.auth.login.config", url.getPath());
Subject subject = new Subject();
subject.getPrincipals().add(new User("admin"));
LoginContext loginContext = new LoginContext("app", subject);
loginContext.login();
}
}AppLoginModule:
@Slf4j
public class AppLoginModule implements LoginModule {
@Override
public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
log.info("initialize");
// 基于配置構(gòu)建認證環(huán)境
}
@Override
public boolean login() throws LoginException {
log.info("login");
return true;
}
@Override
public boolean commit() throws LoginException {
log.info("commit");
return true;
}
@Override
public boolean abort() throws LoginException {
log.info("abort");
return false;
}
@Override
public boolean logout() throws LoginException {
log.info("logout");
return false;
}
} jaas.config,放到classpath即可:
app {
com.sucl.blog.security.jdk.auth.AppLoginModule required
useTicketCache=true
doNotPrompt=true;
};相關(guān)這塊知識在網(wǎng)上找了一圈,發(fā)現(xiàn)很少有人講到,在編寫示例準備讓文心一言給出點提示,發(fā)現(xiàn)它只會傻傻的坑我,由于時間原因這塊內(nèi)容也沒有過多的深入, 通過關(guān)鍵接口的實現(xiàn),可以看到,在很多成熟的項目中都有被用到,可能jdk本身的模塊更多是應(yīng)用在構(gòu)建基礎(chǔ)系統(tǒng)架構(gòu)中吧。
java.security 包是 Java 安全框架的核心部分,上面說到它提供了各種類和接口來支持加密、解密、簽名、驗證等安全操作。下面簡單羅列了常用的工具類及其使用場景。
(1) KeyPairGenerator 和 KeyPair:
(2) Certificate 和 CertificateFactory:
(3) AlgorithmParameters 和 AlgorithmParameterGenerator:
(4) SecureRandom:
(5) KeyStore:
除了上述模塊,java.security 包還包含其他與安全相關(guān)的類和接口,如權(quán)限、策略等。這些模塊提供了更細粒度的安全控制和配置選項,適用于各種安全場景。 要了解全面的安全功能和用法,請參考 Java 官方文檔或相關(guān)資源。
Java Security技術(shù)提供了全面的安全防護機制,包括授權(quán)、訪問控制、數(shù)據(jù)加密、身份驗證等。通過深入了解和掌握這些技術(shù), 我們可以構(gòu)建更加安全、可靠的Java應(yīng)用程序。本文通過詳細介紹Java Security的核心模塊和代碼演示,旨在幫助讀者更好地理解和應(yīng)用這些技術(shù)。 未來,隨著技術(shù)的不斷發(fā)展,Java Security將會不斷完善和改進,為我們的應(yīng)用程序提供更加安全、可靠的保障。

我們在微信上24小時期待你的聲音
解答本文疑問/技術(shù)咨詢/運營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流