java裸签名代码
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java裸签名代码相关的知识,希望对你有一定的参考价值。
import java.io.File; import java.io.FileInputStream; import java.security.KeyStore; import java.security.PrivateKey; import java.security.Signature; import java.util.Enumeration; import javax.security.cert.Certificate; import javax.security.cert.X509Certificate; import com.sun.org.apache.xml.internal.security.utils.Base64; public class Test { public static void main(String[] args) { String str =sign(); verify(str); } public static String sign() { PrivateKey keyOfSigner=null; java.security.cert.Certificate certOfSigner=null; try{ File file = new File("F:/pro.pfx"); FileInputStream fis = new FileInputStream(file); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(fis, "password".toCharArray()); fis.close(); Enumeration enums = keyStore.aliases(); while (enums.hasMoreElements()) { String keyAlias = (String) enums.nextElement(); if (keyStore.isKeyEntry(keyAlias)) { keyOfSigner = (PrivateKey) keyStore.getKey(keyAlias, "password".toCharArray()); certOfSigner =keyStore.getCertificate(keyAlias); } } byte[] encryptedDigest; Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(keyOfSigner); signature.update("123".getBytes()); encryptedDigest = signature.sign(); System.out.println(Base64.encode(encryptedDigest)); return Base64.encode(encryptedDigest); } catch(Exception e){ e.printStackTrace(); } return null; } public static void verify(String str) { File f = new File("D:/cert.cer"); try { FileInputStream fs = new FileInputStream(f); byte[] be = new byte[fs.available()]; fs.read(be); fs.close(); Certificate x = X509Certificate.getInstance(be); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initVerify(x.getPublicKey()); signature.update("123".getBytes()); boolean b = signature .verify(Base64 .decode(str)); // boolean b = signature // .verify(Base64 // .decode("r50rGj6Hrtq2MEHwrEcQQklEEdeQGokE6RJ84qLsRq/7CR+jdO2pSp4feQW3ufqmu2Cv/jR/T7hRI6qWXVTBZHu/+K2mUnYwk/iOJSQSvzo/fcwqC+HsNaIoWKoDJXIaBLorynd8vd5TeOzmY7FVcrSQG9xSkbA0RSKrRUk8UP1Cu3MuXE0R+YzDPElnwgMIVuM/t8R3WxVjgf4uzDbz/tgUcRHEgWAzD8YQqVR+cNUzjqpN06BmOO13pKqVO5CEY/xppXby7Y/qS7GKhIH7BYRIgoktUeh1TKZ8dsaWpjlyEOMP4YkMOZ1jvU6mGuCtlif92AVJX9OdJIMSBfjyEQ==")); System.out.println(b); } catch (Exception e) { e.printStackTrace(); } } }
以上是关于java裸签名代码的主要内容,如果未能解决你的问题,请参考以下文章