gpt4 book ai didi

java - InvalidKeyException 加密-解密文件 - Java/Android

转载 作者:行者123 更新时间:2023-12-02 06:19:39 25 4
gpt4 key购买 nike

我正在使用以下示例:

http://compscipleslab.wordpress.com/category/java/

但是我遇到了异常,当我记录异常时,它出现在我的 logcat 中,说明:InvalidKeyException

我不确定我到底做错了什么。我还没有真正修改教程中的方法(也许这就是问题所在),所以我不确定为什么会出现此错误。

来源:

   public class FileChooser extends ListActivity {

private File currentDir;
private File moveToDir;
private FileArrayAdapter adapter;
public static String TAG = "DEBUG THIS:";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentDir = new File("/sdcard/");
fill(currentDir);
registerForContextMenu(getListView());
// get the attachment's filename
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
String attachmentFileName = preferences.getString("fileName", "");

// save the attachment
try {
InputStream attachment = getContentResolver().openInputStream(
getIntent().getData());

File savedFile = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), attachmentFileName);
FileOutputStream f = new FileOutputStream(savedFile);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = attachment.read(buffer)) > 0) {
f.write(buffer);
}
f.close();
} catch (Exception e) {
}
}

// File Manager Source to view SD Card or Internal Storage Contents
private void fill(File f) {
File[] dirs = f.listFiles();
this.setTitle("Current Dir: " + f.getName());
List<Item> dir = new ArrayList<Item>();
List<Item> fls = new ArrayList<Item>();
try {
for (File ff : dirs) {
Date lastModDate = new Date(ff.lastModified());
DateFormat formater = DateFormat.getDateTimeInstance();
String date_modify = formater.format(lastModDate);
if (ff.isDirectory()) {

File[] fbuf = ff.listFiles();
int buf = 0;
if (fbuf != null) {
buf = fbuf.length;
} else
buf = 0;
String num_item = String.valueOf(buf);
if (buf == 0)
num_item = num_item + " item";
else
num_item = num_item + " items";

// String formated = lastModDate.toString();
dir.add(new Item(ff.getName(), num_item, date_modify, ff
.getAbsolutePath(), "directory_icon"));
} else {

fls.add(new Item(ff.getName(), ff.length() + " Byte",
date_modify, ff.getAbsolutePath(), "file_icon"));
}
}
} catch (Exception e) {

}
Collections.sort(dir);
Collections.sort(fls);
dir.addAll(fls);
if (!f.getName().equalsIgnoreCase("sdcard"))
dir.add(0, new Item("..", "Parent Directory", "", f.getParent(),
"directory_up"));
adapter = new FileArrayAdapter(FileChooser.this, R.layout.file_view,
dir);
this.setListAdapter(adapter);
}

// onClick listener to move back one directory
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Item o = adapter.getItem(position);
if (o.getImage().equalsIgnoreCase("directory_icon")
|| o.getImage().equalsIgnoreCase("directory_up")) {
currentDir = new File(o.getPath());
fill(currentDir);
} else {
onFileClick(o);
}
}

// open file onClick
private void onFileClick(Item o) {

Intent intent = new Intent();
intent.putExtra("GetPath", currentDir.toString());
intent.putExtra("GetFileName", o.getName());
setResult(RESULT_OK, intent);
finish();
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Context Menu");
menu.add(0, v.getId(), 0, "Copy");
menu.add(0, v.getId(), 0, "Paste");
menu.add(0, v.getId(), 0, "Delete");
menu.add(0, v.getId(), 0, "Encrypt");
menu.add(0, v.getId(), 0, "Decrypt");
}

@Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == "Copy") {
function1(item.getItemId());
}
if (item.getTitle() == "Paste") {
function2(item.getItemId());
}
if (item.getTitle() == "Delete") {
function3(item.getItemId());
}
if (item.getTitle() == "Encrypt") {
function4(item.getItemId());
}
if (item.getTitle() == "Decrypt") {
function5(item.getItemId());
} else {
}
return false;

}

public void function1(int id) {
Toast.makeText(this, "Copy", Toast.LENGTH_SHORT).show();

try {

File sd = Environment.getExternalStorageDirectory();
currentDir = new File(sd.getAbsolutePath());
moveToDir = new File(sd.getAbsolutePath());
copyDirectoryOneLocationToAnotherLocation(currentDir, currentDir);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

public void function2(int id) {

Toast.makeText(this, "Paste", Toast.LENGTH_SHORT).show();
}

public void function3(int id) {
Toast.makeText(this, "Delete", Toast.LENGTH_SHORT).show();
DeleteRecursive(currentDir);
}

public void function4(int id) {
Toast.makeText(this, "Encrypt", Toast.LENGTH_SHORT).show();
//encrypt(null, null, null);
// encrypt(String PlaintextFile, String Key, String CiphertextFile);
encrypt("D:\\plaintext.txt", "testkey", "D:\\ciphertext.txt");
}

public void function5(int id) {
Toast.makeText(this, "Decrypt", Toast.LENGTH_SHORT).show();
decrypt(null, null, null);
// decrypt(String PlaintextFile, String Key, String CiphertextFile);

}

private void DeleteRecursive(File fileOrDirectory) {

if (fileOrDirectory.isDirectory()) {
File[] children = fileOrDirectory.listFiles();
if (null != children) {
for (File child : children)
DeleteRecursive(child);
}
}

fileOrDirectory.delete();

}

public static void copyDirectoryOneLocationToAnotherLocation(
File sourceLocation, File targetLocation) throws IOException {

if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}

String[] children = sourceLocation.list();
for (int i = 0; i < sourceLocation.listFiles().length; i++) {

copyDirectoryOneLocationToAnotherLocation(new File(
sourceLocation, children[i]), new File(targetLocation,
children[i]));
}
} else {

InputStream in = new FileInputStream(Environment
.getExternalStorageDirectory().getPath());

OutputStream out = new FileOutputStream(Environment
.getExternalStorageDirectory().getPath());
Log.d("TEST", "source: " + in);
Log.d("TEST", "target: " + out);

// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}

}

public static void encrypt(String PlaintextFile, String Key,
String CiphertextFile) {
try {
byte[] KeyData = Key.getBytes();
SecretKeySpec KS = new SecretKeySpec(KeyData, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, KS);
FileInputStream fis = new FileInputStream(PlaintextFile);
CipherInputStream cis = new CipherInputStream(fis, cipher);
FileOutputStream fos = new FileOutputStream(CiphertextFile);
byte[] b = new byte[1024];
int i = cis.read(b);
while (i != -1) {
fos.write(b, 0, i);
i = cis.read(b);
}
fos.flush();
fos.close();
fis.close();
cis.close();
System.out.println("Encryption Successfull !!!");

} catch (NoSuchAlgorithmException exception) {
// do something.

Thread.currentThread().getStackTrace();
} catch (NoSuchPaddingException exception) {
// do something (else?).
Thread.currentThread().getStackTrace();
} catch (InvalidKeyException exception) {
// do something.
Thread.currentThread().getStackTrace();
} catch (IOException exception) {
// do something (else?).
Thread.currentThread().getStackTrace();

}

}

public static void decrypt(String CiphertextFile, String Key,
String DecipheredFile) {
try {
byte[] KeyData = Key.getBytes();
SecretKeySpec KS = new SecretKeySpec(KeyData, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, KS);
FileInputStream fis = new FileInputStream(CiphertextFile);
FileOutputStream fos = new FileOutputStream(DecipheredFile);
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
byte[] b = new byte[1024];
int i = fis.read(b);
while (i != -1) {
cos.write(b, 0, i);
i = fis.read(b);
}
fos.flush();
fos.close();
fis.close();
cos.flush();
cos.close();
System.out.println("Decryption Successfull !!!");

} catch (NoSuchAlgorithmException exception) {
// do something.

Thread.currentThread().getStackTrace();
} catch (NoSuchPaddingException exception) {
// do something (else?).
Thread.currentThread().getStackTrace();
} catch (InvalidKeyException exception) {
// do something.
Thread.currentThread().getStackTrace();
} catch (IOException exception) {
// do something (else?).
Thread.currentThread().getStackTrace();

}

}
public static void main(String[] args) {
encrypt("D:\\plaintext.txt", "testkey", "D:\\ciphertext.txt");
decrypt("D:\\ciphertext.txt", "testkey", "D:\\originaltext.txt");
}
}

日志:

01-14 17:53:07.904: I/SurfaceTextureClient(9545): [STC::queueBuffer] (this:0x5f1c6d58) fps:6.11, dur:2780.41, max:2503.10, min:13.29
01-14 17:53:07.905: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:07.905: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:07.958: V/Provider/Settings(9545): invalidate [system]: current 6 != cached 0
01-14 17:53:07.963: V/Provider/Settings(9545): from db cache, name = sound_effects_enabled , value = 0
01-14 17:53:07.966: D/skia(9545): Flag is not 10
01-14 17:53:07.976: W/System.err(9545): java.security.InvalidKeyException: Key length not 128/192/256 bits.
01-14 17:53:07.983: W/System.err(9545): at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineInit(BaseBlockCipher.java:578)
01-14 17:53:07.983: W/System.err(9545): at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineInit(BaseBlockCipher.java:625)
01-14 17:53:07.983: W/System.err(9545): at javax.crypto.Cipher.init(Cipher.java:519)
01-14 17:53:07.983: W/System.err(9545): at javax.crypto.Cipher.init(Cipher.java:479)
01-14 17:53:07.983: W/System.err(9545): at com.idg.voiscphone.FileChooser.encrypt(FileChooser.java:276)
01-14 17:53:07.984: W/System.err(9545): at com.idg.voiscphone.FileChooser.function4(FileChooser.java:209)
01-14 17:53:07.984: W/System.err(9545): at com.idg.voiscphone.FileChooser.onContextItemSelected(FileChooser.java:169)
01-14 17:53:07.984: W/System.err(9545): at android.app.Activity.onMenuItemSelected(Activity.java:2597)
01-14 17:53:07.984: W/System.err(9545): at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:3663)
01-14 17:53:07.984: W/System.err(9545): at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
01-14 17:53:07.985: W/System.err(9545): at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
01-14 17:53:07.985: W/System.err(9545): at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
01-14 17:53:07.985: W/System.err(9545): at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:167)
01-14 17:53:07.985: W/System.err(9545): at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:963)
01-14 17:53:07.985: W/System.err(9545): at android.widget.AdapterView.performItemClick(AdapterView.java:298)
01-14 17:53:07.985: W/System.err(9545): at android.widget.AbsListView.performItemClick(AbsListView.java:1128)
01-14 17:53:07.986: W/System.err(9545): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2812)
01-14 17:53:07.986: W/System.err(9545): at android.widget.AbsListView$1.run(AbsListView.java:3571)
01-14 17:53:07.986: W/System.err(9545): at android.os.Handler.handleCallback(Handler.java:725)
01-14 17:53:07.986: W/System.err(9545): at android.os.Handler.dispatchMessage(Handler.java:92)
01-14 17:53:07.986: W/System.err(9545): at android.os.Looper.loop(Looper.java:153)
01-14 17:53:07.987: W/System.err(9545): at android.app.ActivityThread.main(ActivityThread.java:5297)
01-14 17:53:07.987: W/System.err(9545): at java.lang.reflect.Method.invokeNative(Native Method)
01-14 17:53:07.987: W/System.err(9545): at java.lang.reflect.Method.invoke(Method.java:511)
01-14 17:53:07.987: W/System.err(9545): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
01-14 17:53:07.988: W/System.err(9545): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
01-14 17:53:07.988: W/System.err(9545): at dalvik.system.NativeStart.main(Native Method)
01-14 17:53:07.989: D/OpenGLRenderer(9545): Flushing caches (mode 0)
01-14 17:53:08.013: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.013: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.028: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.028: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.052: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.053: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.054: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.076: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.076: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.076: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.078: V/InputMethodManager(9545): onWindowFocus: android.widget.ListView{4206e2c0 VFED.VCL .F...... 0,0-720,1126 #102000a android:id/list} softInputMode=16 first=false flags=#1810100
01-14 17:53:08.091: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.091: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.091: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.092: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.092: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.092: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.097: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0
01-14 17:53:08.102: W/Trace(9545): Unexpected value from nativeGetEnabledTags: 0

最佳答案

您的代码存在一个问题,即您为 CipherSecretKeySpec 实例指定的算法不相同。您正在混合两种不同的算法。

与引用示例一样,两个实例保持相同:

错误行:

SecretKeySpec KS = new SecretKeySpec(KeyData, "Blowfish");
Cipher cipher = Cipher.getInstance("AES");

您可以考虑阅读 AES vs Blowfish here .

编辑:

如前所述,整个解决方案将严格使用 AES。因此,您设置的 key 不是有效的 AES key - AES key 是 128、192 或 256 位(从您的异常(exception)情况也可以看出)。这意味着您当前的 key 应该为 16、24 或 32 字节(尽管 testkey 为 7)。

考虑以下因素:

  1. 按照引用将算法更改为 Blowfish,它将接受您的 key
  2. 尝试将 key 更改为 16 字节(例如:ThisSecurityKey1)。可能需要考虑您的字符编码(UTF-8、UTF-16),但由于您使用的是纯文本,因此它应该可以工作。
  3. 查找KeyGenerator类,可用于生成对称 key 。

This class provides the functionality of a secret (symmetric) key generator.

此外,请尝试引用更好的 AES 加密示例 - 您选择的引用文献充满了不兼容的 Java 编码标准。

关于java - InvalidKeyException 加密-解密文件 - Java/Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21124475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com