
正文
dsa代码java dsl代码
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
java程序里运行错误不晓得怎么改
你检查错误啊!全是拼写错误!
1、finleIn.read(encodedprivateKey); 你上面定义的是FileInputStream fileIn=new FileInputStream(args[0]); 是fileIn 不是finleIn
改为:fileIn.read(encodedprivateKey);
2、PKCS8EncodeKeySpec 改为 PKCS8EncodedKeySpec
3、PrivateKey privKey=keyFactory.generatePrivate(privKeySpec); 参数传的不正确,是privKeySpec 不是privateKeySpec,看看你上面怎么定义的!
相关问答
Q1: java问题
-------------参考下------------------
JAVA加密算法的实现用例
对象
参数 algorithm 如:"DSA"
public final void initSign(PrivateKey privateKey)
throws InvalidKeyException
用指定的私钥初始化
参数:privateKey 所进行签名时用的私钥
public final void update(byte data)
throws SignatureException
public final void update(byte[] data)
throws SignatureException
public final void update(byte[] data, int off, int len)
throws SignatureException
添加要签名的信息
public final byte[] sign()
throws SignatureException
返回签名的数组,前提是initSign和update
public final void initVerify(PublicKey publicKey)
throws InvalidKeyException
用指定的公钥初始化
参数:publicKey 验证时用的公钥
public final boolean verify(byte[] signature)
throws SignatureException
验证签名是否有效,前提是已经initVerify初始化
参数: signature 签名数组
*/
import java.security.*;
import java.security.spec.*;
public class testdsa {
public static void main(String[] args) throws java.security.NoSuchAlgorithmException,java.lang.Exception {
testdsa my=new testdsa();
my.run();
}
public void run()
{
//数字签名生成密钥
//第一步生成密钥对,如果已经生成过,本过程就可以跳过,对用户来讲myprikey.dat要保存在本地
//而mypubkey.dat给发布给其它用户
if ((new java.io.File("myprikey.dat")).exists()==false) {
if (generatekey()==false) {
System.out.println("生成密钥对败");
return;
};
}
//第二步,此用户
//从文件中读入私钥,对一个字符串进行签名后保存在一个文件(myinfo.dat)中
//并且再把myinfo.dat发送出去
//为了方便数字签名也放进了myifno.dat文件中,当然也可分别发送
try {
java.io.ObjectInputStream in=new java.io.ObjectInputStream(new java.io.FileInputStream("myprikey.dat"));
PrivateKey myprikey=(PrivateKey)in.readObject();
in.close();
// java.security.spec.X509EncodedKeySpec pubX509=new java.security.spec.X509EncodedKeySpec(bX509);
//java.security.spec.X509EncodedKeySpec pubkeyEncode=java.security.spec.X509EncodedKeySpec
String myinfo="这是我的信息"; //要签名的信息
//用私钥对信息生成数字签名
java.security.Signature signet=java.security.Signature.getInstance("DSA");
signet.initSign(myprikey);
signet.update(myinfo.getBytes());
byte[] signed=signet.sign(); //对信息的数字签名
System.out.println ("signed(签名内容)="+byte2hex(signed));
//把信息和数字签名保存在一个文件中
java.io.ObjectOutputStream out=new java.io.ObjectOutputStream(new java.io.FileOutputStream("myinfo.dat"));
out.writeObject(myinfo);
out.writeObject(signed);
out.close();
System.out.println("签名并生成文件成功");
}
catch (java.lang.Exception e) {
e.printStackTrace();
System.out.println("签名并生成文件失败");
};
//第三步
//其他人通过公共方式得到此户的公钥和文件
//其他人用此户的公钥,对文件进行检查,如果成功说明是此用户发布的信息.
//
try {
java.io.ObjectInputStream in=new java.io.ObjectInputStream(new java.io.FileInputStream("mypubkey.dat"));
PublicKey pubkey=(PublicKey)in.readObject();
in.close();
System.out.println(pubkey.getFormat());
in=new java.io.ObjectInputStream(new java.io.FileInputStream("myinfo.dat"));
String info=(String)in.readObject();
byte[] signed=(byte[])in.readObject();
in.close();
java.security.Signature signetcheck=java.security.Signature.getInstance("DSA");
signetcheck.initVerify(pubkey);
signetcheck.update (info.getBytes());
if (signetcheck.verify(signed)) {
System.out.println("info="+info);
System.out.println("签名正常");
}
else System.out.println("非签名正常");
}
catch ( java.lang.Exception e) {e.printStackTrace();};
}
//生成一对文件myprikey.dat和mypubkey.dat---私钥和公钥,
//公钥要用户发送(文件,网络等方法)给其它用户,私钥保存在本地
public boolean generatekey()
{
try {
java.security.KeyPairGenerator keygen=java.security.KeyPairGenerator.getInstance("DSA");
// SecureRandom secrand=new SecureRandom();
// secrand.setSeed("tttt".getBytes()); //初始化随机产生器
// keygen.initialize(576,secrand); //初始化密钥生成器
keygen.initialize(512);
KeyPair keys=keygen.genKeyPair();
// KeyPair keys=keygen.generateKeyPair(); //生成密钥组
PublicKey pubkey=keys.getPublic();
PrivateKey prikey=keys.getPrivate();
java.io.ObjectOutputStream out=new java.io.ObjectOutputStream(new java.io.FileOutputStream("myprikey.dat"));
out.writeObject(prikey);
out.close();
System.out.println("写入对象 prikeys ok");
out=new java.io.ObjectOutputStream (new java.io.FileOutputStream("mypubkey.dat"));
out.writeObject(pubkey);
out.close();
System.out.println("写入对象 pubkeys ok");
System.out.println("生成密钥对成功");
return true;
}
catch (java.lang.Exception e) {
e.printStackTrace();
System.out.println("生成密钥对失败");
return false;
};
}
public String byte2hex(byte[] b)
{
String hs="";
String stmp="";
for (int n=0;nb.length;n++)
{
stmp=(java.lang.Integer.toHexString(b[n] 0XFF));
if (stmp.length()==1) hs=hs+"0"+stmp;
else hs=hs+stmp;
if (nb.length-1) hs=hs+":";
}
return hs.toUpperCase();
}
}
2.4. DESede/DES对称算法
首先生成密钥,并保存(这里并没的保存的代码,可参考DSA中的方法)
KeyGenerator keygen = KeyGenerator.getInstance(Algorithm);
SecretKey deskey = keygen.generateKey();
用密钥加密明文(myinfo),生成密文(cipherByte)
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE,deskey);
byte[] cipherByte=c1.doFinal(myinfo.getBytes());
传送密文和密钥,本文没有相应代码可参考DSA
.............
用密钥解密密文
c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.DECRYPT_MODE,deskey);
byte[] clearByte= c1.doFinal(cipherByte);
相对来说对称密钥的使用是很简单的,对于JCE来讲支技DES,DESede,Blowfish三种加密术
对于密钥的保存各传送可使用对象流或者用二进制编码,相关参考代码如下
SecretKey deskey = keygen.generateKey();
byte[] desEncode=deskey.getEncoded();
javax.crypto.spec.SecretKeySpec destmp=new javax.crypto.spec.SecretKeySpec(desEncode,Algorithm);
SecretKey mydeskey=destmp;
相关API
KeyGenerator 在DSA中已经说明,在添加JCE后在instance进可以如下参数
DES,DESede,Blowfish,HmacMD5,HmacSHA1
javax.crypto.Cipher 加/解密器
public static final Cipher getInstance(java.lang.String transformation)
throws java.security.NoSuchAlgorithmException ,
NoSuchPaddingException
返回一个指定方法的Cipher对象
参数:transformation 方法名(可用 DES,DESede,Blowfish)
public final void init(int opmode, java.security.Key key)
throws java.security.InvalidKeyException
用指定的密钥和模式初始化Cipher对象
参数:opmode 方式(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)
key 密钥
public final byte[] doFinal(byte[] input)
throws java.lang.IllegalStateException,
IllegalBlockSizeException,
BadPaddingException
对input内的串,进行编码处理,返回处理后二进制串,是返回解密文还是加解文由init时的opmode决定
注意:本方法的执行前如果有update,是对updat和本次input全部处理,否则是本inout的内容
/*
安全程序 DESede/DES测试
*/
import java.security.*;
import javax.crypto.*;
public class testdes {
public static void main(String[] args){
testdes my=new testdes();
my.run();
}
public void run() {
//添加新安全算法,如果用JCE就要把它添加进去
Security.addProvider(new com.sun.crypto.provider.SunJCE());
String Algorithm="DES"; //定义 加密算法,可用 DES,DESede,Blowfish
String myinfo="要加密的信息";
try {
//生成密钥
KeyGenerator keygen = KeyGenerator.getInstance(Algorithm);
SecretKey deskey = keygen.generateKey();
//加密
System.out.println("加密前的二进串:"+byte2hex( myinfo.getBytes()));
System.out.println("加密前的信息:"+myinfo);
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE,deskey);
byte[] cipherByte=c1.doFinal(myinfo.getBytes());
System.out.println("加密后的二进串:"+byte2hex(cipherByte));
//解密
c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.DECRYPT_MODE,deskey);
byte[] clearByte=c1.doFinal(cipherByte);
System.out.println ("解密后的二进串:"+byte2hex(clearByte));
System.out.println("解密后的信息:"+(new String(clearByte)));
}
catch (java.security.NoSuchAlgorithmException e1) {e1.printStackTrace();}
catch (javax.crypto.NoSuchPaddingException e2) {e2.printStackTrace();}
catch (java.lang.Exception e3) {e3.printStackTrace();}
}
public String byte2hex(byte[] b) //二行制转字符串
{
String hs="";
String stmp="";
for (int n=0;nb.length;n++)
{
stmp=(java.lang.Integer.toHexString(b[n] 0XFF));
if (stmp.length()==1) hs=hs+"0"+stmp;
else hs=hs+stmp;
if (nb.length-1 ) hs=hs+":";
}
return hs.toUpperCase();
}
}
2.5. Diffie-Hellman密钥一致协议
公 开密钥密码体制的奠基人Diffie和Hellman所提出的 "指数密钥一致协议" (Exponential Key Agreement Protocol),该协议不要求别的安全性先决条件,允许两名用户在公开媒体上交换信息以生成 "一致"的,可以共享的密钥。在JCE的中实现用户alice生成DH类型的密钥对,如果长度用1024生成的时间请,推荐第一次生成后保存 DHParameterSpec,以便下次使用直接初始化.使其速度加快
System.out.println("ALICE: 产生 DH 对 ...");
KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
aliceKpairGen.initialize(512);
KeyPair aliceKpair = aliceKpairGen.generateKeyPair();
alice生成公钥发送组bob
byte[] alicePubKeyEnc = aliceKpair.getPublic().getEncoded();
bob从alice发送来的公钥中读出DH密钥对的初始参数生成bob的DH密钥对
注意这一步一定要做,要保证每个用户用相同的初始参数生成的
DHParameterSpec dhParamSpec = ((DHPublicKey)alicePubKey).getParams();
KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
bobKpairGen.initialize(dhParamSpec);
KeyPair bobKpair = bobKpairGen.generateKeyPair();
bob根据alice的公钥生成本地的DES密钥
KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH");
bobKeyAgree.init(bobKpair.getPrivate());
bobKeyAgree.doPhase (alicePubKey, true);
SecretKey bobDesKey = bobKeyAgree.generateSecret("DES");
bob已经生成了他的DES密钥,他现把他的公钥发给alice,
byte[] bobPubKeyEnc = bobKpair.getPublic().getEncoded();
alice根据bob的公钥生成本地的DES密钥
,,,,,,解码
KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH");
aliceKeyAgree.init(aliceKpair.getPrivate());
aliceKeyAgree.doPhase (bobPubKey, true);
SecretKey aliceDesKey = aliceKeyAgree.generateSecret("DES");
bob和alice能过这个过程就生成了相同的DES密钥,在这种基础就可进行安全能信
常用API
java.security.KeyPairGenerator 密钥生成器类
public static KeyPairGenerator getInstance(String algorithm)
throws NoSuchAlgorithmException
以指定的算法返回一个KeyPairGenerator 对象
参数: algorithm 算法名.如:原来是DSA,现在添加了 DiffieHellman(DH)
public void initialize(int keysize)
以指定的长度初始化KeyPairGenerator对象,如果没有初始化系统以1024长度默认设置
参数:keysize 算法位长.其范围必须在 512 到 1024 之间,且必须为 64 的倍数
注意:如果用1024生长的时间很长,最好生成一次后就保存,下次就不用生成了
public void initialize(AlgorithmParameterSpec params)
throws InvalidAlgorithmParameterException
以指定参数初始化
javax.crypto.interfaces.DHPublicKey
public DHParameterSpec getParams()
返回
java.security.KeyFactory
public static KeyFactory getInstance(String algorithm)
throws NoSuchAlgorithmException
以指定的算法返回一个KeyFactory
参数: algorithm 算法名:DSH,DH
public final PublicKey generatePublic(KeySpec keySpec)
throws InvalidKeySpecException
根据指定的key说明,返回一个PublicKey对象
java.security.spec.X509EncodedKeySpec
public X509EncodedKeySpec(byte[] encodedKey)
根据指定的二进制编码的字串生成一个key的说明
参数:encodedKey 二进制编码的字串(一般能过PublicKey.getEncoded()生成)
javax.crypto.KeyAgreement 密码一至类
public static final KeyAgreement getInstance(java.lang.String algorithm)
throws java.security.NoSuchAlgorithmException
返回一个指定算法的KeyAgreement对象
参数:algorithm 算法名,现在只能是DiffieHellman(DH)
public final void init(java.security.Key key)
throws java.security.InvalidKeyException
用指定的私钥初始化
参数:key 一个私钥
public final java.security.Key doPhase(java.security.Key key,
boolean lastPhase)
throws java.security.InvalidKeyException,
java.lang.IllegalStateException
用指定的公钥进行定位,lastPhase确定这是否是最后一个公钥,对于两个用户的
情况下就可以多次定次,最后确定
参数:key 公钥
lastPhase 是否最后公钥
public final SecretKey generateSecret(java.lang.String algorithm)
throws java.lang.IllegalStateException,
java.security.NoSuchAlgorithmException,
java.security.InvalidKeyException
根据指定的算法生成密钥
参数:algorithm 加密算法(可用 DES,DESede,Blowfish)
*/
import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.spec.*;
import java.security.interfaces.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
import com.sun.crypto.provider.SunJCE;
public class testDHKey {
public static void main(String argv[]) {
try {
testDHKey my= new testDHKey();
my.run();
} catch (Exception e) {
System.err.println(e);
}
}
private void run() throws Exception {
Security.addProvider (new com.sun.crypto.provider.SunJCE());
System.out.println("ALICE: 产生 DH 对 ...");
KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
aliceKpairGen.initialize (512);
KeyPair aliceKpair = aliceKpairGen.generateKeyPair(); //生成时间长
// 张三(Alice)生成公共密钥 alicePubKeyEnc 并发送给李四(Bob) ,
//比如用文件方式,socket.....
byte[] alicePubKeyEnc = aliceKpair.getPublic ().getEncoded();
//bob接收到alice的编码后的公钥,将其解码
KeyFactory bobKeyFac = KeyFactory.getInstance("DH");
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec (alicePubKeyEnc);
PublicKey alicePubKey = bobKeyFac.generatePublic(x509KeySpec);
System.out.println("alice公钥bob解码成功");
// bob必须用相同的参数初始化的他的DH KEY对,所以要从Alice发给他的公开密钥,
//中读出参数,再用这个参数初始化他的 DH key对
//从alicePubKye中取alice初始化时用的参数
DHParameterSpec dhParamSpec = ((DHPublicKey)alicePubKey).getParams();
KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH");
bobKpairGen.initialize(dhParamSpec);
KeyPair bobKpair = bobKpairGen.generateKeyPair();
System.out.println("BOB: 生成 DH key 对成功");
KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH");
bobKeyAgree.init(bobKpair.getPrivate());
System.out.println("BOB: 初始化本地key成功");
//李四(bob) 生成本地的密钥 bobDesKey
bobKeyAgree.doPhase(alicePubKey, true);
SecretKey bobDesKey = bobKeyAgree.generateSecret("DES");
System.out.println("BOB: 用alice的公钥定位本地key,生成本地DES密钥成功");
// Bob生成公共密钥 bobPubKeyEnc 并发送给Alice,
//比如用文件方式,socket.....,使其生成本地密钥
byte[] bobPubKeyEnc = bobKpair.getPublic().getEncoded();
System.out.println("BOB向ALICE发送公钥");
// alice接收到 bobPubKeyEnc后生成bobPubKey
// 再进行定位,使aliceKeyAgree定位在bobPubKey
KeyFactory aliceKeyFac = KeyFactory.getInstance("DH");
x509KeySpec = new X509EncodedKeySpec(bobPubKeyEnc);
PublicKey bobPubKey = aliceKeyFac.generatePublic(x509KeySpec);
System.out.println("ALICE接收BOB公钥并解码成功");
;
KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH");
aliceKeyAgree.init(aliceKpair.getPrivate());
System.out.println("ALICE: 初始化本地key成功");
aliceKeyAgree.doPhase(bobPubKey, true);
// 张三(alice) 生成本地的密钥 aliceDesKey
SecretKey aliceDesKey = aliceKeyAgree.generateSecret("DES");
System.out.println("ALICE: 用bob的公钥定位本地key,并生成本地DES密钥");
if (aliceDesKey.equals(bobDesKey)) System.out.println ("张三和李四的密钥相同");
//现在张三和李四的本地的deskey是相同的所以,完全可以进行发送加密,接收后解密,达到
//安全通道的的目的
/*
* bob用bobDesKey密钥加密信息
*/
Cipher bobCipher = Cipher.getInstance("DES");
bobCipher.init(Cipher.ENCRYPT_MODE, bobDesKey);
String bobinfo= "这是李四的机密信息";
System.out.println("李四加密前原文:"+bobinfo);
byte[] cleartext =bobinfo.getBytes();
byte[] ciphertext = bobCipher.doFinal(cleartext);
/*
* alice用aliceDesKey密钥解密
*/
Cipher aliceCipher = Cipher.getInstance("DES");
aliceCipher.init(Cipher.DECRYPT_MODE, aliceDesKey);
byte[] recovered = aliceCipher.doFinal(ciphertext);
System.out.println("alice解密bob的信息:"+(new String(recovered)));
if (!java.util.Arrays.equals(cleartext, recovered))
throw new Exception("解密后与原文信息不同");
System.out.println("解密后相同");
}
}
Q2: java中DSA数字签名问题,生成秘钥的时候用了私钥密码的怎样进行签名
先进行在线RSA私钥密码清除,把密码去掉,再用生成的私钥就可以签名了。
Q3: 在Java中怎么使用断言
如果要开启断言检查,则需要用开关-enableassertions或-ea来开启。
assert关键字语法很简单,有两种用法:
1、assert boolean表达式
如果boolean表达式为true,则程序继续执行。
如果为false,则程序抛出AssertionError,并终止执行。
2、assert boolean表达式 : 错误信息表达式
如果boolean表达式为true,则程序继续执行。
如果为false,则程序抛出java.lang.AssertionError,并输入错误信息表达式。
三、应用实例
下面给出一个例子,通过例子说明其用法:
public class AssertFoo {
public static void main(String args[]) {
//断言1结果为true,则继续往下执行
assert true;
System.out.println("断言1没有问题,Go!");
System.out.println("\n-----------------\n");
//断言2结果为false,程序终止
assert false : "断言失败,此表达式的信息将会在抛出异常的时候输出!";
System.out.println("断言2没有问题,Go!");
}
}
保存代码到C:\AssertFoo.java,然后按照下面的方式执行,查看控制台输出结果:
1、编译程序:
C:\javac AssertFoo.java
2、默认执行程序,没有开启-ea开关:
C:\java AssertFoo
断言1没有问题,Go!
-----------------
断言2没有问题,Go!
3、开启-ea开关,执行程序:
C:\java -ea AssertFoo
断言1没有问题,Go!
-----------------
Exception in thread "main" java.lang.AssertionError: 断言失败,此表达式的信息将
会在抛出异常的时候输出!
at AssertFoo.main(AssertFoo.java:10)
四、陷阱
assert关键字用法简单,但是使用assert往往会让你陷入越来越深的陷阱中。应避免使用。笔者经过研究,总结了以下原因:
1、assert关键字需要在运行时候显式开启才能生效,否则你的断言就没有任何意义。而现在主流的Java IDE工具默认都没有开启-ea断言检查功能。这就意味着你如果使用IDE工具编码,调试运行时候会有一定的麻烦。并且,对于Java Web应用,程序代码都是部署在容器里面,你没法直接去控制程序的运行,如果一定要开启-ea的开关,则需要更改Web容器的运行配置参数。这对程序的移植和部署都带来很大的不便。
2、用assert代替if是陷阱之二。assert的判断和if语句差不多,但两者的作用有着本质的区别:assert关键字本意上是为测试调试程序时使用的,但如果不小心用assert来控制了程序的业务流程,那在测试调试结束后去掉assert关键字就意味着修改了程序的正常的逻辑。
3、assert断言失败将面临程序的退出。这在一个生产环境下的应用是绝不能容忍的。一般都是通过异常处理来解决程序中潜在的错误。但是使用断言就很危险,一旦失败系统就挂了。
五、对assert的思考
assert既然是为了调试测试程序用,不在正式生产环境下用,那应该考虑更好的测试JUint来代替其做用,JUint相对assert关键的所提供的功能是有过之而无不及。当然完全可以通过IDE debug来进行调试测试。在此看来,assert的前途一片昏暗。
因此,应当避免在Java中使用assert关键字,除非哪一天Java默认支持开启-ea的开关,这时候可以考虑。对比一下,assert能给你带来多少好处,多少麻烦,这是我们选择是否使用的的原则。
以上仅仅代表我个人观点,欢迎大家留言讨论。
-----------------------------------------------------------------------------------
下面是一些Assert的例子:
assert 0 value;
assert 0 value:"value="+value;
assert ref != null:"ref doesn''t equal null";
assert isBalanced();
-----------------------------------------------------------------------------------
AssertinError类是Error的直接子类,因此代表程序出现了严重的错误,这种异常通常是不需要程序员使用catch语句捕捉的。
使用assert的准则:assert语句的作用是保证程序内部的一致性,而不是用户与程序之间的一致性,所以不应用在保证命令行参数的正确性。可以用来保证传递给private方法参数的正确性。因为私有方法只是在类的内部被调用,因而是程序员可以控制的,我们可以预期它的状态是正确和一致的。公有方法则不适用。此外,assert语句可用于检查任何方法结束时状态的正确性,及在方法的开始检查相关的初始状态 等等。
assert语句并不构成程序正常运行逻辑的一部分,时刻记住在运行时它们可能不会被执行。
-----------------------------------------------------------------------------------
两类参数:
参数 -esa和 -dsa:
它们含义为开启(关闭)系统类的assertion功能。由于新版本的Java的系统类中,也使了 assertion语句,因此如果用户需要观察它们的运行情况,就需要打开系统类的assertion功能 ,我们可使用-esa参数打开,使用 -dsa参数关闭。 -esa和-dsa的全名为-enablesystemassertions和-disenablesystemassertions,全名和缩写名有同样的功能。
参数 -ea和 -ea:
它们含义为开启(关闭)用户类的assertion功能:通过这个参数,用户可以打开某些类或包的assertion功能,同样用户也可以关闭某些类和包的assertion功能。打开assertion功能参数为-ea;如果不带任何参数,表示打开所有用户类;如果带有包名称或者类名称,表示打开这些类或包;如果包名称后面跟有三个点,代表这个包及其子包;如果只有三个点,代表无名包。关闭 assertion功能参数为-da,使用方法与-ea类似。
-ea和-da的全名为-enableassertions和-disenableassertions,全名和缩写名有同样的功能。
下面表格表示了参数及其含义,并有例子说明如何使用。
参数 例子 说明
-ea java -ea 打开所有用户类的assertion
-da java -da 关闭所有用户类的assertion
-ea: java -ea:MyClass1 打开MyClass1的assertion
-da: java -da: MyClass1 关闭MyClass1的assertion
-ea: java -ea:pkg1 打开pkg1包的assertion
-da: java -da:pkg1 关闭pkg1包的assertion
-ea:... java -ea:... 打开缺省包(无名包)的assertion
-da:... java -da:... 关闭缺省包(无名包)的assertion
-ea:... java -ea:pkg1... 打开pkg1包和其子包的assertion
-da:... java -da:pkg1... 关闭pkg1包和其子包的assertion
-esa java -esa 打开系统类的assertion
-dsa java -dsa 关闭系统类的assertion
-----------------------------------------------------------------------------------
不要再public的方法里面检查参数是不是为null之类的操作,例如:
public int get(String s){
assert s != null;
}
如果需要检查也最好通过 if s = null 抛出 NullPointerException来检查。
不要用assert来检查方法操作的返回值来判断方法操作的结果,例如:
assert list.removeAll();这样看起来好像没有问题 但是想想如果assert 被disable呢,那样他就不会被执行了,所以removeAll()操作就没有被执行,可以这样代替
boolean boo = list.removeAl();
assert boo;
-----------------------------------------------------------------------------------
另外,Java为了让程序也能够动态开启和关闭某些类和包的assertion功能,Java修该了Class和ClassLoader的实现,增加了几个用于操作assert的API。下面简单说明一下几个API的作用。
ClassLoader类中的几个相关的API:
setDefaultAssertionStatus:用于开启/关闭assertion功能
setPackageAssertionStatus:用于开启/关闭某些包的assertion功能
setClassAssertionStatus: 用于开启/关闭某些类的assertion功能
clearAssertionStatus:用于关闭assertion功能
Q4: 如何使用JAVA实现对字符串的DES加密和解密
java加密字符串可以使用des加密算法,实例如下:
package test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
/**
* 加密解密
*
* @author shy.qiu
* @since
*/
public class CryptTest {
/**
* 进行MD5加密
*
* @param info
* 要加密的信息
* @return String 加密后的字符串
*/
public String encryptToMD5(String info) {
byte[] digesta = null;
try {
// 得到一个md5的消息摘要
MessageDigest alga = MessageDigest.getInstance("MD5");
// 添加要进行计算摘要的信息
alga.update(info.getBytes());
// 得到该摘要
digesta = alga.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 将摘要转为字符串
String rs = byte2hex(digesta);
return rs;
}
/**
* 进行SHA加密
*
* @param info
* 要加密的信息
* @return String 加密后的字符串
*/
public String encryptToSHA(String info) {
byte[] digesta = null;
try {
// 得到一个SHA-1的消息摘要
MessageDigest alga = MessageDigest.getInstance("SHA-1");
// 添加要进行计算摘要的信息
alga.update(info.getBytes());
// 得到该摘要
digesta = alga.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 将摘要转为字符串
String rs = byte2hex(digesta);
return rs;
}
// //////////////////////////////////////////////////////////////////////////
/**
* 创建密匙
*
* @param algorithm
* 加密算法,可用 DES,DESede,Blowfish
* @return SecretKey 秘密(对称)密钥
*/
public SecretKey createSecretKey(String algorithm) {
// 声明KeyGenerator对象
KeyGenerator keygen;
// 声明 密钥对象
SecretKey deskey = null;
try {
// 返回生成指定算法的秘密密钥的 KeyGenerator 对象
keygen = KeyGenerator.getInstance(algorithm);
// 生成一个密钥
deskey = keygen.generateKey();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 返回密匙
return deskey;
}
/**
* 根据密匙进行DES加密
*
* @param key
* 密匙
* @param info
* 要加密的信息
* @return String 加密后的信息
*/
public String encryptToDES(SecretKey key, String info) {
// 定义 加密算法,可用 DES,DESede,Blowfish
String Algorithm = "DES";
// 加密随机数生成器 (RNG),(可以不写)
SecureRandom sr = new SecureRandom();
// 定义要生成的密文
byte[] cipherByte = null;
try {
// 得到加密/解密器
Cipher c1 = Cipher.getInstance(Algorithm);
// 用指定的密钥和模式初始化Cipher对象
// 参数:(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)
c1.init(Cipher.ENCRYPT_MODE, key, sr);
// 对要加密的内容进行编码处理,
cipherByte = c1.doFinal(info.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
// 返回密文的十六进制形式
return byte2hex(cipherByte);
}
/**
* 根据密匙进行DES解密
*
* @param key
* 密匙
* @param sInfo
* 要解密的密文
* @return String 返回解密后信息
*/
public String decryptByDES(SecretKey key, String sInfo) {
// 定义 加密算法,
String Algorithm = "DES";
// 加密随机数生成器 (RNG)
SecureRandom sr = new SecureRandom();
byte[] cipherByte = null;
try {
// 得到加密/解密器
Cipher c1 = Cipher.getInstance(Algorithm);
// 用指定的密钥和模式初始化Cipher对象
c1.init(Cipher.DECRYPT_MODE, key, sr);
// 对要解密的内容进行编码处理
cipherByte = c1.doFinal(hex2byte(sInfo));
} catch (Exception e) {
e.printStackTrace();
}
// return byte2hex(cipherByte);
return new String(cipherByte);
}
// /////////////////////////////////////////////////////////////////////////////
/**
* 创建密匙组,并将公匙,私匙放入到指定文件中
*
* 默认放入mykeys.bat文件中
*/
public void createPairKey() {
try {
// 根据特定的算法一个密钥对生成器
KeyPairGenerator keygen = KeyPairGenerator.getInstance("DSA");
// 加密随机数生成器 (RNG)
SecureRandom random = new SecureRandom();
// 重新设置此随机对象的种子
random.setSeed(1000);
// 使用给定的随机源(和默认的参数集合)初始化确定密钥大小的密钥对生成器
keygen.initialize(512, random);// keygen.initialize(512);
// 生成密钥组
KeyPair keys = keygen.generateKeyPair();
// 得到公匙
PublicKey pubkey = keys.getPublic();
// 得到私匙
PrivateKey prikey = keys.getPrivate();
// 将公匙私匙写入到文件当中
doObjToFile("mykeys.bat", new Object[] { prikey, pubkey });
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
/**
* 利用私匙对信息进行签名 把签名后的信息放入到指定的文件中
*
* @param info
* 要签名的信息
* @param signfile
* 存入的文件
*/
public void signToInfo(String info, String signfile) {
// 从文件当中读取私匙
PrivateKey myprikey = (PrivateKey) getObjFromFile("mykeys.bat", 1);
// 从文件中读取公匙
PublicKey mypubkey = (PublicKey) getObjFromFile("mykeys.bat", 2);
try {
// Signature 对象可用来生成和验证数字签名
Signature signet = Signature.getInstance("DSA");
// 初始化签署签名的私钥
signet.initSign(myprikey);
// 更新要由字节签名或验证的数据
signet.update(info.getBytes());
// 签署或验证所有更新字节的签名,返回签名
byte[] signed = signet.sign();
// 将数字签名,公匙,信息放入文件中
doObjToFile(signfile, new Object[] { signed, mypubkey, info });
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 读取数字签名文件 根据公匙,签名,信息验证信息的合法性
*
* @return true 验证成功 false 验证失败
*/
public boolean validateSign(String signfile) {
// 读取公匙
PublicKey mypubkey = (PublicKey) getObjFromFile(signfile, 2);
// 读取签名
byte[] signed = (byte[]) getObjFromFile(signfile, 1);
// 读取信息
String info = (String) getObjFromFile(signfile, 3);
try {
// 初始一个Signature对象,并用公钥和签名进行验证
Signature signetcheck = Signature.getInstance("DSA");
// 初始化验证签名的公钥
signetcheck.initVerify(mypubkey);
// 使用指定的 byte 数组更新要签名或验证的数据
signetcheck.update(info.getBytes());
System.out.println(info);
// 验证传入的签名
return signetcheck.verify(signed);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将二进制转化为16进制字符串
*
* @param b
* 二进制字节数组
* @return String
*/
public String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
/**
* 十六进制字符串转化为2进制
*
* @param hex
* @return
*/
public byte[] hex2byte(String hex) {
byte[] ret = new byte[8];
byte[] tmp = hex.getBytes();
for (int i = 0; i 8; i++) {
ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
}
return ret;
}
/**
* 将两个ASCII字符合成一个字节; 如:"EF"-- 0xEF
*
* @param src0
* byte
* @param src1
* byte
* @return byte
*/
public static byte uniteBytes(byte src0, byte src1) {
byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
.byteValue();
_b0 = (byte) (_b0 4);
byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
.byteValue();
byte ret = (byte) (_b0 ^ _b1);
return ret;
}
/**
* 将指定的对象写入指定的文件
*
* @param file
* 指定写入的文件
* @param objs
* 要写入的对象
*/
public void doObjToFile(String file, Object[] objs) {
ObjectOutputStream oos = null;
try {
FileOutputStream fos = new FileOutputStream(file);
oos = new ObjectOutputStream(fos);
for (int i = 0; i objs.length; i++) {
oos.writeObject(objs[i]);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 返回在文件中指定位置的对象
*
* @param file
* 指定的文件
* @param i
* 从1开始
* @return
*/
public Object getObjFromFile(String file, int i) {
ObjectInputStream ois = null;
Object obj = null;
try {
FileInputStream fis = new FileInputStream(file);
ois = new ObjectInputStream(fis);
for (int j = 0; j i; j++) {
obj = ois.readObject();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return obj;
}
/**
* 测试
*
* @param args
*/
public static void main(String[] args) {
CryptTest jiami = new CryptTest();
// 执行MD5加密"Hello world!"
System.out.println("Hello经过MD5:" + jiami.encryptToMD5("Hello"));
// 生成一个DES算法的密匙
SecretKey key = jiami.createSecretKey("DES");
// 用密匙加密信息"Hello world!"
String str1 = jiami.encryptToDES(key, "Hello");
System.out.println("使用des加密信息Hello为:" + str1);
// 使用这个密匙解密
String str2 = jiami.decryptByDES(key, str1);
System.out.println("解密后为:" + str2);
// 创建公匙和私匙
jiami.createPairKey();
// 对Hello world!使用私匙进行签名
jiami.signToInfo("Hello", "mysign.bat");
// 利用公匙对签名进行验证。
if (jiami.validateSign("mysign.bat")) {
System.out.println("Success!");
} else {
System.out.println("Fail!");
}
}
}
dsa代码java的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于dsl代码、dsa代码java的信息别忘了在本站进行查找喔。







