WindowとLinuxはプラットフォームJAVAにまたがってプログラミングする注意事項
5229 ワード
このブログは開発中に発生したプラットフォームをまたぐJAVAプログラムの異常状況と処理を記録します。
パス処理絶対パスを書かないでください。
経路はルートディレクトリから 直接使用しないでください。
上記のようにFile.separatorを使用します。 は、Custoom FileUtilsなどのツールを自分で作って経路をつなぎ合わせることができます。
windowsで暗号化したら、Linuxから復号すると
SecureRandomはオペレーティングシステム自体の内部状態に完全に従うことを実現するためであり、起動者がgetInstance方法を起動してからsetSeed方法を起動しない限り、
この実装はwindows上では毎回生成されるkeyは同じであるが、solarisまたは一部のlinuxシステムでは異なる。SecureRandom類の詳細については、SecureRandomを参照してください。
解決方法:
パス処理
C:\\admin\\test
のように経路はルートディレクトリから
config
または静的なクラスを使用して構成されるべきで、このように比較的に変更されやすい。たとえば:
public static class ComStatic {
String ROOT_FOLDER = "ROOT";
String FILE_TEMP = "TEMP";
String WINDOWS_HOME = "C\:";
String LINUX_HOME = "/opt";
}
class myClass {
public void doSomething() {
// : C:/ROOT/TEMP
String static ROOT_PATH_WINDOWS = String.format("%s%s%s%s%s",
ComStatic.WINDOWS_HOME, File.separator, ComStatic.ROOT_FOLDER,
File.separator,ComStatic.FILE_TEMP);
// : /opt/ROOT/TEMP
String static ROOT_PATH_LINUX = String.format("%s%s%s%s%s",
ComStatic.LINUX_HOME, File.separator, ComStatic.ROOT_FOLDER,
File.separator, ComStatic.FILE_TEMP);
}
}
上記のようにFile.separatorを使用します。
/** * * @param pathList a, b, c, d * @return a/b/c/d */
public static String parsePath(String ... pathList){
if(pathList.length == 0){
return "";
}
StringBuilder sb = new StringBuilder();
for(String o : pathList){
sb.append(o).append(File.separator);
}
return sb.toString().substring(0,sb.length()-1);
}
暗号解読問題windowsで暗号化したら、Linuxから復号すると
javax.crypto.BadPaddingException:Given final block not properly padded
が現れます。SecureRandomはオペレーティングシステム自体の内部状態に完全に従うことを実現するためであり、起動者がgetInstance方法を起動してからsetSeed方法を起動しない限り、
この実装はwindows上では毎回生成されるkeyは同じであるが、solarisまたは一部のlinuxシステムでは異なる。SecureRandom類の詳細については、SecureRandomを参照してください。
解決方法:
//
/** * * * @param secretKey * @return * @throws NoSuchAlgorithmException */
private SecretKey generateKey(String secretKey) throws NoSuchAlgorithmException{
/* */
SecureRandom secureRandom = new SecureRandom(secretKey.getBytes());
KeyGenerator kg = null;
try {
kg = KeyGenerator.getInstance(DES_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
}
kg.init(secureRandom);
//
return kg.generateKey();
}
/** * * * @param secretKey * @return * @throws NoSuchAlgorithmException */
private SecretKey generateKey(String secretKey) throws NoSuchAlgorithmException{
// linux key
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
/* */
secureRandom.setSeed(secretKey.getBytes());
KeyGenerator kg = null;
try {
kg = KeyGenerator.getInstance(DES_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
}
kg.init(secureRandom);
//
return kg.generateKey();
}