本文整理汇总了Java中java.security.Signature.update方法的典型用法代码示例。如果您正苦于以下问题:Java Signature.update方法的具体用法?Java Signature.update怎么用?Java Signature.update使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.security.Signature
的用法示例。
在下文中一共展示了Signature.update方法的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包/类
/**
* <p>
* 用私钥对信息生成数字签名
* </p>
*
* @param data 已加密数据
* @param privateKey 私钥(BASE64编码)
* @return
* @throws Exception
*/
public static String sign(byte[] data, String privateKey) throws Exception {
byte[] keyBytes = Base64Utils.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateK);
signature.update(data);
return Base64Utils.encode(signature.sign());
}
示例3: createJWT
import java.security.Signature; //导入方法依赖的package包/类
public String createJWT(String username, Set<String> groups)
throws GeneralSecurityException, IOException {
// Create and Base64 encode the header portion of the JWT
JsonObject headerObj =
Json.createObjectBuilder()
.add("alg", "RS256") /* Algorithm used */
.add("typ", "JWT") /* Type of token */
// .add("kid", "default") /* Hint about which key to use to sign, but the signature is
// invalid when I include this. */
.build();
String headerEnc = Base64Utility.encode(headerObj.toString().getBytes(), true);
// Create and Base64 encode the claims portion of the JWT
JsonObject claimsObj =
Json.createObjectBuilder()
.add("exp", (System.currentTimeMillis() / 1000) + 300) /* Expire time */
.add("iat", (System.currentTimeMillis() / 1000)) /* Issued time */
.add("aud", "acmeGifts") /* Audience */
.add("jti", Long.toHexString(System.nanoTime())) /* Unique value */
.add("sub", username) /* Subject */
.add("upn", username) /* Subject again */
.add("iss", JWT_ISSUER) /* Issuer */
.add("groups", getGroupArray(groups)) /* Group list */
.build();
String claimsEnc = Base64Utility.encode(claimsObj.toString().getBytes(), true);
String headerClaimsEnc = headerEnc + "." + claimsEnc;
// Open the keystore that the server will use to validate the JWT
KeyStore ks = KeyStore.getInstance("JCEKS");
InputStream ksStream = this.getClass().getResourceAsStream("/keystore.jceks");
char[] password = new String("secret").toCharArray();
ks.load(ksStream, password);
// Get the private key to use to sign the JWT. Normally we would not do this but
// we are pretending to be the user service here.
KeyStore.ProtectionParameter keyPassword = new KeyStore.PasswordProtection(password);
KeyStore.PrivateKeyEntry privateKeyEntry =
(KeyStore.PrivateKeyEntry) ks.getEntry("default", keyPassword);
PrivateKey privateKey = privateKeyEntry.getPrivateKey();
// Sign the JWT
Signature sig = Signature.getInstance(JWT_ALGORITHM);
sig.initSign(privateKey);
sig.update(headerClaimsEnc.getBytes());
String sigEnc = Base64Utility.encode(sig.sign(), true);
// Lets just check......
String jwtEnc = headerClaimsEnc + "." + sigEnc;
java.security.cert.Certificate cert = ks.getCertificate("default");
PublicKey publicKey = cert.getPublicKey();
validateJWT("Bearer " + jwtEnc, publicKey);
// Return the complete JWT (header, claims, signature).
return jwtEnc;
}
示例4: sign
import java.security.Signature; //导入方法依赖的package包/类
/**
* 签名
*
* @param data 待签名数据
* @param privateKey 私钥
* @return byte[] 数字签名
* @throws Exception
*/
public static byte[] sign(byte[] data, byte[] privateKey) throws Exception {
// 转换私钥材料
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
// 实例化密钥工厂
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
// 取私钥匙对象
PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 实例化Signature
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
// 初始化Signature
signature.initSign(priKey);
// 更新
signature.update(data);
// 签名
return signature.sign();
}
示例5: doSign
import java.security.Signature; //导入方法依赖的package包/类
/**
* Signs the given hash and returns the R and S components as BigIntegers
* and put them in ECDSASignature
*
* @param input to sign
* @return ECDSASignature signature that contains the R and S components
*/
public ECDSASignature doSign(byte[] input) {
if (input.length != 32) {
throw new IllegalArgumentException("Expected 32 byte input to ECDSA signature, not " + input.length);
}
// No decryption of private key required.
if (privKey == null)
throw new MissingPrivateKeyException();
if (privKey instanceof BCECPrivateKey) {
ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
ECPrivateKeyParameters privKeyParams = new ECPrivateKeyParameters(((BCECPrivateKey) privKey).getD(), CURVE);
signer.init(true, privKeyParams);
BigInteger[] components = signer.generateSignature(input);
return new ECDSASignature(components[0], components[1]).toCanonicalised();
} else {
try {
final Signature ecSig = ECSignatureFactory.getRawInstance(provider);
ecSig.initSign(privKey);
ecSig.update(input);
final byte[] derSignature = ecSig.sign();
return ECDSASignature.decodeFromDER(derSignature).toCanonicalised();
} catch (SignatureException | InvalidKeyException ex) {
throw new RuntimeException("ECKey signing error", ex);
}
}
}
示例6: 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");
}
}
示例7: validate
import java.security.Signature; //导入方法依赖的package包/类
@Override
public boolean validate(MessagePayload message) {
if (this.publicKey == null) {
throw new RuntimeException("publicKey not initialized");
}
try {
Signature sgr = new EdDSAEngine(MessageDigest.getInstance("SHA-512"));
sgr.initVerify(this.publicKey);
sgr.update(message.payload);
return sgr.verify(signature.payload);
} catch (Exception e) {
throw new RuntimeException(e.toString(), e);
}
}
示例8: verify
import java.security.Signature; //导入方法依赖的package包/类
/**
* Verifies that this CRL was signed using the
* private key that corresponds to the given public key,
* and that the signature verification was computed by
* the given provider.
*
* @param key the PublicKey used to carry out the verification.
* @param sigProvider the name of the signature provider.
*
* @exception NoSuchAlgorithmException on unsupported signature
* algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchProviderException on incorrect provider.
* @exception SignatureException on signature errors.
* @exception CRLException on encoding errors.
*/
public synchronized void verify(PublicKey key, String sigProvider)
throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
NoSuchProviderException, SignatureException {
if (sigProvider == null) {
sigProvider = "";
}
if ((verifiedPublicKey != null) && verifiedPublicKey.equals(key)) {
// this CRL has already been successfully verified using
// this public key. Make sure providers match, too.
if (sigProvider.equals(verifiedProvider)) {
return;
}
}
if (signedCRL == null) {
throw new CRLException("Uninitialized CRL");
}
Signature sigVerf = null;
if (sigProvider.length() == 0) {
sigVerf = Signature.getInstance(sigAlgId.getName());
} else {
sigVerf = Signature.getInstance(sigAlgId.getName(), sigProvider);
}
sigVerf.initVerify(key);
if (tbsCertList == null) {
throw new CRLException("Uninitialized CRL");
}
sigVerf.update(tbsCertList, 0, tbsCertList.length);
if (!sigVerf.verify(signature)) {
throw new SignatureException("Signature does not match.");
}
verifiedPublicKey = key;
verifiedProvider = sigProvider;
}
示例9: 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;
}
示例10: runTest
import java.security.Signature; //导入方法依赖的package包/类
private void runTest(OidAlgorithmPair oidAlgorithmPair, KeyPair keyPair)
throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidKeyException, SignatureException {
Signature sgAlgorithm =
Signature.getInstance(oidAlgorithmPair.algorithm, provider);
Signature sgOid = Signature.getInstance(oidAlgorithmPair.oid, provider);
if (sgAlgorithm == null) {
throw new RuntimeException(String.format(
"Test failed: algorithm string %s getInstance failed.%n",
oidAlgorithmPair.algorithm));
}
if (sgOid == null) {
throw new RuntimeException(
String.format("Test failed: OID %s getInstance failed.%n",
oidAlgorithmPair.oid));
}
if (!sgAlgorithm.getAlgorithm().equals(oidAlgorithmPair.algorithm)) {
throw new RuntimeException(String.format(
"Test failed: algorithm string %s getInstance "
+ "doesn't generate expected algorithm.%n",
oidAlgorithmPair.algorithm));
}
sgAlgorithm.initSign(keyPair.getPrivate());
sgAlgorithm.update(INPUT);
sgOid.initVerify(keyPair.getPublic());
sgOid.update(INPUT);
if (!sgOid.verify(sgAlgorithm.sign())) {
throw new RuntimeException(
"Signature verification failed unexpectedly");
}
}
示例11: 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();
}
示例12: sign
import java.security.Signature; //导入方法依赖的package包/类
/**
* Sign a message using the given private key.
* @param privateKey The private key
* @param data The message
* @return The signature
*/
public static byte[] sign(PrivateKey privateKey, byte[] data) {
try {
Signature sig = Signature.getInstance("SHA256withECDSA", PROVIDER);
sig.initSign(privateKey);
sig.update(data);
return sig.sign();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
示例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: getCredentials
import java.security.Signature; //导入方法依赖的package包/类
@Override
public Properties getCredentials(final Properties securityProperties,
final DistributedMember server, final boolean isPeer) throws AuthenticationFailedException {
final String keyStorePath = securityProperties.getProperty(KEYSTORE_FILE_PATH);
if (keyStorePath == null) {
throw new AuthenticationFailedException(
"PKCSAuthInit: key-store file path property [" + KEYSTORE_FILE_PATH + "] not set.");
}
final String alias = securityProperties.getProperty(KEYSTORE_ALIAS);
if (alias == null) {
throw new AuthenticationFailedException(
"PKCSAuthInit: key alias name property [" + KEYSTORE_ALIAS + "] not set.");
}
final String keyStorePass = securityProperties.getProperty(KEYSTORE_PASSWORD);
try {
final KeyStore ks = KeyStore.getInstance("PKCS12");
final char[] passPhrase = (keyStorePass != null ? keyStorePass.toCharArray() : null);
final FileInputStream certificatefile = new FileInputStream(keyStorePath);
try {
ks.load(certificatefile, passPhrase);
} finally {
certificatefile.close();
}
final Key key = ks.getKey(alias, passPhrase);
if (key instanceof PrivateKey) {
final PrivateKey privKey = (PrivateKey) key;
final X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
final Signature sig = Signature.getInstance(cert.getSigAlgName());
sig.initSign(privKey);
sig.update(alias.getBytes("UTF-8"));
final byte[] signatureBytes = sig.sign();
final Properties newprops = new Properties();
newprops.put(KEYSTORE_ALIAS, alias);
newprops.put(SIGNATURE_DATA, signatureBytes);
return newprops;
} else {
throw new AuthenticationFailedException(
"PKCSAuthInit: " + "Failed to load private key from the given file: " + keyStorePath);
}
} catch (Exception ex) {
throw new AuthenticationFailedException(
"PKCSAuthInit: Exception while getting credentials: " + ex, ex);
}
}
示例15: main0
import java.security.Signature; //导入方法依赖的package包/类
private static void main0(String keyAlgorithm, int keysize,
String signatureAlgorithm, String provider) throws Exception {
byte[] plaintext = "aaa".getBytes("UTF-8");
// Generate
KeyPairGenerator generator =
provider == null ?
(KeyPairGenerator) KeyPairGenerator.getInstance(keyAlgorithm) :
(KeyPairGenerator) KeyPairGenerator.getInstance(
keyAlgorithm, provider);
generator.initialize(keysize);
System.out.println("Generating " + keyAlgorithm + " keypair using " +
generator.getProvider().getName() + " JCE provider");
KeyPair keypair = generator.generateKeyPair();
// Sign
Signature signer =
provider == null ?
Signature.getInstance(signatureAlgorithm) :
Signature.getInstance(signatureAlgorithm, provider);
signer.initSign(keypair.getPrivate());
signer.update(plaintext);
System.out.println("Signing using " + signer.getProvider().getName() +
" JCE provider");
byte[] signature = signer.sign();
// Invalidate
System.out.println("Invalidating signature ...");
byte[] badSignature = new byte[signature.length + 5];
System.arraycopy(signature, 0, badSignature, 0, signature.length);
badSignature[signature.length] = 0x01;
badSignature[signature.length + 1] = 0x01;
badSignature[signature.length + 2] = 0x01;
badSignature[signature.length + 3] = 0x01;
badSignature[signature.length + 4] = 0x01;
// Verify
Signature verifier =
provider == null ?
Signature.getInstance(signatureAlgorithm) :
Signature.getInstance(signatureAlgorithm, provider);
verifier.initVerify(keypair.getPublic());
verifier.update(plaintext);
System.out.println("Verifying using " +
verifier.getProvider().getName() + " JCE provider");
try {
System.out.println("Valid? " + verifier.verify(badSignature));
throw new Exception(
"ERROR: expected a SignatureException but none was thrown");
} catch (SignatureException e) {
System.out.println("OK: caught expected exception: " + e);
}
System.out.println();
}