英文:
I need to read the @salt_key@ and @Secret_key from properties file in Java. i.e declared in Java code
问题
@Bean
@Scope("prototype")
protected SecretKeySpec secretkey() throws InvalidKeySpecException, NoSuchAlgorithmException {
String secretKey = "Fra@d@15gt";
String salt = "Sa@t5dS3@";
KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
SecretKey tmp = secretKeyFactory().generateSecret(spec);
SecretKeySpec secretKey1 = new SecretKeySpec(tmp.getEncoded(), "AES");
return secretKey1;
}
英文:
@Bean
@Scope("prototype")
protected SecretKeySpec secretkey() throws InvalidkeySpecException,
NoSuchAlgorithamException {
String secretKey = "Fra@d@15gt";
String salt = "Sa@t5dS3@";
KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
SecretKey tmp = secretKeyFactory().generateSecret(spec);
SecretKeySpec secretKey1 = new SecretKeySpec(tmp.getEncoded(), "AES");
return secretKey1;
}
答案1
得分: 1
首先在配置文件中存储secretKey和salt,如下所示:
secretKey=Fra@d@15gt
salt=Sa@t5dS3@
然后在Java代码中读取它,如下所示:
@Bean
@Scope("prototype")
protected SecretKeySpec secretkey(@Value("${secretKey}") final String secretKey,
@Value("${salt}") final String salt)
throws InvalidKeySpecException, NoSuchAlgorithmException {
KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
SecretKey tmp = secretKeyFactory().generateSecret(spec);
SecretKeySpec secretKey1 = new SecretKeySpec(tmp.getEncoded(), "AES");
return secretKey1;
}
确保在 @Value
内部的字符串与您在配置文件中保存的内容完全匹配。对于不同的环境(如生产/质量保证/本地),将会有不同的secretKey和salt。对于每个环境,您可以创建具有环境特定值的单独文件。
英文:
First store secretKey and salt in configuration file like below:
secretKey=Fra@d@15gt
salt=Sa@t5dS3@
Then read it in java code as below:
@Bean
@Scope("prototype")
protected SecretKeySpec secretkey(@Value("${secretKey}") final String secretKey,
@Value("${salt}") final String salt)
throws InvalidkeySpecException, NoSuchAlgorithamException {
KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
SecretKey tmp = secretKeyFactory().generateSecret(spec);
SecretKeySpec secretKey1 = new SecretKeySpec(tmp.getEncoded(), "AES");
return secretKey1;
}
Make sure that string inside @Value
should match exactly as what you have saved inside configuration file.
For different environments (like production/QA/local) there would be different secretKey and salt. For each environment, you can create separate files with environment-specific values.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论