java.security.Signature Java Examples

The following examples show how to use java.security.Signature. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Nacl.java    From api with Apache License 2.0 6 votes vote down vote up
/**
 * Signs a message using the supplied secretKey
 * Returns message signature of `message`, using the `secretKey`.
 * **example**  
 * 
 * ```java
 * naclSign([...], [...]); // => [...]
 * ```
 */
//export default function naclSign (message: Uint8Array, { publicKey, secretKey }: Partial<Keypair>): Uint8Array {
//    assert(secretKey, 'Expected valid secretKey');
//
//    return isReady()
//            ? ed25519Sign(publicKey as Uint8Array, (secretKey as Uint8Array).subarray(0, 32), message)
//: nacl.sign.detached(message, secretKey as Uint8Array);
//}
public static byte[] naclSign(byte[] message, final Types.Keypair keypair) {
    try {
        EdDSAParameterSpec spec = EdDSANamedCurveTable.getByName(EdDSANamedCurveTable.ED_25519);
        Signature sgr = new EdDSAEngine(MessageDigest.getInstance(spec.getHashAlgorithm()));

        EdDSAPrivateKeySpec edPrivateKey = new EdDSAPrivateKeySpec(spec, keypair.secretKey);
        PrivateKey privateKey = new EdDSAPrivateKey(edPrivateKey);
        sgr.initSign(privateKey);
        sgr.update(message);
        return sgr.sign();
    }
    catch (Exception e) {
        return null;
    }
}
 
Example #2
Source File: CodecUtil.java    From seed with Apache License 2.0 6 votes vote down vote up
/**
 * RSA算法使用私钥对数据生成数字签名
 * 注意签名算法SHA1WithRSA已被废弃,推荐使用SHA256WithRSA
 * @param data 待签名的明文字符串
 * @param key  RSA私钥字符串
 * @return RSA私钥签名后的经过Base64编码的字符串
 */
public static String buildRSASignByPrivateKey(String data, String key){
    try{
        //通过PKCS#8编码的Key指令获得私钥对象
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(key));
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        //sign
        Signature signature = Signature.getInstance(ALGORITHM_RSA_SIGN);
        signature.initSign(privateKey);
        signature.update(data.getBytes(SeedConstants.DEFAULT_CHARSET));
        return Base64.encodeBase64URLSafeString(signature.sign());
    }catch(Exception e){
        throw new RuntimeException("签名字符串[" + data + "]时遇到异常", e);
    }
}
 
Example #3
Source File: BalanzaComprobacionv11.java    From factura-electronica with Apache License 2.0 6 votes vote down vote up
public void verificar() throws Exception {
	String certStr = document.getCertificado();
	Base64 b64 = new Base64();
	byte[] cbs = b64.decode(certStr);

	X509Certificate cert = KeyLoaderFactory.createInstance(KeyLoaderEnumeration.PUBLIC_KEY_LOADER,new ByteArrayInputStream(cbs)).getKey();

	String sigStr = document.getSello();
	byte[] signature = b64.decode(sigStr); 
	byte[] bytes = getOriginalBytes();
	Signature sig = Signature.getInstance("SHA1withRSA");
	sig.initVerify(cert);
	sig.update(bytes);
	boolean bool = sig.verify(signature);
	if (!bool) {
		throw new Exception("Invalid signature");
	}
}
 
Example #4
Source File: X509CertificateObject.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
private void checkSignature(
    PublicKey key, 
    Signature signature) 
    throws CertificateException, NoSuchAlgorithmException, 
        SignatureException, InvalidKeyException
{
    if (!isAlgIdEqual(c.getSignatureAlgorithm(), c.getTBSCertificate().getSignature()))
    {
        throw new CertificateException("signature algorithm in TBS cert not same as outer cert");
    }

    ASN1Encodable params = c.getSignatureAlgorithm().getParameters();

    // TODO This should go after the initVerify?
    X509SignatureUtil.setSignatureParameters(signature, params);

    signature.initVerify(key);

    signature.update(this.getTBSCertificate());

    if (!signature.verify(this.getSignature()))
    {
        throw new SignatureException("certificate does not verify with supplied key");
    }
}
 
Example #5
Source File: RSA.java    From aes-rsa-java with Apache License 2.0 6 votes vote down vote up
public static String sign(String content, String privateKey) {
	String charset = ConfigureEncryptAndDecrypt.CHAR_ENCODING;
	try {
		PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
				Base64.decodeBase64(privateKey.getBytes()));
		KeyFactory keyf = KeyFactory.getInstance("RSA");
		PrivateKey priKey = keyf.generatePrivate(priPKCS8);

		Signature signature = Signature.getInstance("SHA256WithRSA");

		signature.initSign(priKey);
		signature.update(content.getBytes(charset));

		byte[] signed = signature.sign();

		return new String(Base64.encodeBase64(signed));
	} catch (Exception e) {

	}

	return null;
}
 
Example #6
Source File: QaP11Actions.java    From xipki with Apache License 2.0 6 votes vote down vote up
@Override
protected Object execute1(PrivateKey key, Certificate cert) throws Exception {
  PublicKey pubKey = cert.getPublicKey();

  String sigAlgo = getSignatureAlgo(pubKey);
  println("signature algorithm: " + sigAlgo);
  Signature sig = Signature.getInstance(sigAlgo);
  sig.initSign(key);

  byte[] data = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  sig.update(data);
  byte[] signature = sig.sign(); // CHECKSTYLE:SKIP
  println("signature created successfully");

  Signature ver = Signature.getInstance(sigAlgo, "BC");
  ver.initVerify(pubKey);
  ver.update(data);
  boolean valid = ver.verify(signature);
  println("signature valid: " + valid);
  return null;
}
 
Example #7
Source File: CryptoUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static Signature getSignature(PrivateKey key, String signAlgo, SecureRandom random,
                              AlgorithmParameterSpec params) {
    try {
        Signature s = Signature.getInstance(signAlgo);
        if (random == null) {
            s.initSign(key);
        } else {
            s.initSign(key, random);
        }
        if (params != null) {
            s.setParameter(params);
        }
        return s;
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}
 
Example #8
Source File: ReconSignature.java    From swim with Apache License 2.0 6 votes vote down vote up
public static ReconSignature signRsa(Signature signature, PrivateKey privateKey,
                                     Value payload, Value protectedHeader,
                                     Value unprotectedHeader) {
  final Output<Data> output = Data.output();
  Recon.structureWriter().writeValue(payload, output);
  Recon.structureWriter().writeAttr(Text.from("protected"), protectedHeader, output);
  final Data signingInput = output.bind();

  try {
    signature.initSign(privateKey);
    signature.update(signingInput.asByteBuffer());
    final Data hash = Data.wrap(signature.sign());
    final Value signatureHeader;
    if (unprotectedHeader.isDefined()) {
      signatureHeader = unprotectedHeader.concat(Slot.of("hash", hash));
    } else {
      signatureHeader = Record.of(Slot.of("hash", hash));
    }
    return new ReconSignature(payload, protectedHeader, signatureHeader);
  } catch (GeneralSecurityException cause) {
    throw new RuntimeException(cause);
  }
}
 
Example #9
Source File: BouncyCryptography.java    From Jabit with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] getSignature(byte[] data, PrivateKey privateKey) {
    try {
        ECParameterSpec spec = new ECParameterSpec(
            EC_CURVE_PARAMETERS.getCurve(),
            EC_CURVE_PARAMETERS.getG(),
            EC_CURVE_PARAMETERS.getN(),
            EC_CURVE_PARAMETERS.getH(),
            EC_CURVE_PARAMETERS.getSeed()
        );

        BigInteger d = keyToBigInt(privateKey.getPrivateSigningKey());
        KeySpec keySpec = new ECPrivateKeySpec(d, spec);
        java.security.PrivateKey privKey = KeyFactory.getInstance(ALGORITHM_ECDSA, provider)
            .generatePrivate(keySpec);

        Signature sig = Signature.getInstance(ALGORITHM_ECDSA, provider);
        sig.initSign(privKey);
        sig.update(data);
        return sig.sign();
    } catch (GeneralSecurityException e) {
        throw new ApplicationException(e);
    }
}
 
Example #10
Source File: KeyStoreHelper.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
/**
 * Checks the given byte[] data against the signature, using the
 * public key with which this helper was initialised and the algorithm
 * MD5 with RSA.
 *
 * @param data the original data that was signed
 * @param signature the provided signature
 *
 * @return true in case the signature matches, false otherwise.
 *
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
public boolean checkDataWithPublicKey(final String publicKeyAlias,
                                      final byte[] data,
                                      final byte[] signature) throws KeyStoreException,
                                                             NoSuchAlgorithmException,
                                                             InvalidKeyException,
                                                             SignatureException {
    if( pubKeyStore == null ) {
        throw new RuntimeException( "Key store with public key not configured. Please configure it properly before using signed serialization." );
    }
    Certificate cert = pubKeyStore.getCertificate( publicKeyAlias );
    if( cert == null ) {
        throw new RuntimeException( "Public certificate for key '"+publicKeyAlias+"' not found in the configured key store. Impossible to deserialize the object." );
    }
    Signature sig = Signature.getInstance( "MD5withRSA" );
    sig.initVerify( cert.getPublicKey() );
    sig.update( data );
    return sig.verify( signature );
}
 
Example #11
Source File: SignatureECDSA.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/** @inheritDoc */
protected void engineInitVerify(Key publicKey) throws XMLSignatureException {

    if (!(publicKey instanceof PublicKey)) {
        String supplied = publicKey.getClass().getName();
        String needed = PublicKey.class.getName();
        Object exArgs[] = { supplied, needed };

        throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
    }

    try {
        this.signatureAlgorithm.initVerify((PublicKey) publicKey);
    } catch (InvalidKeyException ex) {
        // reinstantiate Signature object to work around bug in JDK
        // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
        Signature sig = this.signatureAlgorithm;
        try {
            this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
        } catch (Exception e) {
            // this shouldn't occur, but if it does, restore previous
            // Signature
            if (log.isLoggable(java.util.logging.Level.FINE)) {
                log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
            }
            this.signatureAlgorithm = sig;
        }
        throw new XMLSignatureException("empty", ex);
    }
}
 
Example #12
Source File: NetscapeCertRequest.java    From ripple-lib-java with ISC License 5 votes vote down vote up
public void sign(PrivateKey priv_key, SecureRandom rand)
        throws NoSuchAlgorithmException, InvalidKeyException,
        SignatureException, NoSuchProviderException,
        InvalidKeySpecException
{
    Signature sig = Signature.getInstance(sigAlg.getAlgorithm().getId(),
            "BC");

    if (rand != null)
    {
        sig.initSign(priv_key, rand);
    }
    else
    {
        sig.initSign(priv_key);
    }

    ASN1EncodableVector pkac = new ASN1EncodableVector();

    pkac.add(getKeySpec());
    pkac.add(new DERIA5String(challenge));

    try
    {
        sig.update(new DERSequence(pkac).getEncoded(ASN1Encoding.DER));
    }
    catch (IOException ioe)
    {
        throw new SignatureException(ioe.getMessage());
    }

    sigBits = sig.sign();
}
 
Example #13
Source File: SignatureTestable.java    From ECTester with MIT License 5 votes vote down vote up
public SignatureTestable(Signature sig, ECPrivateKey signKey, ECPublicKey verifyKey, byte[] data) {
    this.sig = sig;
    this.signKey = signKey;
    this.verifyKey = verifyKey;
    this.data = data;
    if (data == null) {
        SecureRandom random = new SecureRandom();
        this.data = new byte[64];
        random.nextBytes(this.data);
    }
}
 
Example #14
Source File: FingerprintActivity.java    From AndroidSamples with Apache License 2.0 5 votes vote down vote up
@Nullable
private Signature initSignature(String keyName) throws Exception {
    KeyPair keyPair = getKeyPair(keyName);

    if (keyPair != null) {
        Signature signature = Signature.getInstance("SHA256withECDSA");
        signature.initSign(keyPair.getPrivate());
        return signature;
    }
    return null;
}
 
Example #15
Source File: JWSFactory.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
public <T extends Serializable> JWS<T> create(JWSHeader header, T payload, PrivateKey privateKey) {
    String headerString = Base64UrlUtil.encodeToString(jsonConverter.writeValueAsString(header).getBytes(StandardCharsets.UTF_8));
    String payloadString = Base64UrlUtil.encodeToString(jsonConverter.writeValueAsString(payload).getBytes(StandardCharsets.UTF_8));
    String signedData = headerString + "." + payloadString;
    Signature signatureObj = SignatureUtil.createSignature(header.getAlg().getJcaName());
    try {
        signatureObj.initSign(privateKey);
        signatureObj.update(signedData.getBytes());
        byte[] derSignature = signatureObj.sign();
        byte[] jwsSignature = JWSSignatureUtil.convertDerSignatureToJwsSignature(derSignature);
        return new JWS<>(header, headerString, payload, payloadString, jwsSignature);
    } catch (InvalidKeyException | SignatureException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #16
Source File: RSAUtil.java    From anyline with Apache License 2.0 5 votes vote down vote up
/** 
 * 用私钥对信息生成数字签名 
 * @param data 已加密数据 
 * @param privateKey 私钥(BASE64编码) 
 *  
 * @return return
 * @throws Exception Exception
 */ 
public static String sign(byte[] data, String privateKey) throws Exception { 
    PrivateKey privateK = getPrivateKey(privateKey); 
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); 
    signature.initSign(privateK); 
    signature.update(data); 
    return Base64Util.encode(signature.sign()); 
     
		 
}
 
Example #17
Source File: EncodingXMLTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testDSA2048() throws Exception {
	KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
	gen.initialize(2048); // works with 4096 too but it takes lot of time
	KeyPair pair = gen.generateKeyPair();

	Signature s = Signature.getInstance("SHA256withDSA");
	s.initSign(pair.getPrivate());
	s.update(HELLO_WORLD.getBytes());
	byte[] signatureValue = s.sign();
	assertTrue(Utils.isArrayNotEmpty(DSSSignatureUtils.convertToXmlDSig(EncryptionAlgorithm.DSA, signatureValue)));
}
 
Example #18
Source File: CryptoServiceImpl.java    From paymentgateway with GNU General Public License v3.0 5 votes vote down vote up
protected String sign(PrivateKey key, String plainData) throws MipsException {
	try {
		Signature instance = Signature.getInstance("SHA1withRSA");
		instance.initSign(key);
		instance.update(plainData.getBytes("UTF-8"));
		byte[] signature = instance.sign();
		return Base64.encodeBase64String(signature);
	}
	catch (Exception e) {
		throw new MipsException(RespCode.INTERNAL_ERROR, "sign failed: ", e);
	}
}
 
Example #19
Source File: SigningUtil.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
private static boolean verifyMessageSignature(PublicKey publicKey,
                                              String messageString, byte[] signature)
        throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {
    Signature sign = Signature.getInstance("SHA256withRSA/PSS", new BouncyCastleProvider());
    byte[] message = messageString.getBytes();
    sign.initVerify(publicKey);
    sign.update(message);
    return sign.verify(signature);
}
 
Example #20
Source File: VerifyRangeCheckOverflow.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
    keyPairGenerator.initialize(1024);
    KeyPair keys = keyPairGenerator.generateKeyPair();
    PublicKey publicKey = keys.getPublic();
    byte[] sigBytes = new byte[100];

    Signature signature = Signature.getInstance("SHA1withDSA");
    signature.initVerify(publicKey);
    try {
        signature.verify(sigBytes, Integer.MAX_VALUE, 1);
    } catch (IllegalArgumentException ex) {
        // Expected
    }
}
 
Example #21
Source File: SignatureTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private Signature getTestSignature() throws NoSuchAlgorithmException {
    Provider provider = new MyProvider("TestProvider", 1.0, "Test Provider", "Signature.ABC", MySignature.class.getName());
    Security.insertProviderAt(provider, 1);

    try {
        return Signature.getInstance("ABC");
    }
    finally {
       Security.removeProvider("TestProvider");
    }

}
 
Example #22
Source File: GXPkcs10.java    From gurux.dlms.java with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sign
 * 
 * @param kp
 *            Public and Private key.
 * @param hashAlgorithm
 *            Used algorithm for signing.
 */
@SuppressWarnings("squid:S00112")
public void sign(final KeyPair kp, final HashAlgorithm hashAlgorithm) {
    byte[] data = GXAsn1Converter.toByteArray(getdata());
    try {
        Signature instance =
                Signature.getInstance(hashAlgorithm.toString());
        instance.initSign(kp.getPrivate());
        instance.update(data);
        signatureAlgorithm = hashAlgorithm;
        signature = instance.sign();
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
    }
}
 
Example #23
Source File: NonStandardNames.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] data = "Hello".getBytes();
        X500Name n = new X500Name("cn=Me");

        CertAndKeyGen cakg = new CertAndKeyGen("RSA", "SHA256withRSA");
        cakg.generate(1024);
        X509Certificate cert = cakg.getSelfCertificate(n, 1000);

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        PKCS9Attributes authed = new PKCS9Attributes(new PKCS9Attribute[]{
            new PKCS9Attribute(PKCS9Attribute.CONTENT_TYPE_OID, ContentInfo.DATA_OID),
            new PKCS9Attribute(PKCS9Attribute.MESSAGE_DIGEST_OID, md.digest(data)),
        });

        Signature s = Signature.getInstance("SHA256withRSA");
        s.initSign(cakg.getPrivateKey());
        s.update(authed.getDerEncoding());
        byte[] sig = s.sign();

        SignerInfo signerInfo = new SignerInfo(
                n,
                cert.getSerialNumber(),
                AlgorithmId.get("SHA-256"),
                authed,
                AlgorithmId.get("SHA256withRSA"),
                sig,
                null
                );

        PKCS7 pkcs7 = new PKCS7(
                new AlgorithmId[] {signerInfo.getDigestAlgorithmId()},
                new ContentInfo(data),
                new X509Certificate[] {cert},
                new SignerInfo[] {signerInfo});

        if (pkcs7.verify(signerInfo, data) == null) {
            throw new Exception("Not verified");
        }
    }
 
Example #24
Source File: RSAUtils.java    From rhizobia_J with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @Description: 验签
 * @Param: sign 数字签名
 * @Param: oriData 原始数据
 * @return: boolean 是否通过验签
 */
public boolean verify(byte[] sign, String oriData) throws Exception {
    byte[] data = oriData.getBytes();
    // 实例化Signature
    Signature signature = Signature.getInstance(signatureAlgorithm);
    // 初始化Signature
    signature.initVerify(publicKey);
    // 更新
    signature.update(data);

    return signature.verify(sign);
}
 
Example #25
Source File: SignatureDSA.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @inheritDoc
 */
protected void engineInitVerify(Key publicKey) throws XMLSignatureException {
    if (!(publicKey instanceof PublicKey)) {
        String supplied = publicKey.getClass().getName();
        String needed = PublicKey.class.getName();
        Object exArgs[] = { supplied, needed };

        throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs);
    }

    try {
        this.signatureAlgorithm.initVerify((PublicKey) publicKey);
    } catch (InvalidKeyException ex) {
        // reinstantiate Signature object to work around bug in JDK
        // see: http://bugs.java.com/view_bug.do?bug_id=4953555
        Signature sig = this.signatureAlgorithm;
        try {
            this.signatureAlgorithm = Signature.getInstance(signatureAlgorithm.getAlgorithm());
        } catch (Exception e) {
            // this shouldn't occur, but if it does, restore previous
            // Signature
            if (log.isLoggable(java.util.logging.Level.FINE)) {
                log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Signature:" + e);
            }
            this.signatureAlgorithm = sig;
        }
        throw new XMLSignatureException("empty", ex);
    }
    size = ((DSAKey)publicKey).getParams().getQ().bitLength();
}
 
Example #26
Source File: RSASigner.java    From fusionauth-jwt with Apache License 2.0 5 votes vote down vote up
public byte[] sign(String message) {
  Objects.requireNonNull(message);

  try {
    Signature signature = cryptoProvider.getSignatureInstance(algorithm.getName());
    signature.initSign(privateKey);
    signature.update(message.getBytes(StandardCharsets.UTF_8));
    return signature.sign();
  } catch (InvalidKeyException | NoSuchAlgorithmException | SignatureException e) {
    throw new JWTSigningException("An unexpected exception occurred when attempting to sign the JWT", e);
  }
}
 
Example #27
Source File: Graph.java    From SPADE with GNU General Public License v3.0 5 votes vote down vote up
public boolean addSignature(String nonce){
	try{
		SecureRandom secureRandom = new SecureRandom();
		secureRandom.nextInt();
		Signature signature = Signature.getInstance("SHA256withRSA");
		PrivateKey privateKey = Kernel.getServerPrivateKey("serverprivate");
		if(privateKey == null){
			return false;
		}
		signature.initSign(privateKey, secureRandom);

		for(AbstractVertex vertex : vertexSet()){
			signature.update(vertex.bigHashCodeBytes());
		}
		for(AbstractEdge edge : edgeSet()){
			signature.update(edge.bigHashCodeBytes());
		}
		if(getQueryString() != null){
			signature.update(getQueryString().getBytes("UTF-8"));
		}
		if(nonce != null){
			signature.update(nonce.getBytes("UTF-8"));
		}

		byte[] digitalSignature = signature.sign();
		setSignature(digitalSignature);

		return true;
	}catch(Exception ex){
		logger.log(Level.SEVERE, "Error signing the result graph!", ex);
	}
	return false;
}
 
Example #28
Source File: NonStandardNames.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] data = "Hello".getBytes();
        X500Name n = new X500Name("cn=Me");

        CertAndKeyGen cakg = new CertAndKeyGen("RSA", "SHA256withRSA");
        cakg.generate(1024);
        X509Certificate cert = cakg.getSelfCertificate(n, 1000);

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        PKCS9Attributes authed = new PKCS9Attributes(new PKCS9Attribute[]{
            new PKCS9Attribute(PKCS9Attribute.CONTENT_TYPE_OID, ContentInfo.DATA_OID),
            new PKCS9Attribute(PKCS9Attribute.MESSAGE_DIGEST_OID, md.digest(data)),
        });

        Signature s = Signature.getInstance("SHA256withRSA");
        s.initSign(cakg.getPrivateKey());
        s.update(authed.getDerEncoding());
        byte[] sig = s.sign();

        SignerInfo signerInfo = new SignerInfo(
                n,
                cert.getSerialNumber(),
                AlgorithmId.get("SHA-256"),
                authed,
                AlgorithmId.get("SHA256withRSA"),
                sig,
                null
                );

        PKCS7 pkcs7 = new PKCS7(
                new AlgorithmId[] {signerInfo.getDigestAlgorithmId()},
                new ContentInfo(data),
                new X509Certificate[] {cert},
                new SignerInfo[] {signerInfo});

        if (pkcs7.verify(signerInfo, data) == null) {
            throw new Exception("Not verified");
        }
    }
 
Example #29
Source File: BasicSamlTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void testSpecialCharsInRelayState(String encodedRelayState) throws Exception {
    AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(SAML_CLIENT_ID_SALES_POST_SIG, SAML_ASSERTION_CONSUMER_URL_SALES_POST_SIG, getAuthServerSamlEndpoint(REALM_NAME));

    Document doc = SAML2Request.convert(loginRep);
    URI redirect = Binding.REDIRECT.createSamlUnsignedRequest(getAuthServerSamlEndpoint(REALM_NAME), null, doc).getURI();
    String query = redirect.getRawQuery();
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RSA_SHA256;

    // now add the relayState
    String relayStatePart = encodedRelayState == null
      ? ""
      : ("&" + GeneralConstants.RELAY_STATE + "=" + encodedRelayState);
    String sigAlgPart = "&" + GeneralConstants.SAML_SIG_ALG_REQUEST_KEY + "=" + Encode.encodeQueryParamAsIs(signatureAlgorithm.getXmlSignatureMethod());

    Signature signature = signatureAlgorithm.createSignature();
    byte[] sig;

    signature.initSign(KeyUtils.privateKeyFromString(SAML_CLIENT_SALES_POST_SIG_PRIVATE_KEY));
    signature.update(query.getBytes(GeneralConstants.SAML_CHARSET));
    signature.update(relayStatePart.getBytes(GeneralConstants.SAML_CHARSET));
    signature.update(sigAlgPart.getBytes(GeneralConstants.SAML_CHARSET));
    sig = signature.sign();

    String encodedSig = RedirectBindingUtil.base64Encode(sig);
    String sigPart = "&" + GeneralConstants.SAML_SIGNATURE_REQUEST_KEY + "=" + Encode.encodeQueryParamAsIs(encodedSig);

    new SamlClientBuilder()
      .navigateTo(redirect.toString() + relayStatePart + sigAlgPart + sigPart)
      .assertResponse(statusCodeIsHC(Status.OK))
      .execute();
}
 
Example #30
Source File: SolarisShortDSA.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
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);
}