加密

Wu Jun 2020-01-03 18:43:49
Categories: > > Tags:

1 对称密码

“Java密码扩展”包含所有加密算法的超类: Cipher 类。

Cipher cipher = Cipher.getInstance(algorithName);
Cipher cipher = Cipher.getInstance(algorithName, providerName);

初始化密码对象

int mode = ...;//设置模式
Key key = ...;//密钥
cipher.init(mode, key);

update加密

int blockSize = cipher.getBlockSize();
byte[] intBytes = new byte[blockSize];
...//read inBytes
int outputSize = cipher.getOutputSize(blockSize);
byte[] outBytes = new byte[outputSize];
int outLength = cipher.update(inBytes, 0, outputSize, outBytes);
...//write outBytes

最后 doFinal

//未完
outBytes = cipher.doFinal(inByte, 0, inLength);
//已完
outBytes = cipher.doFinal();

2 密钥生成

  1. 为加密算法获取 KeyGenerator
  2. 用随机源来初始化密钥发生器。指定密码块长度
  3. 调用 generateKey 方法
KeyGenerator keygen = KeyGenerator.getInstance("AES");
SecureRandom random = new SecureRandom();
keygen.init(random);
Key key = keygen.generateKey();

3 密码流

JCE 库提供了便捷的流类,能对数据流自动加密解密。 使用 CiperInputStream 和 CiperOutputStream 可以屏蔽 update 和 doFinal 等细节;

Cipher cipher = ...;
cipher.init(Supher.ENCRYPT_MODE, key);
CiperOutputStream out = new CiperOutputStream(new FileOutputStream(outputFileName), cipher);
byte[] bytes = new byte[BLOCKSIZE];
int inLength = getData(bytes);
while(inLength != -1){
    out.write(bytes, 0, inLength);
    inLength = getData(bytes);
}
out.flush();

4 公共密钥密码

对称密码,加密解密都是用相同密钥,缺点在于密码的分发。

公共密钥算法 RSA,有一对公共/私有密钥

  1. A生成一个随机对称加密密钥,用该密钥对明文进行加密
  2. A用B的公共密钥给对称密钥加密
  3. A将加密后的对称密钥和加密后的明文发送给B
  4. B用他的私钥给对称密钥解密
  5. B用解密后的对称密钥给信息解密