【架构实战】数据加密架构:传输加密+存储加密

张开发
2026/4/11 9:14:00 15 分钟阅读

分享文章

【架构实战】数据加密架构:传输加密+存储加密
涓€銆佹暟鎹姞瀵嗘杩?鏁版嵁鍔犲瘑鏄繚鎶ゆ暟鎹畨鍏ㄧ殑閲嶈鎵嬫锛?*鍔犲瘑鍦烘櫙锛?浼犺緭鍔犲瘑锛圚TTPS锛?- 瀛樺偍鍔犲瘑锛堟晱鎰熸暟鎹級瀵嗛挜绠悊浜屻€佷紶杈撳姞瀵?1. HTTPS閰嶇疆ConfigurationpublicclassSSLConfig{BeanpublicTomcatServletWebServerFactoryservletContainer(){TomcatServletWebServerFactorytomcatnewTomcatServletWebServerFactory();tomcat.setProtocol(org.apache.coyote.http11.Http11NioProtocol);SSLsslnewSSL();ssl.setKeyStore(classpath:keystore.p12);ssl.setKeyStorePassword(password);ssl.setKeyStoreType(PKCS12);ConnectorconnectornewConnector(org.apache.coyote.http11.Http11NioProtocol);connector.setScheme(https);connector.setSecure(true);connector.setPort(8443);connector.setProperty(sslProtocol,TLS);tomcat.addAdditionalTomcatConnectors(connector);returntomcat;}}2. 璇佷功閰嶇疆# application.ymlserver:ssl:enabled:truekey-store:classpath:keystore.p12key-store-password:passwordkey-store-type:PKCS12key-alias:mycert涓夈€佸绉板姞瀵?1. AES鍔犲瘑ServicepublicclassAESEncryptionService{privatestaticfinalStringALGORITHMAES;privatestaticfinalStringTRANSFORMATIONAES/ECB/PKCS5Padding;Value(${encryption.aes.key})privateStringsecretKey;publicStringencrypt(Stringplaintext){try{SecretKeySpeckeySpecnewSecretKeySpec(secretKey.getBytes(),ALGORITHM);CiphercipherCipher.getInstance(TRANSFORMATION);cipher.init(Cipher.ENCRYPT_MODE,keySpec);byte[]encryptedcipher.doFinal(plaintext.getBytes());returnBase64.getEncoder().encodeToString(encrypted);}catch(Exceptione){thrownewRuntimeException(鍔犲瘑澶辫触,e);}}publicStringdecrypt(Stringciphertext){try{SecretKeySpeckeySpecnewSecretKeySpec(secretKey.getBytes(),ALGORITHM);CiphercipherCipher.getInstance(TRANSFORMATION);cipher.init(Cipher.DECRYPT_MODE,keySpec);byte[]decryptedcipher.doFinal(Base64.getDecoder().decode(ciphertext));returnnewString(decrypted);}catch(Exceptione){thrownewRuntimeException(瑙瘑澶辫触,e);}}}2. 瀛楁鍔犲瘑ComponentpublicclassFieldEncryptionConverterimplementsAttributeConverterString,String{AutowiredprivateAESEncryptionServiceencryptionService;OverridepublicStringconvertToDatabaseColumn(Stringattribute){returnStringUtils.isEmpty(attribute)?attribute:encryptionService.encrypt(attribute);}OverridepublicStringconvertToEntityAttribute(StringdbData){returnStringUtils.isEmpty(dbData)?dbData:encryptionService.decrypt(dbData);}}鍥涖€侀潪瀵圭О鍔犲瘑1. RSA鍔犲瘑ServicepublicclassRSAEncryptionService{publicKeyPairgenerateKeyPair()throwsNoSuchAlgorithmException{KeyPairGeneratorgeneratorKeyPairGenerator.getInstance(RSA);generator.initialize(2048);returngenerator.generateKeyPair();}publicStringencrypt(Stringplaintext,PublicKeypublicKey)throwsException{CiphercipherCipher.getInstance(RSA);cipher.init(Cipher.ENCRYPT_MODE,publicKey);byte[]encryptedcipher.doFinal(plaintext.getBytes());returnBase64.getEncoder().encodeToString(encrypted);}publicStringdecrypt(Stringciphertext,PrivateKeyprivateKey)throwsException{CiphercipherCipher.getInstance(RSA);cipher.init(Cipher.DECRYPT_MODE,privateKey);byte[]decryptedcipher.doFinal(Base64.getDecoder().decode(ciphertext));returnnewString(decrypted);}}2. 鏁板瓧绛惧悕ServicepublicclassSignatureService{publicStringsign(Stringdata,PrivateKeyprivateKey)throwsException{SignaturesignatureSignature.getInstance(SHA256withRSA);signature.initSign(privateKey);signature.update(data.getBytes());returnBase64.getEncoder().encodeToString(signature.sign());}publicbooleanverify(Stringdata,StringsignatureStr,PublicKeypublicKey)throwsException{SignaturesignatureSignature.getInstance(SHA256withRSA);signature.initVerify(publicKey);signature.update(data.getBytes());returnsignature.verify(Base64.getDecoder().decode(signatureStr));}}浜斻€佸搱甯屽姞瀵?1. 瀵嗙爜鍝堝笇ServicepublicclassPasswordHashService{publicStringhashPassword(Stringpassword){returnBCryptPasswordEncoder.encode(password);}publicbooleanverifyPassword(Stringpassword,StringhashedPassword){returnnewBCryptPasswordEncoder().matches(password,hashedPassword);}}2. 鏁版嵁瀹屾暣鎬?ServicepublicclassHashService{publicStringmd5(Stringdata){returnDigestUtils.md5Hex(data);}publicStringsha256(Stringdata){returnDigestUtils.sha256Hex(data);}publicStringhmacSha256(Stringdata,Stringkey){try{SecretKeySpecsecretKeynewSecretKeySpec(key.getBytes(),HmacSHA256);MacmacMac.getInstance(HmacSHA256);mac.init(secretKey);byte[]hmacmac.doFinal(data.getBytes());returnBase64.getEncoder().encodeToString(hmac);}catch(Exceptione){thrownewRuntimeException(e);}}}鍏€佸瘑閽ョ鐞?1. 瀵嗛挜杞崲ServicepublicclassKeyRotationService{Value(${encryption.key.version})privateintcurrentVersion;publicvoidrotateKey()throwsException{// 1. 鐢熸垚鏂板瘑閽? KeyPair newKeyPair rsaService.generateKeyPair();// 2. 鍔犲瘑鏃у瘑閽ョ殑鏁版嵁MapInteger,StringencryptedKeysnewHashMap();// ... 浣跨敤鏂板瘑閽ュ姞瀵嗘棫瀵嗛挜// 3. 瀛樺偍鏂板瘑閽? keyStore.store(newKeyPair, currentVersion 1);// 4. 鏇存柊鐗堟湰鍙? currentVersion;}}2. 瀵嗛挜鎵樼ConfigurationpublicclassKMSConfig{BeanpublicAWSSimpleSystemsManagementawsSSM(){returnAWSSimpleSystemsManagementClientBuilder.defaultClient();}}ServicepublicclassKMSKeyService{AutowiredprivateAWSSimpleSystemsManagementawsSSM;publicStringgetKey(StringkeyId){GetParameterRequestrequestnewGetParameterRequest().withName(keyId).withWithDecryption(true);returnawsSSM.getParameter(request).getParameter().getValue();}}涓冦€佹晱鎰熸暟鎹繚鎶?1. 瀛楁鑴辨晱ComponentpublicclassSensitiveDataFilter{SensitiveField(typeMaskingType.PHONE)publicStringmaskPhone(Stringphone){if(phonenull)returnnull;returnphone.substring(0,3)****phone.substring(7);}SensitiveField(typeMaskingType.ID_CARD)publicStringmaskIdCard(StringidCard){if(idCardnull)returnnull;returnidCard.substring(0,6)********idCard.substring(14);}}2. 鍏ㄩ摼璺姞瀵?ComponentpublicclassEndToEndEncryptionService{// 绔埌绔姞瀵嗙ず渚? public String encryptForRecipient(String plaintext, String recipientPublicKey)throwsException{// 1. 鐢熸垚闅忔満瀵圭О瀵嗛挜KeyGeneratorkeyGenKeyGenerator.getInstance(AES);keyGen.init(256);SecretKeysymmetricKeykeyGen.generateKey();// 2. 鐢ㄥ绉板瘑閽ュ姞瀵嗘暟鎹? Cipher aesCipher Cipher.getInstance(AES);aesCipher.init(Cipher.ENCRYPT_MODE,symmetricKey);byte[]encryptedDataaesCipher.doFinal(plaintext.getBytes());// 3. 鐢ㄦ帴鏀惰€呭叕閽ュ姞瀵嗗绉板瘑閽? Cipher rsaCipher Cipher.getInstance(RSA);rsaCipher.init(Cipher.ENCRYPT_MODE,getPublicKey(recipientPublicKey));byte[]encryptedKeyrsaCipher.doFinal(symmetricKey.getEncoded());// 4. 杩斿洖鍔犲瘑鍚庣殑鏁版嵁鍜屽瘑閽? return Base64.getEncoder().encodeToString(encryptedData) : Base64.getEncoder().encodeToString(encryptedKey);}}鍏€佹€荤粨鏁版嵁鍔犲瘑鏄繚鎶ゆ暟鎹畨鍏ㄧ殑鍩虹锛?浼犺緭鍔犲瘑锛欻TTPS/TLS瀛樺偍鍔犲瘑锛欰ES/RSA瀵嗛挜绠悊锛氳疆鎹?鎵樼鏁忔劅淇濇姢锛氳劚鏁?鍏ㄩ摼璺姞瀵?*涓汉瑙傜偣锛屼粎渚涘弬鑰?

更多文章