introduction
In modern software development, data encryption is a very important link, especially when processing sensitive information (such as price, user data, etc.). This article will provide detailed descriptions on how to implement price encryption using Java and optimize code to improve its robustness, maintainability, and performance.
1. Background
In advertising trading systems, price information usually needs to be encrypted to ensure its security. Google's DoubleClick Ad Exchange provides an encryption scheme that encrypts prices using the HMAC-SHA1 algorithm. This article will implement a price encryption tool based on this solution and gradually optimize the code.
2. Achieve price encryption
2.1 Encryption principle
DoubleClick's encryption scheme uses two keys:
- Encryption Key: Used to encrypt price data.
- Integrity Key: Used to generate signatures to ensure the integrity of the data.
The encrypted data format is as follows:
initVector:16 || E(payload:?) || I(signature:4)
in:
-
initVector
is the initialization vector, including the timestamp and server ID. -
E(payload)
It is encrypted price data. -
I(signature)
It is a complete signature.
2.2 Basic implementation
The following is the basic price encryption implementation:
import ; import ; import .Base64; public class PriceEncryptor { private static final String HMAC_ALGORITHM = "HmacSHA1"; /** * Encrypted price * * @param winPrice price string * @param enKey encryption key (Base64 encoding) * @param ivKey Integrity Key (Base64 Encoding) * @return Encrypted price string (Base64 encoding) * @throws IllegalArgumentException if the parameter is invalid * @throws RuntimeException If encryption fails */ public static String priceEncrypt(String winPrice, String enKey, String ivKey) { // Parameter verification (winPrice, "The price cannot be empty"); (enKey, "The encryption key cannot be empty"); (ivKey, "The integrity key cannot be empty"); if (().isEmpty()) { throw new IllegalArgumentException("The price cannot be an empty string"); } try { // Convert price to double double priceValue = (winPrice); // parse the key SecretKey encryptionKey = decodeBase64ToSecretKey(enKey, HMAC_ALGORITHM); SecretKey integrityKey = decodeBase64ToSecretKey(ivKey, HMAC_ALGORITHM); // Create encryption tools keys = new (encryptionKey, integrityKey); crypto = new (keys); // Encrypted price return (priceValue, null); } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid price format: " + winPrice, e); } catch (Exception e) { throw new RuntimeException("Encryption failed", e); } } /** * Convert Base64 encoded key to SecretKey * * @param base64Key Base64 Encoded key * @param algorithm key algorithm * @return SecretKey * @throws IllegalArgumentException if key is invalid */ private static SecretKey decodeBase64ToSecretKey(String base64Key, String algorithm) { try { byte[] keyBytes = ().decode(base64Key); return new SecretKeySpec(keyBytes, algorithm); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Invalid Base64 Key: " + base64Key, e); } } public static void main(String[] args) { try { String bidPrice = priceEncrypt("88", "your_base64_encoded_enKey", "your_base64_encoded_ivKey"); ("Encrypted price:" + bidPrice); } catch (Exception e) { ("Encryption failed: " + ()); (); } } }
2.3 Code Description
-
Parameter verification:
- use
examine
winPrice
、enKey
andivKey
Is itnull
。 - examine
winPrice
Whether it is an empty string.
- use
-
Exception handling:
- Capture
NumberFormatException
, provide clear error information. - Catch other exceptions and throw them uniformly
RuntimeException
。
- Capture
-
Key resolution:
- Convert Base64 encoded key to
SecretKey
。
- Convert Base64 encoded key to
-
Encryption logic:
- use
Encrypt the price.
- use
3. Optimize the code
3.1 Parameter verification
In encryption methods, parameter verification is essential. We useTo ensure that the parameters are not
null
, and check if the price string is empty.
(winPrice, "The price cannot be empty"); (enKey, "The encryption key cannot be empty"); (ivKey, "The integrity key cannot be empty"); if (().isEmpty()) { throw new IllegalArgumentException("The price cannot be an empty string"); }
3.2 Exception handling
To provide better error information, we captureNumberFormatException
And throwIllegalArgumentException
. Other exceptions will be thrown uniformlyRuntimeException
。
try { double priceValue = (winPrice); // ... } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid price format: " + winPrice, e); } catch (Exception e) { throw new RuntimeException("Encryption failed", e); }
3.3 Code reuse
Encapsulate key parsing logic intodecodeBase64ToSecretKey
In the method, avoid duplicate code.
private static SecretKey decodeBase64ToSecretKey(String base64Key, String algorithm) { try { byte[] keyBytes = ().decode(base64Key); return new SecretKeySpec(keyBytes, algorithm); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Invalid Base64 Key: " + base64Key, e); } }
3.4 Performance optimization
ifpriceEncrypt
Methods will be called frequently, you can considerand
The instances of are cached to avoid repeated creation.
private static final Map<String, > CRYPTO_CACHE = new ConcurrentHashMap<>(); private static getCrypto(String enKey, String ivKey) { String cacheKey = enKey + "|" + ivKey; return CRYPTO_CACHE.computeIfAbsent(cacheKey, k -> { SecretKey encryptionKey = decodeBase64ToSecretKey(enKey, HMAC_ALGORITHM); SecretKey integrityKey = decodeBase64ToSecretKey(ivKey, HMAC_ALGORITHM); keys = new (encryptionKey, integrityKey); return new (keys); }); }
Then inpriceEncrypt
Use in the methodgetCrypto
GetExample.
crypto = getCrypto(enKey, ivKey); return (priceValue, null);
4. Summary
Through the above steps, we have implemented a robust and efficient price encryption tool. The optimized code has the following advantages:
- Strongness: Passing parameter checksum exception handling, ensure that the code can run normally in exceptional situations.
- Maintainability: Through code reuse and modular design, the readability and maintainability of the code are improved.
- performance: Reduces the overhead of repeatedly creating objects by caching encryption tool instances.
This is the end of this article about using Java to implement price encryption and optimization functions. For more related Java price encryption and optimization content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!