Example usage for java.security.interfaces RSAPublicKey getPublicExponent

List of usage examples for java.security.interfaces RSAPublicKey getPublicExponent

Introduction

In this page you can find the example usage for java.security.interfaces RSAPublicKey getPublicExponent.

Prototype

public BigInteger getPublicExponent();

Source Link

Document

Returns the public exponent.

Usage

From source file:com.verisignlabs.dnssec.cl.KeyInfoTool.java

public void execute() throws Exception {
    for (int i = 0; i < state.keynames.length; ++i) {
        String keyname = state.keynames[i];
        DnsKeyPair key = BINDKeyUtils.loadKey(keyname, null);
        DNSKEYRecord dnskey = key.getDNSKEYRecord();
        DnsKeyAlgorithm dnskeyalg = DnsKeyAlgorithm.getInstance();

        boolean isSEP = (dnskey.getFlags() & DNSKEYRecord.Flags.SEP_KEY) != 0;

        System.out.println(keyname + ":");
        System.out.println("Name: " + dnskey.getName());
        System.out.println("SEP: " + isSEP);

        System.out.println("Algorithm: " + dnskeyalg.algToString(dnskey.getAlgorithm()) + " ("
                + dnskey.getAlgorithm() + ")");
        System.out.println("ID: " + dnskey.getFootprint());
        System.out.println("KeyFileBase: " + BINDKeyUtils.keyFileBase(key));
        int basetype = dnskeyalg.baseType(dnskey.getAlgorithm());
        switch (basetype) {
        case DnsKeyAlgorithm.RSA: {
            RSAPublicKey pub = (RSAPublicKey) key.getPublic();
            System.out.println("RSA Public Exponent: " + pub.getPublicExponent());
            System.out.println("RSA Modulus: " + pub.getModulus());
            break;
        }//ww  w .j av a 2 s .  c om
        case DnsKeyAlgorithm.DSA: {
            DSAPublicKey pub = (DSAPublicKey) key.getPublic();
            System.out.println("DSA base (G): " + pub.getParams().getG());
            System.out.println("DSA prime (P): " + pub.getParams().getP());
            System.out.println("DSA subprime (Q): " + pub.getParams().getQ());
            System.out.println("DSA public (Y): " + pub.getY());
            break;
        }
        }
        if (state.keynames.length - i > 1) {
            System.out.println();
        }
    }
}

From source file:org.ejbca.util.keystore.KeyTools.java

/**
 * Gets the key AlgorithmParameterSpec of supported keys. Can be used to initialize a KeyPairGenerator to generate a key of equal type and size.
 * @param pk PublicKey used to derive the AlgorithmParameterSpec
 * @return null if key is unsupported or pk is null, otherwise a AlgorithmParameterSpec.
 *//* w  ww. j a va2s .c  om*/
public static AlgorithmParameterSpec getKeyGenSpec(final PublicKey pk) {
    if (pk == null) {
        return null;
    }
    AlgorithmParameterSpec ret = null;
    if (pk instanceof RSAPublicKey) {
        log.debug("getKeyGenSpec: RSA");
        final RSAPublicKey rpk = (RSAPublicKey) pk;
        ret = new RSAKeyGenParameterSpec(getKeyLength(pk), rpk.getPublicExponent());
    } else if (pk instanceof DSAPublicKey) {
        log.debug("getKeyGenSpec: DSA");
        final DSAPublicKey dpk = (DSAPublicKey) pk;
        final DSAParams params = dpk.getParams();
        ret = new DSAParameterSpec(params.getP(), params.getQ(), params.getG());
    } else if (pk instanceof ECPublicKey) {
        log.debug("getKeyGenSpec: ECPublicKey");
        final ECPublicKey ecpub = (ECPublicKey) pk;
        final java.security.spec.ECParameterSpec sunsp = ecpub.getParams();
        final EllipticCurve ecurve = new EllipticCurve(sunsp.getCurve().getField(), sunsp.getCurve().getA(),
                sunsp.getCurve().getB());
        //ECParameterSpec par = new ECNamedCurveSpec(null, sunsp.getCurve(), sunsp.getGenerator(), sunsp.getOrder(), BigInteger.valueOf(sunsp.getCofactor()));
        final ECParameterSpec params = new ECParameterSpec(ecurve, sunsp.getGenerator(), sunsp.getOrder(),
                sunsp.getCofactor());
        if (log.isDebugEnabled()) {
            log.debug("Fieldsize: " + params.getCurve().getField().getFieldSize());
            final EllipticCurve curve = params.getCurve();
            log.debug("CurveA: " + curve.getA().toString(16));
            log.debug("CurveB: " + curve.getB().toString(16));
            log.debug("CurveSeed: " + curve.getSeed());
            final ECFieldFp field = (ECFieldFp) curve.getField();
            log.debug("CurveSfield: " + field.getP().toString(16));
            final ECPoint p = params.getGenerator();
            log.debug("Generator: " + p.getAffineX().toString(16) + ", " + p.getAffineY().toString(16));
            log.debug("Order: " + params.getOrder().toString(16));
            log.debug("CoFactor: " + params.getCofactor());
        }
        ret = params;
    } else if (pk instanceof JCEECPublicKey) {
        log.debug("getKeyGenSpec: JCEECPublicKey");
        final JCEECPublicKey ecpub = (JCEECPublicKey) pk;
        final org.bouncycastle.jce.spec.ECParameterSpec bcsp = ecpub.getParameters();
        final ECCurve curve = bcsp.getCurve();
        //TODO: this probably does not work for key generation with the Sun PKCS#11 provider. Maybe seed needs to be set to null as above? Or something else, the BC curve is it the same?
        final ECParameterSpec params = new ECNamedCurveSpec(null, curve, bcsp.getG(), bcsp.getN(), bcsp.getH());
        ret = params;
        //EllipticCurve ecc = new EllipticCurve(curve.)
        //ECParameterSpec sp = new ECParameterSpec(, bcsp.getG(), bcsp.getN(), bcsp.getH().intValue());
    }
    return ret;
}

From source file:net.shopxx.controller.admin.LoginController.java

@RequestMapping
public String index(HttpServletRequest request, ModelMap model) {
    String loginToken = WebUtils.getCookie(request, Admin.LOGIN_TOKEN_COOKIE_NAME);
    if (!StringUtils.equalsIgnoreCase(loginToken, adminService.getLoginToken())) {
        return "redirect:/";
    }/*from w ww  .  j  a v a  2  s  . c o  m*/
    if (adminService.isAuthenticated()) {
        return "redirect:common/main.jhtml";
    }
    Message failureMessage = null;
    String loginFailure = (String) request
            .getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
    if (StringUtils.isNotEmpty(loginFailure)) {
        if (loginFailure.equals("net.shopxx.exception.IncorrectCaptchaException")) {
            failureMessage = Message.error("admin.captcha.invalid");
        } else if (loginFailure.equals("org.apache.shiro.authc.UnknownAccountException")) {
            failureMessage = Message.error("admin.login.unknownAccount");
        } else if (loginFailure.equals("org.apache.shiro.authc.DisabledAccountException")) {
            failureMessage = Message.error("admin.login.disabledAccount");
        } else if (loginFailure.equals("org.apache.shiro.authc.LockedAccountException")) {
            failureMessage = Message.error("admin.login.lockedAccount");
        } else if (loginFailure.equals("org.apache.shiro.authc.IncorrectCredentialsException")) {
            Setting setting = SystemUtils.getSetting();
            if (ArrayUtils.contains(setting.getAccountLockTypes(), Setting.AccountLockType.admin)) {
                failureMessage = Message.error("admin.login.accountLockCount", setting.getAccountLockCount());
            } else {
                failureMessage = Message.error("admin.login.incorrectCredentials");
            }
        } else if (loginFailure.equals("net.shopxx.exception.IncorrectLicenseException")) {
            failureMessage = Message.error("admin.login.incorrectLicense");
        } else if (loginFailure.equals("org.apache.shiro.authc.AuthenticationException")) {
            failureMessage = Message.error("admin.login.authentication");
        }
    }
    RSAPublicKey publicKey = rsaService.generateKey(request);
    model.addAttribute("modulus", Base64.encodeBase64String(publicKey.getModulus().toByteArray()));
    model.addAttribute("exponent", Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray()));
    model.addAttribute("captchaId", UUID.randomUUID().toString());
    model.addAttribute("failureMessage", failureMessage);
    return "/admin/login/index";
}

From source file:org.mitre.openid.connect.view.JwkKeyListView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {

        public boolean shouldSkipField(FieldAttributes f) {

            return false;
        }//www.  jav  a  2s.  c  o m

        public boolean shouldSkipClass(Class<?> clazz) {
            // skip the JPA binding wrapper
            if (clazz.equals(BeanPropertyBindingResult.class)) {
                return true;
            }
            return false;
        }

    }).create();

    response.setContentType("application/json");

    Writer out = response.getWriter();

    //BiMap<String, PublicKey> keyMap = (BiMap<String, PublicKey>) model.get("keys");
    Map<String, JwtSigner> signers = (Map<String, JwtSigner>) model.get("signers");

    JsonObject obj = new JsonObject();
    JsonArray keys = new JsonArray();
    obj.add("keys", keys);

    for (String keyId : signers.keySet()) {

        JwtSigner src = signers.get(keyId);

        if (src instanceof RsaSigner) {

            RsaSigner rsaSigner = (RsaSigner) src;

            RSAPublicKey rsa = (RSAPublicKey) rsaSigner.getPublicKey(); // we're sure this is an RSAPublicKey b/c this is an RsaSigner

            BigInteger mod = rsa.getModulus();
            BigInteger exp = rsa.getPublicExponent();

            String m64 = Base64.encodeBase64URLSafeString(mod.toByteArray());
            String e64 = Base64.encodeBase64URLSafeString(exp.toByteArray());

            JsonObject o = new JsonObject();

            o.addProperty("use", "sig"); // since we don't do encryption yet
            o.addProperty("alg", "RSA"); //rsaSigner.getAlgorithm()); // we know this is RSA
            o.addProperty("mod", m64);
            o.addProperty("exp", e64);
            o.addProperty("kid", keyId);

            keys.add(o);
        } // TODO: deal with non-RSA key types
    }

    gson.toJson(obj, out);

}

From source file:be.e_contract.mycarenet.common.SessionKey.java

/**
 * Gives back the RSA public modulus./*from  ww  w.  jav a 2s . c  o m*/
 * 
 * @return
 */
public byte[] getExponent() {
    RSAPublicKey rsaPublicKey = getRSAPublicKey();
    return rsaPublicKey.getPublicExponent().toByteArray();
}

From source file:test.be.fedict.eid.applet.PKCS11Test.java

@Test
public void testPKCS1viaPKCS11() throws Exception {
    File tmpConfigFile = File.createTempFile("pkcs11-", "conf");
    tmpConfigFile.deleteOnExit();/*  w  w  w.jav  a  2 s .c o m*/
    PrintWriter configWriter = new PrintWriter(new FileOutputStream(tmpConfigFile), true);
    configWriter.println("name=SmartCard");
    configWriter.println("library=/usr/lib/libbeidpkcs11.so.0");
    configWriter.println("slotListIndex=2");

    SunPKCS11 provider = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    Security.addProvider(provider);
    KeyStore keyStore = KeyStore.getInstance("PKCS11", provider);
    keyStore.load(null, null);
    PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry("Authentication", null);
    PrivateKey privateKey = privateKeyEntry.getPrivateKey();
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(privateKey);
    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    X509Certificate certificate = (X509Certificate) privateKeyEntry.getCertificate();
    RSAPublicKey publicKey = (RSAPublicKey) certificate.getPublicKey();
    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger messageBigInteger = signatureValueBigInteger.modPow(publicKey.getPublicExponent(),
            publicKey.getModulus());
    LOG.debug("original message: " + new String(Hex.encodeHex(messageBigInteger.toByteArray())));

    // LOG.debug("ASN.1 signature: " + ASN1Dump.dumpAsString(obj)
}

From source file:test.unit.be.fedict.hsm.entity.KeyStoreSingletonBeanTest.java

@Test
public void testSignature() throws Exception {
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("test");
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();//from  ww  w. ja v a  2s  .  c o  m

    KeyStoreEntity keyStoreEntity = new KeyStoreEntity("test", KeyStoreType.PKCS12,
            KeyStoreSingletonBeanTest.class.getResource("/keystore.p12").toURI().getPath(), "secret");
    entityManager.persist(keyStoreEntity);

    KeyStoreSingletonBean keyStoreSingletonBean = new KeyStoreSingletonBean();

    Field entityManagerField = KeyStoreSingletonBean.class.getDeclaredField("entityManager");
    entityManagerField.setAccessible(true);
    entityManagerField.set(keyStoreSingletonBean, entityManager);

    KeyStoreLoaderBean keyStoreLoaderBean = new KeyStoreLoaderBean();
    Field keyStoreLoaderField = KeyStoreSingletonBean.class.getDeclaredField("keyStoreLoader");
    keyStoreLoaderField.setAccessible(true);
    keyStoreLoaderField.set(keyStoreSingletonBean, keyStoreLoaderBean);

    keyStoreSingletonBean.loadKeys();

    keyStoreSingletonBean.newKeyStore(keyStoreEntity.getId());

    byte[] toBeSigned = "hello world".getBytes();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    messageDigest.update(toBeSigned);
    byte[] digestValue = messageDigest.digest();
    LOG.debug("digest value: " + new String(Hex.encodeHex(digestValue)));
    byte[] signatureValue = keyStoreSingletonBean.sign(keyStoreEntity.getId(), "alias", "SHA-1", digestValue);

    assertNotNull(signatureValue);
    LOG.debug("signature size: " + signatureValue.length);

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(KeyStoreSingletonBeanTest.class.getResourceAsStream("/keystore.p12"), "secret".toCharArray());
    RSAPublicKey publicKey = (RSAPublicKey) keyStore.getCertificate("alias").getPublicKey();

    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger originalBigInteger = signatureValueBigInteger.modPow(publicKey.getPublicExponent(),
            publicKey.getModulus());
    LOG.debug("original message: " + new String(Hex.encodeHex(originalBigInteger.toByteArray())));

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initVerify(publicKey);
    signature.update(toBeSigned);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);
}

From source file:org.cloudfoundry.identity.uaa.oauth.token.TokenKeyEndpoint.java

/**
 * Get the verification key for the token signatures. The principal has to
 * be provided only if the key is secret
 * (shared not public).//  www .ja  v  a  2s .  c  o  m
 * 
 * @param principal the currently authenticated user if there is one
 * @return the key used to verify tokens
 */
@RequestMapping(value = "/token_key", method = RequestMethod.GET)
@ResponseBody
public Map<String, String> getKey(Principal principal) {
    if ((principal == null || principal instanceof AnonymousAuthenticationToken)
            && !signerProvider.isPublic()) {
        throw new AccessDeniedException("You need to authenticate to see a shared key");
    }
    Map<String, String> result = new LinkedHashMap<String, String>();
    result.put("alg", signerProvider.getSigner().algorithm());
    result.put("value", signerProvider.getVerifierKey());
    //new values per OpenID and JWK spec
    result.put("kty", signerProvider.getType());
    result.put("use", "sig");
    if (signerProvider.isPublic() && "RSA".equals(signerProvider.getType())) {
        SignatureVerifier verifier = signerProvider.getVerifier();
        if (verifier != null && verifier instanceof RsaVerifier) {
            RSAPublicKey rsaKey = extractRsaPublicKey((RsaVerifier) verifier);
            if (rsaKey != null) {
                String n = new String(Base64.encode(rsaKey.getModulus().toByteArray()));
                String e = new String(Base64.encode(rsaKey.getPublicExponent().toByteArray()));
                result.put("n", n);
                result.put("e", e);
            }
        }
    }
    return result;
}

From source file:com.lingxiang2014.controller.shop.CommonController.java

@RequestMapping(value = "/public_key", method = RequestMethod.GET)
public @ResponseBody Map<String, String> publicKey(HttpServletRequest request) {
    RSAPublicKey publicKey = rsaService.generateKey(request);
    Map<String, String> data = new HashMap<String, String>();
    data.put("modulus", Base64.encodeBase64String(publicKey.getModulus().toByteArray()));
    data.put("exponent", Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray()));
    return data;/*from   w  w  w .j a v  a 2s . co  m*/
}

From source file:com.microsoft.azure.management.TestContainerService.java

private String getSshKey() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(2048);/*from  w  ww .j  a  v a  2  s . c o  m*/
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(byteOs);
    dos.writeInt("ssh-rsa".getBytes().length);
    dos.write("ssh-rsa".getBytes());
    dos.writeInt(publicKey.getPublicExponent().toByteArray().length);
    dos.write(publicKey.getPublicExponent().toByteArray());
    dos.writeInt(publicKey.getModulus().toByteArray().length);
    dos.write(publicKey.getModulus().toByteArray());
    String publicKeyEncoded = new String(Base64.encodeBase64(byteOs.toByteArray()));
    return "ssh-rsa " + publicKeyEncoded + " ";
}