encrypt:
KeyGenerator keyGenerator = KeyGenerator.getInstance("TripleDES");
keyGenerator.init(168);
SecretKey key = keyGenerator.generateKey();
System.out.println("Done generating the key.");
// Create a cipher using that key to initialize it
Cipher cipher = Cipher.getInstance("TripleDES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plaintextBytes = msg.getBytes();
// Perform the actual encryption
byte[] cipherText = cipher.doFinal(plaintextBytes);
// Now we need to Base64-encode it for ascii display
BASE64Encoder encoder = new BASE64Encoder();
String output = encoder.encode(cipherText);
System.out.println("Ciphertext: "+output);
/* Create a keystore and place the key in it
* We're using a jceks keystore, which is provided by Sun's JCE.
* If you don't have the JCE installed, you can use "JKS",
* which is the default keystore. It doesn't provide
* the same level of protection however.
*/
KeyStore keyStore = KeyStore.getInstance("JCEKS");
// This initializes a blank keystore
keyStore.load(null, null);
// Now we add the key to the keystore, protected
// by the password.
keyStore.setKeyEntry("exampleKey", key, pass.toCharArray(), null);
// Store the password to the filesystem, protected
// by the same password.
FileOutputStream fos = new FileOutputStream(FILENAME);
keyStore.store(fos, pass.toCharArray());
fos.close();
decrypt:
KeyStore keyStore = KeyStore.getInstance("JCEKS");
FileInputStream fis = new FileInputStream(FILENAME);
keyStore.load(fis, pass.toCharArray());
fis.close();
SecretKey key = (SecretKey)keyStore.getKey("exampleKey",pass.toCharArray());
// Create a cipher using that key to initialize it
Cipher cipher = Cipher.getInstance("TripleDES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
// Perform the decryption, first BASE64 decoding the ciphertext
byte[] ciphertextBytes = new BASE64Decoder().decodeBuffer(from);
byte[] decryptedText = cipher.doFinal(ciphertextBytes);
String output = new String(decryptedText);
System.out.println("Plaintext: "+output);
σφάλμα:
Απρ 18, 2014 5:46:16 ΜΜ chatserver.server5 run
SEVERE: null
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:750)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
at com.sun.crypto.provider.DESedeCipher.engineDoFinal(DESedeCipher.java:294)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
Στην εντολή "byte[] decryptedText = cipher.doFinal(ciphertextBytes);" έχει το παραπάνω σφάλμα. Ξέρει κανείς πως το μέγεθος του input θα το κάνω πολλαπλάσιο του 8?