Reference Core Java Volume Ⅱ 10th Edition
“Java密码扩展”包含了一个Cipher,它是所有密码算法的超类。通过getInstance(algorithmName)可以获得一个密码对象。
cipher.init(mode, key);模式有以下四种:
Cipher.ENCRYPT;
Cipher.DECRYPT;
Cipher.WRAP_MODE和Cipher.UNWRAP_MODE会用一个秘钥对另一个秘钥进行加密
// 可以一直调用cipher.update(),进行加密
int blockSize = cipher.getBlockSize();
byte[] inBytes = 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返回加密后的数据
//如果最后一个输入数据块小于blockSize:
outBytes = cipher.doFinal(inBytes, 0, inLength);
//如果所有数据都已加密:
outBytes = cipher.doFinal();
//如果输入数组长度不够blockSize,update方法返回的数组为空,长度为0
doFinal调用时必要的,因为它会对最后的数据块进行填充,常用填充方案是RSA Security公司在公共秘钥密码标准#5(Public Key Cryptography Standard, PKCS)中描述的方案
该方案最后一个数据块不是全用0填充,而是等于填充字节数量的值最为填充值
我们需要确保秘钥生成时随机的。这需要遵循下面的步骤:
1). 为加密算法获取KeyGenerator
2). 用随机源来初始化秘钥发生器。如果密码长度是可变的,还需要指定期望的密码块长度
3). 调用generateKey方法
例如:
KeyGenerator keygen = KeyGenerator.getInstance("AES");
SecureRandom random = new SecureRandom();
keygen.init(random);
SecretKey key = keygen.generateKey();
或者可以从一组固定的原生数据(也许是口令或者随机键产生的)中生成一个密钥,这时可以使用SecretKeyFactory
byte[] keyData = ...; // 16 byte for AES
SecretKey key = new SecretKeySpec(keyData, "AES");
如果要生成密钥,必须使用“真正的随机”数。例如,在常见的Random中的常规的随即发生器。是根据当前的日期和时间来产生的,因此它不够随机。假设计算机时钟可以精确到1/10秒,那么每天最多存在864000个种子。如果攻击者知道密钥的日期(通常可以由消息日期或证书有效日期推算出来),那么就可以很容易的产生那一天的所有可能的种子。
SecureRandom类产生的随机数,远比由Random类产生的那些随机数字安全得多。也可以由我们提供种子。由setSeed(byre[] b)方法传递给它。
如果没有随机数发生器提供种子,那么它将通过启动线程,是他们睡眠,然后测量他们被唤醒的准确时间,一次来计算自己的20个字节的种子
!注意: 这个算法仍然被人为是安全的。而且,在过去,依靠对诸如硬盘访问之间的类的其他计算机组件进行计时的算法, 后来也被证明不也是完全随机的。
密码流能够透明地调用update和doFinal方法,所以非常方便,源码也很简单。
API javax.crypto.CipherInputStream 1.4
CipherInputStream(InputStream in, Cipher cipher)int read()int read(byte[] b, int off, int len)API javax.crypto.CipherOutputStream 1.4
CipherOutputSream(OutputStream out, Cipher cipher)void write(int ch)void write(byte b, int off, int len)void flush()CipherInputStream.read读取完数据后,如果不够一个数据块,会自动调用doFinal方法填充后返回
CipherOutputStream.close方法如果发现,还有没写完的数据,会调用doFinal方法返回数据然后输出
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.*;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Base64;
import java.util.Objects;
/**
* 加解密字符串、文件工具类
* @author YYang 13047
* @version 2022/10/25 12:10
*/
public class AESUtils {
public static final String AES = "AES";
//PKCS: Public Key Cryptographic Standard
public static final String AES_ECB = "AES/ECB/PKCS5Padding";
public static final String AES_CBC = "AES/CBC/PKCS5Padding";
public static final String AES_CFB = "AES/CFB/PKCS5Padding";
public static final int KEY_SIZE = 128;
public static final int BUFFER_SIZE = 512;
public static String encodeToString(byte[] unEncoded) {
return Base64.getEncoder().encodeToString(unEncoded);
}
public static byte[] decode(String encoded) {
return Base64.getDecoder().decode(encoded);
}
public static String generateAESKey() throws NoSuchAlgorithmException {
return generateAESKey(KEY_SIZE, null);
}
/**
* @param keySize keySize must be equal to 128, 192 or 256;
* @param seed 随机数种子
* @see #generateAESKey0()
*/
public static String generateAESKey(int keySize, String seed) throws NoSuchAlgorithmException {
KeyGenerator keyGen = KeyGenerator.getInstance(AES);
SecureRandom random = (seed == null || seed.length() == 0) ?
new SecureRandom() : new SecureRandom(seed.getBytes(StandardCharsets.UTF_8));
//如果不初始化,SunJCE默认使用new SecureRandom()
keyGen.init(keySize, random);
SecretKey secretKey = keyGen.generateKey();
return encodeToString(secretKey.getEncoded());
}
/**
* @return 密钥,不初始化,使用默认的
*/
public static String generateAESKey0() throws NoSuchAlgorithmException {
return encodeToString(KeyGenerator.getInstance(AES).generateKey().getEncoded());
}
/**
* @param algorithm 算法名
* @return 返回一个当前算法BlockSize大小的随机数组,然后Base64转码
* @see #generateAESIv()
*/
public static String generateAESIv(String algorithm) throws NoSuchAlgorithmException, NoSuchPaddingException {
Cipher cipher = Cipher.getInstance(algorithm);
int blockSize = cipher.getBlockSize();
byte[] ivByte = new byte[blockSize];
new SecureRandom().nextBytes(ivByte);
return encodeToString(ivByte);
}
public static String generateAESIv() {
//AES blockSize == 16
byte[] bytes = new byte[16];
new SecureRandom().nextBytes(bytes);
return encodeToString(bytes);
}
public static AlgorithmParameterSpec getIv(String ivStr) {
if (ivStr == null || ivStr.length() < 1) return null;
return new IvParameterSpec(decode(ivStr));
}
/**
* @return 指定秘钥和算法,返回Key对象
*/
public static Key getKey(String keyStr, String algorithm) {
return new SecretKeySpec(decode(keyStr), algorithm);
}
public static Cipher initCipher(String algorithm, int cipherMode, Key key, AlgorithmParameterSpec param)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException {
Cipher cipher = Cipher.getInstance(algorithm);
if (param == null) {
cipher.init(cipherMode, key);
} else {
cipher.init(cipherMode, key, param);
}
return cipher;
}
public static String encrypt(String algorithm, String keyStr, String ivStr, String unencryptedStr) throws Exception {
return encrypt(algorithm, keyStr, ivStr, unencryptedStr, StandardCharsets.UTF_8);
}
public static String encrypt(String algorithm, String keyStr, String ivStr, String unencryptedStr, Charset charset) throws Exception {
Cipher cipher = initCipher(algorithm, Cipher.ENCRYPT_MODE, getKey(keyStr, AES), getIv(ivStr));
byte[] encrypted = cipher.doFinal(unencryptedStr.getBytes(charset));
return encodeToString(encrypted);
}
public static String decrypt(String algorithm, String keyStr, String ivStr, String encryptedStr) throws Exception {
return decrypt(algorithm, keyStr, ivStr, encryptedStr, StandardCharsets.UTF_8);
}
public static String decrypt(String algorithm, String keyStr, String ivStr, String encryptedStr, Charset charset) throws Exception {
Cipher cipher = initCipher(algorithm, Cipher.DECRYPT_MODE, getKey(keyStr, AES), getIv(ivStr));
byte[] decrypted = cipher.doFinal(decode(encryptedStr));
return new String(decrypted, charset);
}
/**
* 解密文件
*/
public static void encryptFile(String algorithm, String keyStr, String ivStr, File source, File target) throws Exception {
checkPath(source, target);
Cipher cipher = initCipher(algorithm, Cipher.ENCRYPT_MODE, getKey(keyStr, AES), getIv(ivStr));
try (FileOutputStream fos = new FileOutputStream(target);
CipherInputStream cis = new CipherInputStream(new FileInputStream(source), cipher)) {
byte[] buffer = new byte[BUFFER_SIZE];
int len;
while ((len = cis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.flush();
}
}
/**
* 加密文件
*/
public static void decryptFile(String algorithm, String keyStr, String ivStr, File source, File target) throws Exception {
checkPath(source, target);
Cipher cipher = initCipher(algorithm, Cipher.DECRYPT_MODE, getKey(keyStr, AES), getIv(ivStr));
try (FileInputStream fis = new FileInputStream(source);
CipherOutputStream cos = new CipherOutputStream(new FileOutputStream(target), cipher)) {
byte[] buffer = new byte[BUFFER_SIZE];
int len;
while ((len = fis.read(buffer)) != -1) {
cos.write(buffer, 0, len);
}
cos.flush();
}
}
public static void checkPath(File source, File target) throws IOException {
Objects.requireNonNull(source);
Objects.requireNonNull(target);
if (source.isDirectory() || !source.exists()) {
throw new FileNotFoundException(source.toString());
}
if (Objects.equals(source.getCanonicalPath(), target.getCanonicalPath())) {
throw new IllegalArgumentException("sourceFile equals targetFile");
}
File parentDirectory = target.getParentFile();
if (parentDirectory != null && !parentDirectory.exists()) {
Files.createDirectories(parentDirectory.toPath());
}
}
public static void main(String[] args) throws Exception {
System.out.println(generateAESKey());
System.out.println(generateAESIv(AES_ECB));
String keyStr = "dN2VIV86Z2ShT47pEC1XwQ==";
String ivStr = "00hDTDhCxa9t11TrQSso3w==";
String encrypted = encrypt(AES_CBC, keyStr, ivStr, "中国深圳");
System.out.println("encrypted:" + encrypted);
System.out.println(decrypt(AES_CBC, keyStr, ivStr, encrypted));
File source = new File("README.md");
File encryptedFile = new File("out/README1.md");
File decryptedFile = new File("out/README2.md");
encryptFile(AES_CBC, keyStr, ivStr, source, encryptedFile);
decryptFile(AES_CBC, keyStr, ivStr, encryptedFile, decryptedFile);
}
}
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
在我的Rails(2.3,Ruby1.8.7)应用程序中,我需要将字符串截断到一定长度。该字符串是unicode,在控制台中运行测试时,例如'א'.length,我意识到返回了双倍长度。我想要一个与编码无关的长度,以便对unicode字符串或latin1编码字符串进行相同的截断。我已经了解了Ruby的大部分unicode资料,但仍然有些一头雾水。应该如何解决这个问题? 最佳答案 Rails有一个返回多字节字符的mb_chars方法。试试unicode_string.mb_chars.slice(0,50)
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje
我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco