下面列出了java.security.PrivateKey#getAlgorithm ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Pair a private key with a public EC point.
* <p>
* All private key operations will use the provider.
*/
public ECKey(Provider provider, PrivateKey privKey, ECPoint pub) {
this.provider = provider;
if (privKey == null || isECPrivateKey(privKey)) {
this.privKey = privKey;
} else {
throw new IllegalArgumentException(
"Expected EC private key, given a private key object with class " +
privKey.getClass().toString() +
" and algorithm " + privKey.getAlgorithm());
}
if (pub == null) {
throw new IllegalArgumentException("Public key may not be null");
} else {
this.pub = pub;
}
}
protected void engineInitSign(PrivateKey privateKey, SecureRandom random)
throws InvalidKeyException {
if (!(privateKey instanceof P11PrivateKey)) {
throw new InvalidKeyException("privateKey is not instanceof "
+ P11PrivateKey.class.getName());
}
String algo = privateKey.getAlgorithm();
if (!"RSA".equals(algo)) {
throw new InvalidKeyException("privateKey is not an RSA private key: " + algo);
}
this.signingKey = (P11PrivateKey) privateKey;
pss = new org.bouncycastle.crypto.signers.PSSSigner(signer, contentDigest, mgfDigest,
saltLength, trailer);
P11RSAKeyParameter p11KeyParam = P11RSAKeyParameter.getInstance(
signingKey.getP11CryptService(), signingKey.getIdentityId());
if (random == null) {
pss.init(true, p11KeyParam);
} else {
pss.init(true, new ParametersWithRandom(p11KeyParam, random));
}
}
/**
* Pair a private key with a public EC point.
*
* <p>All private key operations will use the provider.
*/
public ECKey(Provider provider, @Nullable PrivateKey privKey, ECPoint pub) {
this.provider = provider;
if (privKey == null || isECPrivateKey(privKey)) {
this.privKey = privKey;
} else {
throw new IllegalArgumentException(
"Expected EC private key, given a private key object with" +
" class "
+ privKey.getClass().toString() +
" and algorithm "
+ privKey.getAlgorithm());
}
if (pub == null) {
throw new IllegalArgumentException("Public key may not be null");
} else {
this.pub = pub;
}
}
/**
* Pair a private key with a public EC point. <p> All private key operations will use the
* provider.
*/
public ECKey(Provider provider, @Nullable PrivateKey privKey, ECPoint pub) {
this.provider = provider;
if (privKey == null || isECPrivateKey(privKey)) {
this.privKey = privKey;
} else {
throw new IllegalArgumentException(
"Expected EC private key, given a private key object with" +
" class " +
privKey.getClass().toString() +
" and algorithm " + privKey.getAlgorithm());
}
if (pub == null) {
throw new IllegalArgumentException("Public key may not be null");
} else {
this.pub = pub;
}
}
/**
* Pair a private key with a public EC point.
*
* All private key operations will use the provider.
*/
public ECKey(Provider provider, @Nullable PrivateKey privKey, ECPoint pub) {
this.provider = provider;
if (privKey == null || isECPrivateKey(privKey)) {
this.privKey = privKey;
} else {
throw new IllegalArgumentException(
"Expected EC private key, given a private key object with class "
+ privKey.getClass()
+ " and algorithm "
+ privKey.getAlgorithm());
}
if (pub == null) {
throw new IllegalArgumentException("Public key may not be null");
} else {
this.pub = pub;
}
}
private static String toPkcs1Pem(PrivateKey privateKey) {
try (StringWriter stringWriter = new StringWriter(); JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter)) {
String algorithm = privateKey.getAlgorithm();
String type;
if (algorithm.equals(RSA.getAlgorithmName())) {
type = "RSA PRIVATE KEY";
} else if (algorithm.equals(EC.getAlgorithmName())) {
type = "EC PRIVATE KEY";
} else {
throw new IllegalArgumentException("Unexpected key algorithm: " + algorithm);
}
pemWriter.writeObject(new PemObject(type, getPkcs1Bytes(privateKey)));
pemWriter.flush();
return stringWriter.toString();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException {
if (!(privateKey instanceof P11PrivateKey)) {
throw new InvalidKeyException("privateKey is not instanceof "
+ P11PrivateKey.class.getName());
}
String algo = privateKey.getAlgorithm();
if (!"RSA".equals(algo)) {
throw new InvalidKeyException("privateKey is not an RSA private key: " + algo);
}
digest.reset();
this.signingKey = (P11PrivateKey) privateKey;
}
/**
* Compare the supplied public and private keys, and determine if they correspond to the same key pair.
*
* @param pubKey the public key
* @param privKey the private key
* @return true if the public and private are from the same key pair, false if not
* @throws SecurityException if the keys can not be evaluated, or if the key algorithm is unsupported or unknown
*/
public static boolean matchKeyPair(PublicKey pubKey, PrivateKey privKey) throws SecurityException {
Logger log = getLogger();
// This approach attempts to match the keys by signing and then validating some known data.
if (pubKey == null || privKey == null) {
throw new SecurityException("Either public or private key was null");
}
// Need to dynamically determine the JCA signature algorithm ID to use from the key algorithm.
// Don't currently have a direct mapping, so have to map to XML Signature algorithm URI first,
// then map that to JCA algorithm ID.
SecurityConfiguration secConfig = Configuration.getGlobalSecurityConfiguration();
if (secConfig == null) {
throw new SecurityException("Global security configuration was null, could not resolve signing algorithm");
}
String algoURI = secConfig.getSignatureAlgorithmURI(privKey.getAlgorithm());
if (algoURI == null) {
throw new SecurityException("Can't determine algorithm URI from key algorithm: " + privKey.getAlgorithm());
}
String jcaAlgoID = getAlgorithmIDFromURI(algoURI);
if (jcaAlgoID == null) {
throw new SecurityException("Can't determine JCA algorithm ID from algorithm URI: " + algoURI);
}
if (log.isDebugEnabled()) {
log.debug("Attempting to match key pair containing key algorithms public '{}' private '{}', "
+ "using JCA signature algorithm '{}'", new Object[] { pubKey.getAlgorithm(),
privKey.getAlgorithm(), jcaAlgoID, });
}
byte[] data = "This is the data to sign".getBytes();
byte[] signature = SigningUtil.sign(privKey, jcaAlgoID, data);
return SigningUtil.verify(pubKey, jcaAlgoID, signature, data);
}
private static String getSignatureAlgorithm(PrivateKey key, ASN1ObjectIdentifier digestOid) {
HashAlgo hashAlgo = HashAlgo.getInstance(digestOid.getId());
if (hashAlgo == null) {
hashAlgo = HashAlgo.SHA256;
}
String algorithm = key.getAlgorithm();
if ("RSA".equalsIgnoreCase(algorithm)) {
return hashAlgo.getName() + "withRSA";
} else {
throw new UnsupportedOperationException(
"getSignatureAlgorithm() for non-RSA is not supported yet.");
}
}
protected static ContentSigner buildSigner(PrivateKey signingKey, String hashAlgo)
throws OperatorCreationException {
String keyAlgo = signingKey.getAlgorithm();
String sigAlgo;
if ("EC".equalsIgnoreCase(keyAlgo)) {
sigAlgo = hashAlgo + "WITHECDSA";
} else {
sigAlgo = hashAlgo + "WITH" + keyAlgo;
}
return new JcaContentSignerBuilder(sigAlgo).build(signingKey);
}
public static String getSignatureAlgorithm(PrivateKey key, HashAlgo hashAlgo) {
Args.notNull(key, "key");
Args.notNull(hashAlgo, "hashAlgo");
String algorithm = key.getAlgorithm();
if ("RSA".equalsIgnoreCase(algorithm)) {
return hashAlgo.getName() + "withRSA";
} else {
throw new UnsupportedOperationException(
"getSignatureAlgorithm() for non-RSA is not supported yet.");
}
}
/**
* Sign a string using the private key
*
* @param stringToBeSigned
* @param signingKey
*
* @return
*
* @throws GeneralSecurityException
*/
public static byte[] sign(String stringToBeSigned, PrivateKey signingKey) throws GeneralSecurityException {
if (stringToBeSigned == null)
throw logger.nullArgumentError("stringToBeSigned");
if (signingKey == null)
throw logger.nullArgumentError("signingKey");
String algo = signingKey.getAlgorithm();
Signature sig = getSignature(algo);
sig.initSign(signingKey);
sig.update(stringToBeSigned.getBytes(GeneralConstants.SAML_CHARSET));
return sig.sign();
}
private static int signAlias(int testnum, String alias) throws Exception {
if (ks == null) {
ks = KeyStore.getInstance(KS_TYPE, provider);
ks.load(null, tokenPwd);
}
if (alias == null) {
Enumeration enu = ks.aliases();
if (enu.hasMoreElements()) {
alias = (String)enu.nextElement();
}
}
PrivateKey pkey = (PrivateKey)ks.getKey(alias, null);
if ("RSA".equals(pkey.getAlgorithm())) {
System.out.println("got [" + alias + "] signing key: " + pkey);
} else {
throw new SecurityException
("expected RSA, got " + pkey.getAlgorithm());
}
Signature s = Signature.getInstance("MD5WithRSA", ks.getProvider());
s.initSign(pkey);
System.out.println("initialized signature object with key");
s.update("hello".getBytes());
System.out.println("signature object updated with [hello] bytes");
byte[] signed = s.sign();
System.out.println("received signature " + signed.length +
" bytes in length");
Signature v = Signature.getInstance("MD5WithRSA", ks.getProvider());
v.initVerify(ks.getCertificate(alias));
v.update("hello".getBytes());
v.verify(signed);
System.out.println("signature verified");
System.out.println("test " + testnum++ + " passed");
return testnum;
}
public SignatureStructImpl(byte[] payload, PrivateKey privateKey) throws IdentifierException {
this.payload = payload;
keyAlg = privateKey.getAlgorithm();
if ("RSA".equals(keyAlg)) {
hashAlg = "SHA256";
header = Util.encodeString("{\"alg\":\"RS256\"}");
} else if ("DSA".equals(keyAlg)) {
hashAlg = "SHA1";
header = Util.encodeString("{\"alg\":\"DS160\"}");
} else if ("EC".equals(keyAlg)){
hashAlg = "SM3";
header = Util.encodeString("{\"alg\":\"SM2SM3\"}");
}else {
throw new IllegalArgumentException("未知算法: " + keyAlg);
}
based64_Header = Base64.encodeBase64URLSafe(header);
based64_Payload = Base64.encodeBase64URLSafe(payload);
try {
if("EC".equals(keyAlg)){
SM2Tool sm2Tool = new SM2Tool();
byte[] bDot = new byte[]{(byte)'.'};
byte[] signData = Util.join(based64_Header,bDot,based64_Payload);
String data = new String(signData);
String id = "1234567812345678";
BigInteger prvKey = ((BCECPrivateKey) privateKey).getD();
ECPoint pubkey = sm2Tool.G.multiply(prvKey).normalize();
cn.ac.caict.iiiiot.id.client.security.gm.SM2Tool.Signature sign = sm2Tool.sign(data, id, new SM2KeyPair(pubkey,prvKey));
//signature转为byte[]
byte[] bR = sign.r.toByteArray();
byte[] bS = sign.s.toByteArray();
signature = BaseConvertor.signatureFormat(bR,bS);
//将byte[]用Base64编码
based64_Signature = Base64.encodeBase64URLSafe(signature);
} else {
Signature sig = Signature.getInstance(hashAlg + "with" + keyAlg);
sig.initSign(privateKey);
sig.update(based64_Header);
sig.update((byte) '.');
sig.update(based64_Payload);
signature = sig.sign();
based64_Signature = Base64.encodeBase64URLSafe(signature);
}
} catch (Exception e) {
throw new IdentifierException(ExceptionCommon.EXCEPTIONCODE_SECURITY_ALERT, "构建签名数据失败");
}
}
private static int signAlias(int testnum, String alias) throws Exception {
if (ks == null) {
ks = KeyStore.getInstance(KS_TYPE, provider);
ks.load(null, tokenPwd);
}
if (alias == null) {
Enumeration enu = ks.aliases();
if (enu.hasMoreElements()) {
alias = (String)enu.nextElement();
}
}
PrivateKey pkey = (PrivateKey)ks.getKey(alias, null);
if ("RSA".equals(pkey.getAlgorithm())) {
System.out.println("got [" + alias + "] signing key: " + pkey);
} else {
throw new SecurityException
("expected RSA, got " + pkey.getAlgorithm());
}
Signature s = Signature.getInstance("MD5WithRSA", ks.getProvider());
s.initSign(pkey);
System.out.println("initialized signature object with key");
s.update("hello".getBytes());
System.out.println("signature object updated with [hello] bytes");
byte[] signed = s.sign();
System.out.println("received signature " + signed.length +
" bytes in length");
Signature v = Signature.getInstance("MD5WithRSA", ks.getProvider());
v.initVerify(ks.getCertificate(alias));
v.update("hello".getBytes());
v.verify(signed);
System.out.println("signature verified");
System.out.println("test " + testnum++ + " passed");
return testnum;
}
@Override
protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException {
if (!(privateKey instanceof P11PrivateKey)) {
throw new InvalidKeyException("privateKey is not instanceof "
+ P11PrivateKey.class.getName());
}
String algo = privateKey.getAlgorithm();
if (!"DSA".equals(algo)) {
throw new InvalidKeyException("privateKey is not a DSA private key: " + algo);
}
this.signingKey = (P11PrivateKey) privateKey;
if (signingKey.supportsMechanism(PKCS11Constants.CKM_DSA)) {
mechanism = PKCS11Constants.CKM_DSA;
if (hashAlgo == null) {
outputStream = new ByteArrayOutputStream();
} else {
outputStream = new DigestOutputStream(hashAlgo.createDigest());
}
} else {
if (hashAlgo == HashAlgo.SHA1
&& signingKey.supportsMechanism(PKCS11Constants.CKM_DSA_SHA1)) {
mechanism = PKCS11Constants.CKM_DSA_SHA1;
} else if (hashAlgo == HashAlgo.SHA224
&& signingKey.supportsMechanism(PKCS11Constants.CKM_DSA_SHA224)) {
mechanism = PKCS11Constants.CKM_DSA_SHA224;
} else if (hashAlgo == HashAlgo.SHA256
&& signingKey.supportsMechanism(PKCS11Constants.CKM_DSA_SHA256)) {
mechanism = PKCS11Constants.CKM_DSA_SHA256;
} else if (hashAlgo == HashAlgo.SHA384
&& signingKey.supportsMechanism(PKCS11Constants.CKM_DSA_SHA384)) {
mechanism = PKCS11Constants.CKM_DSA_SHA384;
} else if (hashAlgo == HashAlgo.SHA512
&& signingKey.supportsMechanism(PKCS11Constants.CKM_DSA_SHA512)) {
mechanism = PKCS11Constants.CKM_DSA_SHA512;
} else if (hashAlgo == HashAlgo.SHA3_224
&& signingKey.supportsMechanism(PKCS11Constants.CKM_DSA_SHA3_224)) {
mechanism = PKCS11Constants.CKM_DSA_SHA3_224;
} else if (hashAlgo == HashAlgo.SHA3_256
&& signingKey.supportsMechanism(PKCS11Constants.CKM_DSA_SHA3_256)) {
mechanism = PKCS11Constants.CKM_DSA_SHA3_256;
} else if (hashAlgo == HashAlgo.SHA3_384
&& signingKey.supportsMechanism(PKCS11Constants.CKM_DSA_SHA3_384)) {
mechanism = PKCS11Constants.CKM_DSA_SHA3_384;
} else if (hashAlgo == HashAlgo.SHA3_512
&& signingKey.supportsMechanism(PKCS11Constants.CKM_DSA_SHA3_512)) {
mechanism = PKCS11Constants.CKM_DSA_SHA3_512;
} else {
throw new InvalidKeyException("privateKey and algorithm does not match");
}
outputStream = new ByteArrayOutputStream();
}
this.signingKey = (P11PrivateKey) privateKey;
}
private static int signAlias(int testnum, String alias) throws Exception {
if (ks == null) {
ks = KeyStore.getInstance(KS_TYPE, provider);
ks.load(null, tokenPwd);
}
if (alias == null) {
Enumeration enu = ks.aliases();
if (enu.hasMoreElements()) {
alias = (String)enu.nextElement();
}
}
PrivateKey pkey = (PrivateKey)ks.getKey(alias, null);
if ("RSA".equals(pkey.getAlgorithm())) {
System.out.println("got [" + alias + "] signing key: " + pkey);
} else {
throw new SecurityException
("expected RSA, got " + pkey.getAlgorithm());
}
Signature s = Signature.getInstance("MD5WithRSA", ks.getProvider());
s.initSign(pkey);
System.out.println("initialized signature object with key");
s.update("hello".getBytes());
System.out.println("signature object updated with [hello] bytes");
byte[] signed = s.sign();
System.out.println("received signature " + signed.length +
" bytes in length");
Signature v = Signature.getInstance("MD5WithRSA", ks.getProvider());
v.initVerify(ks.getCertificate(alias));
v.update("hello".getBytes());
v.verify(signed);
System.out.println("signature verified");
System.out.println("test " + testnum++ + " passed");
return testnum;
}
@Override
protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException {
if (!(privateKey instanceof P11PrivateKey)) {
throw new InvalidKeyException("privateKey is not instanceof "
+ P11PrivateKey.class.getName());
}
this.signingKey = (P11PrivateKey) privateKey;
if (!(signingKey.getPublicKey() instanceof ECPublicKey)) {
throw new InvalidKeyException("only EC key is allowed");
}
ECPublicKey pubKey = (ECPublicKey) signingKey.getPublicKey();
if (!GMUtil.isSm2primev2Curve(pubKey.getParams().getCurve())) {
throw new InvalidKeyException("only EC key of curve sm2primev2 is allowed");
}
String algo = privateKey.getAlgorithm();
if (!("EC".equals(algo) || "ECDSA".equals(algo))) {
throw new InvalidKeyException("privateKey is not an EC private key: " + algo);
}
byte[] userId = (paramSpec == null)
? StringUtil.toUtf8Bytes("1234567812345678") : paramSpec.getId();
if (signingKey.supportsMechanism(PKCS11Constants.CKM_VENDOR_SM2)) {
mechanism = PKCS11Constants.CKM_VENDOR_SM2;
outputStream = new DigestOutputStream(HashAlgo.SM3.createDigest());
p11Params = null;
ECPoint w = pubKey.getW();
sm2Z = GMUtil.getSM2Z(userId, GMObjectIdentifiers.sm2p256v1, w.getAffineX(), w.getAffineY());
try {
outputStream.write(sm2Z, 0, sm2Z.length);
} catch (IOException ex) {
throw new InvalidKeyException("could not compute Z of SM2");
}
} else if (signingKey.supportsMechanism(PKCS11Constants.CKM_VENDOR_SM2_SM3)) {
mechanism = PKCS11Constants.CKM_VENDOR_SM2_SM3;
outputStream = new ByteArrayOutputStream();
p11Params = new P11ByteArrayParams(userId);
} else {
throw new InvalidKeyException("privateKey and algorithm does not match");
}
this.signingKey = (P11PrivateKey) privateKey;
}
/**
* Generates a signature.
* @param privKey the private key
* @param certChain the certificate chain
* @param crlList the certificate revocation list
* @param hashAlgorithm the hash algorithm
* @param provider the provider or <code>null</code> for the default provider
* @param hasRSAdata <CODE>true</CODE> if the sub-filter is adbe.pkcs7.sha1
* @throws InvalidKeyException on error
* @throws NoSuchProviderException on error
* @throws NoSuchAlgorithmException on error
*/
public PdfPKCS7(PrivateKey privKey, Certificate[] certChain, CRL[] crlList,
String hashAlgorithm, String provider, boolean hasRSAdata)
throws InvalidKeyException, NoSuchProviderException,
NoSuchAlgorithmException
{
this.privKey = privKey;
this.provider = provider;
digestAlgorithm = (String)allowedDigests.get(hashAlgorithm.toUpperCase());
if (digestAlgorithm == null)
throw new NoSuchAlgorithmException("Unknown Hash Algorithm "+hashAlgorithm);
version = signerversion = 1;
certs = new ArrayList();
crls = new ArrayList();
digestalgos = new HashSet();
digestalgos.add(digestAlgorithm);
//
// Copy in the certificates and crls used to sign the private key.
//
signCert = (X509Certificate)certChain[0];
for (int i = 0;i < certChain.length;i++) {
certs.add(certChain[i]);
}
if (crlList != null) {
for (int i = 0;i < crlList.length;i++) {
crls.add(crlList[i]);
}
}
if (privKey != null) {
//
// Now we have private key, find out what the digestEncryptionAlgorithm is.
//
digestEncryptionAlgorithm = privKey.getAlgorithm();
if (digestEncryptionAlgorithm.equals("RSA")) {
digestEncryptionAlgorithm = ID_RSA;
}
else if (digestEncryptionAlgorithm.equals("DSA")) {
digestEncryptionAlgorithm = ID_DSA;
}
else {
throw new NoSuchAlgorithmException("Unknown Key Algorithm "+digestEncryptionAlgorithm);
}
}
if (hasRSAdata) {
RSAdata = new byte[0];
if (provider == null || provider.startsWith("SunPKCS11"))
messageDigest = MessageDigest.getInstance(getHashAlgorithm());
else
messageDigest = MessageDigest.getInstance(getHashAlgorithm(), provider);
}
if (privKey != null) {
if (provider == null)
sig = Signature.getInstance(getDigestAlgorithm());
else
sig = Signature.getInstance(getDigestAlgorithm(), provider);
sig.initSign(privKey);
}
}
private static int signAlias(int testnum, String alias) throws Exception {
if (ks == null) {
ks = KeyStore.getInstance(KS_TYPE, provider);
ks.load(null, tokenPwd);
}
if (alias == null) {
Enumeration enu = ks.aliases();
if (enu.hasMoreElements()) {
alias = (String)enu.nextElement();
}
}
PrivateKey pkey = (PrivateKey)ks.getKey(alias, null);
if ("RSA".equals(pkey.getAlgorithm())) {
System.out.println("got [" + alias + "] signing key: " + pkey);
} else {
throw new SecurityException
("expected RSA, got " + pkey.getAlgorithm());
}
Signature s = Signature.getInstance("MD5WithRSA", ks.getProvider());
s.initSign(pkey);
System.out.println("initialized signature object with key");
s.update("hello".getBytes());
System.out.println("signature object updated with [hello] bytes");
byte[] signed = s.sign();
System.out.println("received signature " + signed.length +
" bytes in length");
Signature v = Signature.getInstance("MD5WithRSA", ks.getProvider());
v.initVerify(ks.getCertificate(alias));
v.update("hello".getBytes());
v.verify(signed);
System.out.println("signature verified");
System.out.println("test " + testnum++ + " passed");
return testnum;
}