<commit_before>
package com.microsoft.aad.adal.test;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Enumeration;

import javax.security.auth.x500.X500Principal;

import android.content.Context;
import android.util.Base64;
import android.util.Log;

import com.microsoft.aad.adal.AuthenticationConstants;

public class JwsBuilderTests extends AndroidTestHelper {

    private static final String TEST_CERT_ALIAS = "My Key Chain";

    private static final String PKCS12_PASS = "<PASSWORD>";

    static final String TAG = "JwsBuilderTests";

    static final String PKCS12_FILENAME = "keychain.p12";

    static final String JWS_ALGORITHM = "SHA256withRSA";

    public void testGenerateSignedJWT_positive() throws ClassNotFoundException,
            InstantiationException, IllegalAccessException, IllegalArgumentException,
            InvocationTargetException, NoSuchMethodException, UnrecoverableKeyException,
            KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
            InvalidKeyException, SignatureException {
        Object jwsBuilder = getInstance();
        Method m = ReflectionUtils.getTestMethod(jwsBuilder, "generateSignedJWT", String.class,
                String.class, RSAPrivateKey.class, RSAPublicKey.class, String.class);
        KeyStore keystore = loadTestCertificate();
        Key key = keystore.getKey(TEST_CERT_ALIAS, PKCS12_PASS.toCharArray());
        RSAPrivateKey privKey = (RSAPrivateKey)key;
        Certificate cert = keystore.getCertificate(TEST_CERT_ALIAS);
        RSAPublicKey publicKey = (RSAPublicKey)cert.getPublicKey();

        String jws = (String)m.invoke(jwsBuilder, "nonce", "https://someurl", privKey, publicKey,
                getThumbPrintFromCert((X509Certificate)cert));

        verify(jws, publicKey, "nonce", "https://someurl");
    }

    public void testGenerateSignedJWT_negative() throws IllegalArgumentException,
            ClassNotFoundException, NoSuchMethodException, InstantiationException,
            IllegalAccessException, InvocationTargetException {
        Object jwsBuilder = getInstance();
        Method m = ReflectionUtils.getTestMethod(jwsBuilder, "generateSignedJWT", String.class,
                String.class, RSAPrivateKey.class, RSAPublicKey.class, String.class);

        try {
            String jws = (String)m.invoke(jwsBuilder, null, "https://someurl", null, null, null);
        } catch (Exception ex) {
            assertTrue("Argument excetpion", ex.getCause().getMessage().contains("nonce"));
        }
        
        try {
            String jws = (String)m.invoke(jwsBuilder, "nonce", null, null, null, null);
        } catch (Exception ex) {
            assertTrue("Argument excetpion", ex.getCause().getMessage().contains("submitUrl"));
        }
        
        try {
            String jws = (String)m.invoke(jwsBuilder, "nonce", "url", null, null, null);
        } catch (Exception ex) {
            assertTrue("Argument excetpion", ex.getCause().getMessage().contains("privateKey"));
        }
    }

    private void verify(final String jws, RSAPublicKey publicKey, final String nonce,
            final String submiturl) throws NoSuchAlgorithmException, InvalidKeyException,
            UnsupportedEncodingException, SignatureException {
        int dot1 = jws.indexOf(".");
        assertFalse("Serialization error", dot1 == -1);
        int dot2 = jws.indexOf(".", dot1 + 1);
        assertFalse("Serialization error", dot2 == -1);

        String header = jws.substring(0, dot1);
        String body = jws.substring(dot1 + 1, dot2);
        String signature = jws.substring(dot2 + 1);
        byte[] signatureBytes = Base64.decode(signature, Base64.NO_WRAP | Base64.URL_SAFE);
        byte[] signInput = (header + "." + body).getBytes(AuthenticationConstants.ENCODING_UTF8);
        Signature verifier = Signature.getInstance(JWS_ALGORITHM);
        verifier.initVerify(publicKey);
        verifier.update(signInput);
        assertTrue("Signature verify", verifier.verify(signatureBytes));
<commit_msg>negative tests for jws message<commit_after>
package com.microsoft.aad.adal.test;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Enumeration;

import javax.security.auth.x500.X500Principal;

import android.content.Context;
import android.util.Base64;
import android.util.Log;

import com.microsoft.aad.adal.AuthenticationConstants;

public class JwsBuilderTests extends AndroidTestHelper {

    private static final String TEST_CERT_ALIAS = "My Key Chain";

    private static final String PKCS12_PASS = "<PASSWORD>it";

    static final String TAG = "JwsBuilderTests";

    static final String PKCS12_FILENAME = "keychain.p12";

    static final String JWS_ALGORITHM = "SHA256withRSA";

    public void testGenerateSignedJWT_positive() throws ClassNotFoundException,
            InstantiationException, IllegalAccessException, IllegalArgumentException,
            InvocationTargetException, NoSuchMethodException, UnrecoverableKeyException,
            KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
            InvalidKeyException, SignatureException {
        KeyStore keystore = loadTestCertificate();
        Key key = keystore.getKey(TEST_CERT_ALIAS, PKCS12_PASS.toCharArray());
        RSAPrivateKey privKey = (RSAPrivateKey)key;
        Certificate cert = keystore.getCertificate(TEST_CERT_ALIAS);
        RSAPublicKey publicKey = (RSAPublicKey)cert.getPublicKey();

        testSignedJWT(true, "nonce", "https://someurl", privKey, publicKey,
                getThumbPrintFromCert((X509Certificate)cert));
    }

    public void testGenerateSignedJWT_negative() throws IllegalArgumentException,
            ClassNotFoundException, NoSuchMethodException, InstantiationException,
            IllegalAccessException, InvocationTargetException {
        Object jwsBuilder = getInstance();
        Method m = ReflectionUtils.getTestMethod(jwsBuilder, "generateSignedJWT", String.class,
                String.class, RSAPrivateKey.class, RSAPublicKey.class, String.class);

        try {
            m.invoke(jwsBuilder, null, "https://someurl", null, null, null);
        } catch (Exception ex) {
            assertTrue("Argument excetpion", ex.getCause().getMessage().contains("nonce"));
        }

        try {
            m.invoke(jwsBuilder, "nonce", null, null, null, null);
        } catch (Exception ex) {
            assertTrue("Argument excetpion", ex.getCause().getMessage().contains("submitUrl"));
        }

        try {
            m.invoke(jwsBuilder, "nonce", "url", null, null, null);
        } catch (Exception ex) {
            assertTrue("Argument excetpion", ex.getCause().getMessage().contains("privateKey"));
        }
    }

    /**
     * send invalid public and private key
     * 
     * @throws SignatureException
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws ClassNotFoundException
     * @throws InvalidKeyException
     */
    public void testGenerateSignedJWT_KeyPair() throws InvalidKeyException, ClassNotFoundException,
            InstantiationException, IllegalAccessException, IllegalArgumentException,
            InvocationTargetException, NoSuchMethodException, NoSuchAlgorithmException,
            UnsupportedEncodingException, SignatureException {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024);
        KeyPair keyPair = keyGen.genKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey)keyGen.genKeyPair().getPrivate();

        testSignedJWT(false, "invalid key pairs", "https://someurl", privateKey, publicKey,
                "thumprint12323");
    }

    private void testSignedJWT(boolean validSignature, String nonce, String url,
            RSAPrivateKey privKey, RSAPublicKey publicKey, String thumbPrint)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException, NoSuchMethodException,
            InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException,
            SignatureException {
        Object jwsBuilder = getInstance();
        Method m = ReflectionUtils.getTestMethod(jwsBuilder, "generateSignedJWT", String.class,
                String.class, RSAPrivateKey.class, RSAPublicKey.class, String.class);
        String jws = (String)m.invoke(jwsBuilder, nonce, url, privKey, publicKey, thumbPrint);
        verify(validSignature, jws, publicKey, nonce, url);
    }

    private void verify(boolean validSignature, final String jws, RSAPublicKey publicKey,
            final String nonce, final String submiturl) throws NoSuchAlgorithmException,
            InvalidKeyException, UnsupportedEncodingException, SignatureException {
        int dot1 = jws.indexOf(".");
        assertFalse("Serialization error", dot1 == -1);
        int dot2 = jws.indexOf(".", dot1 + 1);
        assertFalse("Serialization error", dot2 == -1);

        String header = jws.substring(0, dot1);
        String body = jws.substring(dot1 + 1, dot2);
        String signature = jws.substring(dot2 + 1);
        byte[] signatureBytes = Base64.decode(signature, Base64.NO_WRAP | Base64.URL_SAFE);
        byte[] signInput = (header + "." + body).getBytes(AuthenticationConstants.ENCODING_UTF8);
        Signature verifier = Signature.getInstance(JWS_ALGORITHM);
        verifier.initVerify(publicKey);
        verifier.update(signInput);
        assertEquals("Signature verify", validSignature, verifier.verify(signatureBytes));

{'fraction_non_alphanumeric': 0.09378482640377196, 'fraction_numerical': 0.008829832833261895, 'mean_word_length': 3.8446843853820596, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 6, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7060548', 'n_tokens_mistral': 3197, 'n_tokens_neox': 3072, 'n_words': 662}