0
암호화 된 문자열을 나중에 암호 해독 할 수 있도록 XML 파일에 키를 저장하려고하는데이 소프트웨어는 암호화하여 "Encrypt()"메소드에서 나를 반환하지만 오류를 반환합니다. 은 "해독()"방법을비밀 키를 문자열로 저장합니다.
코드
private static Cipher ecipher;
private static Cipher dcipher;
public static String[] encrypt(String str) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {
String Key, res;
SecretKey key;
String[] Return = new String[2];
key = KeyGenerator.getInstance("DES").generateKey();
ecipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
enc = BASE64EncoderStream.encode(enc);
res = new String(enc);
//Returning values 0 = Encrypted String 1 = Key For Storage in XML
Return[0] = res;
byte[] keyBytes = key.getEncoded();
Key = new String(keyBytes,"UTF8");
Return[1] = Key;
return Return;
}
public static String decrypt(String str, String Key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, UnsupportedEncodingException, BadPaddingException {
SecretKey key = new SecretKeySpec(Key.getBytes("UTF8"), "DES");
dcipher = Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, key);
byte[] dec = BASE64DecoderStream.decode(str.getBytes());
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
}
콘솔 반환 사용하려고 할 때 :
run:
Encryped String : EB6uhzsBl08=
Key : �g�uX8p
Sep 07, 2014 6:35:17 PM Software.Software main
SEVERE: null
java.security.InvalidKeyException: Invalid key length: 12 bytes
at com.sun.crypto.provider.DESCipher.engineGetKeySize(DESCipher.java:373)
at javax.crypto.Cipher.passCryptoPermCheck(Cipher.java:1062)
at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1020)
at javax.crypto.Cipher.implInit(Cipher.java:796)
at javax.crypto.Cipher.chooseProvider(Cipher.java:859)
at javax.crypto.Cipher.init(Cipher.java:1229)
at javax.crypto.Cipher.init(Cipher.java:1166)
at Software.Encryption.decrypt(Encryption.java:51)
at Software.Software.main(main.java:30)
BUILD SUCCESSFUL (total time: 1 second)
암호화 키의 무작위 바이트가 유효한 UTF8이 아닙니다. base64가 필요합니다. – SLaks
@SLaks base64를 utf8로 변환하고 다시 base64로 변환 할 수있는 방법이 있습니까? –
그건 말이되지 않습니다. http://en.wikipedia.org/wiki/Base64 http://en.wikipedia.org/wiki/UTF-8 – SLaks