Java security KeyStore Cipher 博客分类: 编程技术
程序员文章站
2024-02-12 14:35:10
...
http://docs.oracle.com/javase/7/docs/technotes/guides/security/crypto/CryptoSpec.html
//c:\Program Files\Java\jdk1.7.0_01\bin>keytool.exe -genkeypair -alias alex -keyalg RSA -keysize 1024 -storepass 123456 -v KeyStore keyStore = KeyStore.getInstance("jks"); char[] password = "123456".toCharArray(); keyStore.load(new FileInputStream("c:/users/administrator/.keystore"), password); Enumeration<String> aliases = keyStore.aliases(); while(aliases.hasMoreElements()){ String element = aliases.nextElement(); System.out.println(element); } String alias = "alex"; Certificate cer = keyStore.getCertificate(alias); String s = cer.toString(); System.out.println(s); System.out.println("public key algorithm:"+cer.getPublicKey().getAlgorithm()); Cipher cipher = Cipher.getInstance(cer.getPublicKey().getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, cer); byte[] msg = cipher.doFinal("hello alex".getBytes()); System.out.println("encrypt result:"+new String(msg)); Key key = keyStore.getKey(alias, password); String algorithm = key.getAlgorithm(); System.out.println("key algorithm:"+algorithm); cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.DECRYPT_MODE, key); byte[] result = cipher.doFinal(msg); System.out.println("decrypt result:"+new String(result));