Java关于加解密的一些问题
刚学加解密,看了下网上的例子,自己写了下,有一些疑问;
不定义工作模式和填充模式的时候,会怎么样,是默认ECB+NoPadding吗
DESede的密钥要24字节,但是输入的密钥只有16个,是不是应该把前八个复制到后面补满24字节?
还有看了网上的des和3des的代码差别,感觉就是密钥;很多不填IV的都没影响?
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class Triple{
private static final String Algorithm = "DESede";
public static SecretKey getSecreKey(String key){
byte[] keybyte = key.getBytes();
SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
return deskey;
}
public static byte[] encryptMode(String str, String key){
Cipher cipher;
try {
cipher = Cipher.getInstance(Algorithm);
cipher.init(Cipher.ENCRYPT_MODE, getSecreKey(key));
return cipher.doFinal(str.getBytes());
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
public static void main(String[] args) {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
final String key = "abcdefgh12345678cccccccc";
String str = "bcdma";
System.out.println("加密前字符串:" +str);
byte[] encoded = encryptMode(str, key);
System.out.println("加密后字符串:" +parseByte2HexStr(encryptMode(str, key)));
}
}