des虽然方便,但是不安全,不建议使用,可以使用sm4代替
//psw:加密的文本,pswkey:加密的密码,即密钥
String psw="123",pswkey="999";
//对该DES情况下加密,密钥需要为56位难以人工由string为根据设定,因此这里:
//借助密钥生成器,由new SecureRandom(pswkey.getBytes()),以pswkey为种子值生成密钥
KeyGenerator keyGenerator= null;
try {
keyGenerator = KeyGenerator.getInstance("DES");
keyGenerator.init(56,new SecureRandom(pswkey.getBytes()));
Key key=keyGenerator.generateKey();
//加密,DES/ECB/pkcs5padding为:算法/模式/填充 的参数
//参数new BouncyCastleProvider()也可修改为"BC",要求前面要有Security.addProvider(new BouncyCastleProvider());
Cipher cipher=Cipher.getInstance("DES/ECB/pkcs5padding","BC");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] out=cipher.doFinal(psw.getBytes());
System.out.println(out);//字节数组,没有编码
Log.d("qweqweqweqweq", "加密: "+out);
//解密
Cipher cipher2=Cipher.getInstance("DES/ECB/pkcs5padding","BC");
cipher2.init(Cipher.DECRYPT_MODE, key);
byte[] in=cipher2.doFinal(out);
System.out.println(new String(in));
Log.d("qweqweqweqweq", "解密: "+new String(in));
} catch (Exception e) {
e.printStackTrace();
}