我上了这个课:
public class KeyCrypter {
private SecureRandom secRandom;
private static final String ALGORITHM = "DESede"; //with "PBEWithMD5AndDES" say 'KeyGenerator PBEWithMD5AndDES implementation not found'
private static KeyCrypter mInstance = null;
public static KeyCrypter getInstance() {
if (mInstance == null) {
mInstance = new KeyCrypter();
}
return mInstance;
}
protected byte[] encrypt(String str) {
try {
secRandom = new SecureRandom();
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
keyGenerator.init(secRandom);
SecretKey key = keyGenerator.generateKey();
Cipher encrypter = Cipher.getInstance(ALGORITHM);
encrypter.init(Cipher.ENCRYPT_MODE, key);
byte[] utf8 = str.getBytes(StandardCharsets.UTF_8);
byte[] enc = encrypter.doFinal(utf8);
return Base64.encode(enc, Base64.NO_PADDING);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected String decrypt(String str) {
try {
secRandom = new SecureRandom();
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
keyGenerator.init(secRandom);
SecretKey key = keyGenerator.generateKey();
Cipher decrypter = Cipher.getInstance(ALGORITHM);
decrypter.init(Cipher.DECRYPT_MODE, key);
byte[] dec = Base64.decode(str.getBytes(), Base64.NO_PADDING);
byte[] utf8 = decrypter.doFinal(dec);
return new String(utf8, StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
如果您看这种简单的方法,我只想加密一个String,然后再解密,但是每次使用不同的“算法”时,我都有“ BadPaddingException”。请有人帮我。