本文整理汇总了Java中java.security.Signature.sign方法的典型用法代码示例。如果您正苦于以下问题:Java Signature.sign方法的具体用法?Java Signature.sign怎么用?Java Signature.sign使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.security.Signature
的用法示例。
在下文中一共展示了Signature.sign方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testInvalidSignature
import java.security.Signature; //导入方法依赖的package包/类
private static void testInvalidSignature(KeyPair kp1, KeyPair kp2) throws Exception {
System.out.println("Testing signature with incorrect key...");
Signature sig = Signature.getInstance("MD5withRSA", provider);
sig.initSign(kp1.getPrivate());
byte[] data = new byte[100];
sig.update(data);
byte[] signature = sig.sign();
sig.initVerify(kp1.getPublic());
sig.update(data);
if (sig.verify(signature) == false) {
throw new Exception("verification failed");
}
sig.initVerify(kp2.getPublic());
sig.update(data);
// verify needs to return false and not throw an Exception
if (sig.verify(signature)) {
throw new Exception("verification unexpectedly succeeded");
}
}
示例2: sign
import java.security.Signature; //导入方法依赖的package包/类
/**
* Compute the raw signature value over the supplied input.
*
* It is up to the caller to ensure that the specified algorithm ID is consistent with the type of signing key
* supplied.
*
* @param signingKey the private key with which to compute the signature
* @param jcaAlgorithmID the Java JCA algorithm ID to use
* @param input the input over which to compute the signature
* @return the computed signature value
* @throws SecurityException thrown if the signature computation results in an error
*/
public static byte[] sign(PrivateKey signingKey, String jcaAlgorithmID, byte[] input) throws SecurityException {
Logger log = getLogger();
log.debug("Computing signature over input using private key of type {} and JCA algorithm ID {}", signingKey
.getAlgorithm(), jcaAlgorithmID);
try {
Signature signature = Signature.getInstance(jcaAlgorithmID);
signature.initSign(signingKey);
signature.update(input);
byte[] rawSignature = signature.sign();
log.debug("Computed signature: {}", new String(Hex.encode(rawSignature)));
return rawSignature;
} catch (GeneralSecurityException e) {
log.error("Error during signature generation", e);
throw new SecurityException("Error during signature generation", e);
}
}
示例3: createEncoder
import java.security.Signature; //导入方法依赖的package包/类
@Override
public OneWayCodec createEncoder() throws Exception {
final Signature signature = Signature.getInstance(signatureAlgorithmName);
signature.initSign(keyPair.getPrivate());
return new OneWayCodec() {
@Override
public byte[] code(final byte[] data) throws Exception {
final int dataLen = data.length;
final byte[] b = new byte[dataLen + signatureLength];
System.arraycopy(data, 0, b, 0, dataLen);
signature.update(data);
signature.sign(b, dataLen, signatureLength);
return b;
}
};
}
示例4: testSignature
import java.security.Signature; //导入方法依赖的package包/类
private static void testSignature(String algorithm, PrivateKey privateKey,
PublicKey publicKey) throws Exception {
System.out.println("Testing " + algorithm + "...");
Signature s = Signature.getInstance(algorithm, provider);
s.initSign(privateKey);
s.update(data);
byte[] sig = s.sign();
s.initVerify(publicKey);
s.update(data);
boolean result;
result = s.verify(sig);
if (result == false) {
throw new Exception("Verification 1 failed");
}
s.update(data);
result = s.verify(sig);
if (result == false) {
throw new Exception("Verification 2 failed");
}
result = s.verify(sig);
if (result == true) {
throw new Exception("Verification 3 succeeded");
}
}
示例5: test
import java.security.Signature; //导入方法依赖的package包/类
public static void test() throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(512, new SecureRandom());
KeyPair keyPair = keyGen.generateKeyPair();
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(keyPair.getPrivate());
byte[] message = "abc".getBytes();
signature.update(message);
byte[] sigBytes = signature.sign();
signature.initVerify(keyPair.getPublic());
signature.update(message);
System.out.println(signature.verify(sigBytes));
}
示例6: sign
import java.security.Signature; //导入方法依赖的package包/类
protected static byte[]
sign(
byte[] private_key,
byte[] hash,
int version,
int size )
throws Exception
{
Signature signature = CryptoECCUtils.getSignature( CryptoECCUtils.rawdataToPrivkey( private_key ));
// key for signature is hash + version + size so we have some
// control over auto-update process and prevent people from injecting
// potentially huge bogus updates
signature.update( encode( hash, version, size ));
return( signature.sign());
}
示例7: calculateSignature
import java.security.Signature; //导入方法依赖的package包/类
static byte[] calculateSignature(
DERObjectIdentifier sigOid,
String sigName,
PrivateKey key,
SecureRandom random,
ASN1Encodable object)
throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException
{
Signature sig;
if (sigOid == null)
{
throw new IllegalStateException("no signature algorithm specified");
}
sig = X509Util.getSignatureInstance(sigName);
if (random != null)
{
sig.initSign(key, random);
}
else
{
sig.initSign(key);
}
sig.update(object.toASN1Primitive().getEncoded(ASN1Encoding.DER));
return sig.sign();
}
示例8: use
import java.security.Signature; //导入方法依赖的package包/类
static boolean use(KeyPair kp) throws Exception {
Signature sig = Signature.getInstance("SHA1withDSA");
sig.initSign(kp.getPrivate());
sig.update(data);
byte[] signed = sig.sign();
Signature sig2 = Signature.getInstance("SHA1withDSA");
sig2.initVerify(kp.getPublic());
sig2.update(data);
return sig2.verify(signed);
}
示例9: encodeAndSign
import java.security.Signature; //导入方法依赖的package包/类
/**
* Create the signed certificate request. This will later be
* retrieved in either string or binary format.
*
* @param subject identifies the signer (by X.500 name).
* @param signature private key and signing algorithm to use.
* @exception IOException on errors.
* @exception CertificateException on certificate handling errors.
* @exception SignatureException on signature handling errors.
*/
public void encodeAndSign(X500Name subject, Signature signature)
throws CertificateException, IOException, SignatureException {
DerOutputStream out, scratch;
byte[] certificateRequestInfo;
byte[] sig;
if (encoded != null)
throw new SignatureException("request is already signed");
this.subject = subject;
/*
* Encode cert request info, wrap in a sequence for signing
*/
scratch = new DerOutputStream();
scratch.putInteger(BigInteger.ZERO); // PKCS #10 v1.0
subject.encode(scratch); // X.500 name
scratch.write(subjectPublicKeyInfo.getEncoded()); // public key
attributeSet.encode(scratch);
out = new DerOutputStream();
out.write(DerValue.tag_Sequence, scratch); // wrap it!
certificateRequestInfo = out.toByteArray();
scratch = out;
/*
* Sign it ...
*/
signature.update(certificateRequestInfo, 0,
certificateRequestInfo.length);
sig = signature.sign();
/*
* Build guts of SIGNED macro
*/
AlgorithmId algId = null;
try {
algId = AlgorithmId.get(signature.getAlgorithm());
} catch (NoSuchAlgorithmException nsae) {
throw new SignatureException(nsae);
}
algId.encode(scratch); // sig algorithm
scratch.putBitString(sig); // sig
/*
* Wrap those guts in a sequence
*/
out = new DerOutputStream();
out.write(DerValue.tag_Sequence, scratch);
encoded = out.toByteArray();
}
示例10: main
import java.security.Signature; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
if (initSecmod() == false) {
return;
}
String configName = BASE + SEP + "nss.cfg";
Provider p = getSunPKCS11(configName);
System.out.println(p);
Security.addProvider(p);
if (args.length > 1 && "sm".equals(args[0])) {
System.setProperty("java.security.policy",
BASE + File.separator + args[1]);
System.setSecurityManager(new SecurityManager());
}
KeyStore ks = KeyStore.getInstance(PKCS11, p);
ks.load(null, password);
Collection<String> aliases = new TreeSet<>(
Collections.list(ks.aliases()));
System.out.println("entries: " + aliases.size());
System.out.println(aliases);
PrivateKey privateKey = (PrivateKey)ks.getKey(keyAlias, password);
System.out.println(privateKey);
byte[] data = generateData(1024);
System.out.println("Signing...");
Signature signature = Signature.getInstance("MD5withRSA");
signature.initSign(privateKey);
signature.update(data);
byte[] sig = signature.sign();
X509Certificate[] chain =
(X509Certificate[]) ks.getCertificateChain(keyAlias);
signature.initVerify(chain[0].getPublicKey());
signature.update(data);
boolean ok = signature.verify(sig);
if (ok == false) {
throw new Exception("Signature verification error");
}
System.out.println("OK");
}
示例11: testWolfSignInitMulti
import java.security.Signature; //导入方法依赖的package包/类
@Test
public void testWolfSignInitMulti()
throws NoSuchProviderException, NoSuchAlgorithmException,
SignatureException, InvalidKeyException,
InvalidAlgorithmParameterException {
String toSign = "Hello World";
byte[] toSignBuf = toSign.getBytes();
byte[] signature = null;
for (int i = 0; i < wolfJCEAlgos.length; i++) {
Signature signer =
Signature.getInstance(wolfJCEAlgos[i], "wolfJCE");
Signature verifier =
Signature.getInstance(wolfJCEAlgos[i], "wolfJCE");
assertNotNull(signer);
assertNotNull(verifier);
SecureRandom rand =
SecureRandom.getInstance("HashDRBG", "wolfJCE");
assertNotNull(rand);
/* generate key pair */
KeyPair pair = generateKeyPair(wolfJCEAlgos[i], rand);
assertNotNull(pair);
PrivateKey priv = pair.getPrivate();
PublicKey pub = pair.getPublic();
/* test multiple inits on signer */
signer.initSign(priv);
signer.initSign(priv);
/* test multiple inits on verifier */
verifier.initVerify(pub);
verifier.initVerify(pub);
/* make sure sign/verify still work after multi init */
signer.update(toSignBuf, 0, toSignBuf.length);
signature = signer.sign();
verifier.update(toSignBuf, 0, toSignBuf.length);
boolean verified = verifier.verify(signature);
if (verified != true) {
fail("Signature verification failed when generating with " +
"wolfJCE and verifying with system default JCE " +
"provider");
}
}
}
示例12: signBySoft
import java.security.Signature; //导入方法依赖的package包/类
/**
*
* @param privateKey
* @param data
* @return
* @throws Exception
*/
public static byte[] signBySoft(PrivateKey privateKey, byte[] data)
throws Exception {
byte[] result = null;
Signature st = Signature.getInstance(BC_PROV_ALGORITHM_SHA1RSA, "BC");
st.initSign(privateKey);
st.update(data);
result = st.sign();
return result;
}
示例13: Offsets
import java.security.Signature; //导入方法依赖的package包/类
private Offsets(Signature signature, PublicKey pubkey, PrivateKey privkey,
int size, byte[] cleartext) throws InvalidKeyException,
SignatureException {
this.pubkey = pubkey;
this.signature = signature;
this.size = size;
this.cleartext = cleartext;
signature.initSign(privkey);
signature.update(cleartext, 0, size);
signed = signature.sign();
}
示例14: sign
import java.security.Signature; //导入方法依赖的package包/类
/**
* Encodes an X.509 CRL, and signs it using the given key.
*
* @param key the private key used for signing.
* @param algorithm the name of the signature algorithm used.
* @param provider the name of the provider.
*
* @exception NoSuchAlgorithmException on unsupported signature
* algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchProviderException on incorrect provider.
* @exception SignatureException on signature errors.
* @exception CRLException if any mandatory data was omitted.
*/
public void sign(PrivateKey key, String algorithm, String provider)
throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
NoSuchProviderException, SignatureException {
try {
if (readOnly)
throw new CRLException("cannot over-write existing CRL");
Signature sigEngine = null;
if ((provider == null) || (provider.length() == 0))
sigEngine = Signature.getInstance(algorithm);
else
sigEngine = Signature.getInstance(algorithm, provider);
sigEngine.initSign(key);
// in case the name is reset
sigAlgId = AlgorithmId.get(sigEngine.getAlgorithm());
infoSigAlgId = sigAlgId;
DerOutputStream out = new DerOutputStream();
DerOutputStream tmp = new DerOutputStream();
// encode crl info
encodeInfo(tmp);
// encode algorithm identifier
sigAlgId.encode(tmp);
// Create and encode the signature itself.
sigEngine.update(tbsCertList, 0, tbsCertList.length);
signature = sigEngine.sign();
tmp.putBitString(signature);
// Wrap the signed data in a SEQUENCE { data, algorithm, sig }
out.write(DerValue.tag_Sequence, tmp);
signedCRL = out.toByteArray();
readOnly = true;
} catch (IOException e) {
throw new CRLException("Error while encoding data: " +
e.getMessage());
}
}
示例15: signBySoft256
import java.security.Signature; //导入方法依赖的package包/类
/**
* @param privateKey
* @param data
* @return
* @throws Exception
*/
public static byte[] signBySoft256(PrivateKey privateKey, byte[] data)
throws Exception {
byte[] result = null;
Signature st = Signature.getInstance(BC_PROV_ALGORITHM_SHA256RSA, "BC");
st.initSign(privateKey);
st.update(data);
result = st.sign();
return result;
}