- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试加密然后解密音频文件。一切正常,但是当我尝试解密加密的音频时,每次我都会遇到这个异常
javax.crypto.BadPaddingException:填充 block 已损坏
我的MainActivity是这样的:我想一边解密一边播放这首歌
public class MainActivity extends Activity{
private final String KEY = "abc";
Button btn_Dec, btn_In;
byte[] incrept;
byte[] decrpt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx = this;
btn_Dec = (Button) findViewById(R.id.button2);
btn_In = (Button) findViewById(R.id.button1);
btn_Dec.setOnClickListener(btnDecListner);
btn_In.setOnClickListener(btnInListner);
}
public OnClickListener btnDecListner = new OnClickListener() {
public void onClick(View v) {
VincentFileCrypto simpleCrypto = new VincentFileCrypto();
try {
// decrypt the file here first argument is key and second is encrypted file which we get from SD card.
decrpt = simpleCrypto.decrypt(KEY, getAudioFileFromSdCard());
//play decrypted audio file.
playMp3(decrpt);
} catch (Exception e) {
e.printStackTrace();
}
}
};
Context ctx;
public OnClickListener btnInListner = new OnClickListener() {
public void onClick(View v) {
VincentFileCrypto simpleCrypto = new VincentFileCrypto();
try {
// encrypt audio file send as second argument and corresponding key in first argument.
incrept = simpleCrypto.encrypt(KEY, getAudioFile());
//Store encrypted file in SD card of your mobile with name vincent.mp3.
FileOutputStream fos = new FileOutputStream(new File("/sdcard/vincent.mp3"));
fos.write(incrept);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
};
/**
* @return byte array for encryption.
* @throws FileNotFoundException
*/
public byte[] getAudioFile() throws FileNotFoundException
{
byte[] audio_data = null;
byte[] inarry = null;
AssetManager am = ctx.getAssets();
try {
InputStream is = am.open("Sleep Away.mp3"); // use recorded file instead of getting file from assets folder.
int length = is.available();
audio_data = new byte[length];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = is.read(audio_data)) != -1)
{
output.write(audio_data, 0, bytesRead);
}
inarry = output.toByteArray();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inarry;
}
/**
* This method fetch encrypted file which is save in sd card and convert it in byte array after that this file will be decrept.
*
* @return byte array of encrypted data for decription.
* @throws FileNotFoundException
*/
public byte[] getAudioFileFromSdCard() throws FileNotFoundException
{
byte[] inarry = null;
try {
//getting root path where encrypted file is stored.
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "vincent.mp3"); //Creating file object
//Convert file into array of bytes.
FileInputStream fileInputStream = null;
byte[] bFile = new byte[(int) file.length()];
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
inarry = bFile;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inarry;
}
/**
* This Method is used to play audio file after decrepting.
*
* @param mp3SoundByteArray : This is our audio file which will be play and it converted in byte array.
*/
private void playMp3(byte[] mp3SoundByteArray) {
try {
// create temp file that will hold byte array
File tempMp3 = File.createTempFile("kurchina", "mp3", getCacheDir());
tempMp3.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tempMp3);
fos.write(mp3SoundByteArray);
fos.close();
// Tried reusing instance of media player
// but that resulted in system crashes...
MediaPlayer mediaPlayer = new MediaPlayer();
FileInputStream fis = new FileInputStream(tempMp3);
mediaPlayer.setDataSource(fis.getFD());
mediaPlayer.prepareAsync();
mediaPlayer.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
加密和解密方法都在这个类中提到
public class VincentFileCrypto {
public byte[] encrypt(String seed, byte[] cleartext) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext);
// return toHex(result);
return result;
}
public byte[] decrypt(String seed, byte[] encrypted) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] enc = encrypted;
byte[] result = decrypt(rawKey, enc);
return result;
}
//done
private byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
}
最佳答案
经过几天的研究和努力,我找到了解决方案,可能会帮助并节省其他人的时间。这是我的答案。我把上面的代码逻辑改成这样
现在发生了什么,我能够成功加密文件并将其保存在 sdcard 中,然后解密播放。没有其他人可以播放音频。
我们开始吧:快乐的编码
public class Main2Activity extends AppCompatActivity {
private String encryptedFileName = "encrypted_Audio.mp3";
private static String algorithm = "AES";
static SecretKey yourKey = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//saveFile("Hello From CoderzHeaven asaksjalksjals");
try {
saveFile(getAudioFile());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
decodeFile();
}
public static SecretKey generateKey(char[] passphraseOrPin, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
// Number of PBKDF2 hardening rounds to use. Larger values increase
// computation time. You should select a value that causes computation
// to take >100ms.
final int iterations = 1000;
// Generate a 256-bit key
final int outputKeyLength = 256;
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(passphraseOrPin, salt, iterations, outputKeyLength);
SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
return secretKey;
}
public static SecretKey generateKey() throws NoSuchAlgorithmException {
// Generate a 256-bit key
final int outputKeyLength = 256;
SecureRandom secureRandom = new SecureRandom();
// Do *not* seed secureRandom! Automatically seeded from system entropy.
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(outputKeyLength, secureRandom);
yourKey = keyGenerator.generateKey();
return yourKey;
}
public static byte[] encodeFile(SecretKey yourKey, byte[] fileData)
throws Exception {
byte[] encrypted = null;
byte[] data = yourKey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(data, 0, data.length, algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(
new byte[cipher.getBlockSize()]));
encrypted = cipher.doFinal(fileData);
return encrypted;
}
public static byte[] decodeFile(SecretKey yourKey, byte[] fileData)
throws Exception {
byte[] decrypted = null;
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, yourKey, new IvParameterSpec(new byte[cipher.getBlockSize()]));
decrypted = cipher.doFinal(fileData);
return decrypted;
}
void saveFile(byte[] stringToSave) {
try {
File file = new File(Environment.getExternalStorageDirectory() + File.separator, encryptedFileName);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
yourKey = generateKey();
byte[] filesBytes = encodeFile(yourKey, stringToSave);
bos.write(filesBytes);
bos.flush();
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
void decodeFile() {
try {
byte[] decodedData = decodeFile(yourKey, readFile());
// String str = new String(decodedData);
//System.out.println("DECODED FILE CONTENTS : " + str);
playMp3(decodedData);
} catch (Exception e) {
e.printStackTrace();
}
}
public byte[] readFile() {
byte[] contents = null;
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator, encryptedFileName);
int size = (int) file.length();
contents = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(
new FileInputStream(file));
try {
buf.read(contents);
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return contents;
}
public byte[] getAudioFile() throws FileNotFoundException
{
byte[] audio_data = null;
byte[] inarry = null;
AssetManager am = getAssets();
try {
InputStream is = am.open("Sleep Away.mp3"); // use recorded file instead of getting file from assets folder.
int length = is.available();
audio_data = new byte[length];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = is.read(audio_data)) != -1) {
output.write(audio_data, 0, bytesRead);
}
inarry = output.toByteArray();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inarry;
}
private void playMp3(byte[] mp3SoundByteArray) {
try {
// create temp file that will hold byte array
File tempMp3 = File.createTempFile("kurchina", "mp3", getCacheDir());
tempMp3.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tempMp3);
fos.write(mp3SoundByteArray);
fos.close();
// Tried reusing instance of media player
// but that resulted in system crashes...
MediaPlayer mediaPlayer = new MediaPlayer();
FileInputStream fis = new FileInputStream(tempMp3);
mediaPlayer.setDataSource(fis.getFD());
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
关于android - 如何加密和解密音频文件android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37274768/
我有一个 C# 应用程序调用 Java 网络服务来验证用户密码。我想让 C# 应用程序加密密码,然后让 Java Web 服务解密密码。我已经完成了 Java 端的代码(解密代码),但我无法找出 C#
我正在使用以下代码在使用 openssl 的 Windows 中使用 C 加密和解密二进制数据。如您所见,在这两个函数中,我都知道纯文本的大小。有什么方法可以在不知道纯文本大小的情况下解密消息? #i
已关闭。此问题需要 debugging details 。目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and the
我有一个非常恼人的问题,Java中使用RSA算法对字符串进行不可靠的加密和解密。它似乎只能在大约 35% 的时间内工作,而且我不明白为什么它有时能工作,有时却不能。这是我写的一些测试代码,试图验证加密
我已经设法编写了用于文件加密/解密的函数。但它非常慢,尤其是随着文件大小的增加。例如几MB长的音频/视频文件 我几乎浏览了所有帖子来改进它,并尝试更改算法。如果有任何更改可以帮助我提高性能,请帮助我。
我正在尝试让我的转置密码发挥作用。 每当我将加密方法得到的密文输入解密方法时,我应该得到原始的明文......但事实并非如此...... 我做错了什么? 感谢您的帮助! public String E
我正在使用密码来加密和解密消息: public String encrypt(String string) throws InvalidKeyException, IllegalBlockSizeEx
我有一个在 MySQL 中存储数据的 spring-mvc 堆栈。其中一些数据需要保护,所以我想我应该加密它。由于我以后可能需要使用这些数据(信用卡、SSN 等),所以我需要对其进行解密。我认为这排除
作为一名SEOER,都想了解百度算法,通过算法原理来找到捷径的优化方案,那么今天我把研究多年的百度算法原理解密给大家,可能不是最好的,但是我可以给大家保证,这些都是非常实际的。希望给SEOER带来一
我试图找到一种技术来加密和解密程序中的文件,而无需将密码硬编码到程序中,也无需向用户询问密码。 如果我也可以从我正在编写的另一个程序中解密文件,那就太好了。 到目前为止,我还没有多少运气找到一种看起来
有没有一种方法可以使用作为字符串参数传递给程序的私钥而不是使用存储在机器上的证书来解密 PowerShell 中的 RSA?欢迎任何帮助,我的代码如下。 Function Decrypt-Asymme
通过问题Is it possible to use the Grails Jasypt plugin outside the GORM layer for simple String encrypti
我需要解密/加密我的域类中的几列,并且正在寻找有关如何做的信息。我已经找到了jasypt加密插件,但不幸的是它似乎与Grails 2.4不兼容。 我可能可以将一些东西拼凑在一起,但是想要确保Im遵循最
我需要有关声音文件加密/解密的帮助。我想在存储这个声音文件时加密一个声音文件,并在播放这个文件时解密它。我阅读了有关 java 中的加密/解密以及 java 中可用于此的大量示例代码。但这些程序不适用
我很感兴趣是否可以使用 Excel Visual Basic 和某些加密服务提供程序进行字符串加密/解密。 我找到了一个演练 Encrypting and Decrypting Strings in
我们正在使用加密/解密和UIIMAGE。如果我们在不保存到iphone画廊的情况下进行加密和解密以及UIIMAge,则可以正常工作,但是,如果我们进行加密,保存到画廊,将(加密的图像)加载到应用程序中
我正在做一个像这样的简单程序: package rsaexample; import java.io.*; import java.math.BigInteger; import java.secur
我发现这段代码返回给定字符串的校验和。 public static String getChecksum(String md5) { int counter = 0; while (c
我在 Java SE 和 Android 项目上使用相同的代码。在 Java 和 Android 中运行的应用程序连接到相同的 MQTT 代理并交换消息。消息使用 AES 进行加密/解密。我对 Jav
我想在 openssl/libcrypto 中使用 RSA 加密/解密一个长文件(我知道 AES 更好,但这只是为了比较)。我将输入文件分成大小为 numBlocks = inputFileLengt
我是一名优秀的程序员,十分优秀!