2014-11-02 2 views
0

Я новичок в android, и теперь я создаю приложение для Android, чтобы зашифровать и скрыть данные, как часть моего мини-проекта. Не могли бы вы рассказать мне код для шифрования и дешифрования этих изображений в андроиде с использованием алгоритма AES. ??Как шифровать и дешифровать изображения в Android?

+0

Вы еще что-то пробовали? возможно, сначала попытайтесь сначала зашифровать/дешифровать строки, тогда вы поймете, что это все о байтах 'byte []' :) – Yazan

+0

Множество примеров - просто выполните небольшой поиск. – Henry

+0

У меня есть зашифрованные строки до сих пор ... и теперь мне нужно зашифровать изображения и аудио ... –

ответ

1

Вы можете использовать библиотеку криптографии java. Вот пример того, что вы можете сделать:

byte[] keyBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 
    0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 }; //Choose a key wisely 

SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); 

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC"); 

fis = new FileInputStream("some_img.png"); 
cis = new CipherInputStream(fis, cipher); 
fos = new FileOutputStream("encrypted_img.enc"); 
byte[] b = new byte[8]; 
int i = cis.read(b); 
while (i != -1) { 
    fos.write(b, 0, i); 
    i = cis.read(b); 
} 
fos.close(); 

Смотри на http://docs.oracle.com/javase/7/docs/technotes/guides/security/crypto/

0

Вот статические методы шифрования и дешифрования с AES надеюсь, что это поможет.

public static void encrypt (final byte[] key, 
     final String filename, 
     final String newFilename, 
     final Context context, 
     final EncryptionActionListener listener) { 

    final Handler uiHandler = new Handler(); 
    final ProgressDialog progressDialog = new ProgressDialog(context); 
    progressDialog.setMessage(context.getString(R.string.encrypt_progress_message)); 
    progressDialog.setCancelable(false); 
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
    progressDialog.setMax(100); 
    progressDialog.setProgress(0); 
    progressDialog.show(); 

    Thread task = new Thread("Encrypt thread") { 
     public void run() { 
      boolean deleteSuccess = true; 
      boolean outOfMem = false; 
      boolean exception = false; 

      try { 
       File file = new File(filename); 
       int length = (int)file.length(); 

       byte fileBytes[] = new byte[1024*100]; 

       if (!createLeadingFolders(newFilename)) { 
        throw new IOException("Could not create folders in path " + newFilename); 
       } 

       InputStream is = new FileInputStream(filename); 
       OutputStream os = new FileOutputStream(newFilename);  
       AESOutputStream aos = new AESOutputStream(os, key, length); 

       int totalRead = 0; 
       int partialRead = 0; 
       while (true) { 
        partialRead = is.read(fileBytes); 
        if (partialRead == -1) { 
         break; 
        } else { 
         totalRead += partialRead; 
         aos.write(fileBytes, 0, partialRead); 
         final int percentage = (totalRead * 100)/length; 
         uiHandler.post(new Runnable() { 
          public void run() { 
           progressDialog.setProgress(percentage); 
          } 
         }); 
        } 
       } 

       is.close(); 
       aos.close(); 
       os.close(); 

       deleteSuccess = file.delete(); 

       AESImageAdapter.delete(context, filename); 

       if (listener != null) 
        listener.onActionComplete(); 

       Intent i = new Intent(ACTION_ENCRYPTED_FILES_CHANGED); 
       context.sendBroadcast(i); 

      } catch (OutOfMemoryError e) { 
       e.printStackTrace(); 
       outOfMem = true; 
      } catch (Exception e) { 
       e.printStackTrace(); 
       exception = true; 
      } finally { 
       progressDialog.dismiss(); 
       if (exception) { 
        errorDialog(uiHandler, context.getString(R.string.encrypt_error), context); 
       } else if (outOfMem) { 
        errorDialog(uiHandler, context.getString(R.string.memory_error), context); 
       } else if (!deleteSuccess) { 
        errorDialog(uiHandler, context.getString(R.string.encrypt_delete_error), context); 
       } 
      } 
     } 
    }; 

    task.start(); 
} 




/** 
* Asynchronously decrypt the chosen file. 
* @param keyString Key to decrypt with 
* @param filename Name of file to decrypt 
* @param newFilename Name to save newly decrypted file 
* @param dialog An optional progress dialog to update with progress 
* @param adapter An optional adapter to notify when the encryption is finished 
* @param context Must supply context 
* @return 
*/ 
public static void decrypt (final byte[] key, 
     final String filename, 
     final String newFilename, 
     final Context context, 
     final EncryptionActionListener listener) { 

    final Handler uiHandler = new Handler(); 
    final ProgressDialog progressDialog = new ProgressDialog(context); 
    progressDialog.setMessage(context.getString(R.string.decrypt_progress_message)); 
    progressDialog.setCancelable(false); 
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
    progressDialog.setMax(100); 
    progressDialog.setProgress(0); 
    progressDialog.show(); 

    Thread task = new Thread("Decrypt thread") { 
     public void run() { 
      boolean deleteSuccess = true; 
      boolean outOfMem = false; 
      boolean exception = false; 

      try { 
       File file = new File(filename); 
       int length = (int)file.length(); 

       byte fileBytes[] = new byte[1024*100]; 

       if (!createLeadingFolders(newFilename)) { 
        throw new IOException("Could not create folders in path " + newFilename); 
       } 

       InputStream is = new FileInputStream(filename); 
       OutputStream os = new FileOutputStream(newFilename);  
       AESInputStream ais = new AESInputStream(is, key); 

       int totalRead = 0; 
       int partialRead = 0; 
       while (true) { 
        partialRead = ais.read(fileBytes); 
        if (partialRead == -1) { 
         break; 
        } else { 
         totalRead += partialRead; 
         os.write(fileBytes, 0, partialRead); 
         final int percentage = (totalRead * 100)/length; 
         uiHandler.post(new Runnable() { 
          public void run() { 
           progressDialog.setProgress(percentage); 
          } 
         }); 
        } 
       } 

       ais.close(); 
       is.close(); 
       os.close(); 

       deleteSuccess = file.delete(); 

       // Run the media scanner to discover the decrypted file exists 
       MediaScannerConnection.scanFile(context, 
         new String[] { newFilename }, 
         null, 
         null); 

       if (listener != null) 
        listener.onActionComplete(); 

       Intent i = new Intent(ACTION_ENCRYPTED_FILES_CHANGED); 
       context.sendBroadcast(i); 

      } catch (OutOfMemoryError e) { 
       e.printStackTrace(); 
       outOfMem = true; 
      } catch (Exception e) { 
       e.printStackTrace(); 
       exception = true; 
      } finally { 
       progressDialog.dismiss(); 
       if (exception) { 
        errorDialog(uiHandler, context.getString(R.string.decrypt_error), context); 
       } else if (outOfMem) { 
        errorDialog(uiHandler, context.getString(R.string.memory_error), context); 
       } else if (!deleteSuccess) { 
        errorDialog(uiHandler, context.getString(R.string.decrypt_delete_error), context); 
       } 
      } 
     } 
    }; 

    task.start(); 
} 

для более подробного примера зашифровать или расшифровать файл изображения с AES вы можете по этой ссылке https://github.com/charlesconnell/ImageHider/tree/master/src/com/connell/imagehider

+2

Хотя эта ссылка может ответить на вопрос, лучше включить здесь основные части ответа и предоставить ссылку для справки. Ответные ссылки могут стать недействительными, если связанная страница изменится. –

+0

Спасибо, человек, я отредактировал свой ответ, спасибо! @Hidden Hobbes –

+0

Я пробовал, но это очень медленно – HendraWD

0

Вы можете использовать следующие методы для шифрования или дешифрования медиа-файлов, таких как видео или изображения -

public class Encrypter { 
private final static int DEFAULT_READ_WRITE_BLOCK_BUFFER_SIZE = 1024; 
private final static String ALGO_VIDEO_ENCRYPTOR = "AES/CBC/PKCS5Padding"; 

@SuppressWarnings("resource") 
public static void encrypt(SecretKey key, 
     AlgorithmParameterSpec paramSpec, InputStream in, OutputStream out) 
     throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, 
     InvalidAlgorithmParameterException, IOException { 
    try { 
     Cipher c = Cipher.getInstance(ALGO_VIDEO_ENCRYPTOR); 
     c.init(Cipher.ENCRYPT_MODE, key, paramSpec); 
     out = new CipherOutputStream(out, c); 
     int count = 0; 
     byte[] buffer = new byte[DEFAULT_READ_WRITE_BLOCK_BUFFER_SIZE]; 
     while ((count = in.read(buffer)) >= 0) { 
      out.write(buffer, 0, count); 
     } 
    } finally { 
     out.close(); 
    } 
} 
@SuppressWarnings("resource") 
public static void decrypt(SecretKey key, AlgorithmParameterSpec paramSpec, 
     InputStream in, OutputStream out) 
     throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, 
     InvalidAlgorithmParameterException, IOException { 
    try { 
     Cipher c = Cipher.getInstance(ALGO_VIDEO_ENCRYPTOR); 
     c.init(Cipher.DECRYPT_MODE, key, paramSpec); 
     out = new CipherOutputStream(out, c); 
     int count = 0; 
     byte[] buffer = new byte[DEFAULT_READ_WRITE_BLOCK_BUFFER_SIZE]; 
     while ((count = in.read(buffer)) >= 0) { 
      out.write(buffer, 0, count); 
     } 
    } finally { 
     out.close(); 
    } 
} 
} 

Здесь я шифрую видео. Например, следующая моя MainActivity, которая использует эти методы для шифрования видеофайла.

public class MainActivity extends AppCompatActivity { 
private final static String ALGO_RANDOM_NUM_GENERATOR = "SHA1PRNG"; 
private final static String ALGO_SECRET_KEY_GENERATOR = "AES"; 
private final static int IV_LENGTH = 16; 
Cursor mVideoCursor; 
ArrayList<HashMap<String, String>> listOfVideo; 
@Override protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    listOfVideo = new ArrayList(); 
    String[] videoColumns = {MediaStore.Video.Media.DATA,MediaStore.Video.Media.DURATION, 
    MediaStore.Video.Media.SIZE,MediaStore.Video.Media.DISPLAY_NAME}; 
    mVideoCursor = getApplicationContext().getContentResolver().query 
      (MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoColumns, null, null, null); 
    mVideoCursor.moveToFirst(); 
    for (int i = 0; i < mVideoCursor.getCount(); i++) { 
     listOfVideo.add(new HashMap<String, String>() { 
      { 
       put("data", String.valueOf(mVideoCursor.getString( 
       mVideoCursor.getColumnIndex(MediaStore.Video.Media.DATA)))); 
       put("duration", String.valueOf(mVideoCursor.getString(
       mVideoCursor.getColumnIndex(MediaStore.Video.Media.DURATION)))); 
       put("displayName", String.valueOf(mVideoCursor.getString(
       mVideoCursor.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME)))); 
       put("size", String.valueOf(mVideoCursor.getString(
       mVideoCursor.getColumnIndex(MediaStore.Video.Media.SIZE)))); 
       mVideoCursor.moveToNext(); 

      } 
     }); 
    } 

    String path = listOfVideo.get(0).get("data"); 
    File inFile = new File(listOfVideo.get(0).get("data")); 
    File outFile = new File(path.substring(0, path.lastIndexOf("/"))+"/enc_video.swf"); 
    File outFile_dec = new File(path.substring(0, path.lastIndexOf("/"))+"/dec_video.mp4"); 

    try { 
     SecretKey key = KeyGenerator.getInstance(ALGO_SECRET_KEY_GENERATOR).generateKey(); 
     byte[] keyData = key.getEncoded(); 
     SecretKey key2 = new SecretKeySpec(keyData, 0, keyData.length, ALGO_SECRET_KEY_GENERATOR); 
     byte[] iv = new byte[IV_LENGTH]; 
     SecureRandom.getInstance(ALGO_RANDOM_NUM_GENERATOR).nextBytes(iv); 
     AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv); 

     Encrypter.encrypt(key, paramSpec, 
     new FileInputStream(inFile), new FileOutputStream(outFile)); 
     Encrypter.decrypt(key2, paramSpec, 
     new FileInputStream(outFile), new FileOutputStream(outFile_dec)); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 

} 
Смежные вопросы