Example usage for java.security.interfaces RSAPublicKey getModulus

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

Introduction

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

Prototype

public BigInteger getModulus();

Source Link

Document

Returns the modulus.

Usage

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)./*from ww w .  j  a va 2  s. 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 .ja  va  2s  .c om*/
}

From source file:org.beangle.emsapp.portal.action.LoginAction.java

public String index() {
    RSAPublicKey publicKey = RSAUtil.getDefaultPublicKey();
    put("modulus", new String(Hex.encode(publicKey.getModulus().toByteArray())));
    put("exponent", new String(Hex.encode(publicKey.getPublicExponent().toByteArray())));
    String backurl = get("backurl");
    if (StringUtils.isEmpty(backurl)) {
        backurl = (String) getSession().get("backurl");
    }//from w ww.j  a va  2  s  .co m
    if (StringUtils.isNotBlank(backurl)) {
        if (backurl.indexOf("!save") > 0 || backurl.indexOf("method=save") > 0) {
            backurl = null;
        }
    }
    put("backurl", backurl);
    if (AuthenticationUtils.hasValidAuthentication()) {
        // return "home";
    } else {
        if (!shouldLogin()) {
            notFailEnough();
            return "failure";
        }
        String errorMsg = doLogin();
        if (StringUtils.isNotEmpty(errorMsg)) {
            addActionError(getText(errorMsg));
            increaseLoginFailure();
            return "failure";
        }
        clearLoginFailure();
    }
    if (StringUtils.isNotEmpty(backurl) && backurl.indexOf("logout.action") < 0) {
        try {
            ServletActionContext.getResponse().sendRedirect(backurl);
        } catch (IOException e) {
        }
        return null;
    }
    return "home";
}

From source file:net.groupbuy.controller.shop.CommonController.java

/**
 * /*from   w w  w . j  a v a2s.c  o  m*/
 */
@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 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;
        }/*  w w w  .j  a  v a 2  s  .co  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:uk.org.ukfederation.mda.validate.X509RSAOpenSSLBlacklistValidator.java

/** {@inheritDoc} */
@Override/*from  w w w. j av  a2s  .com*/
public void validate(@Nonnull final X509Certificate cert, @Nonnull final Item<?> item,
        @Nonnull final String stageId) throws StageProcessingException {
    ComponentSupport.ifNotInitializedThrowUninitializedComponentException(this);
    final PublicKey key = cert.getPublicKey();
    if ("RSA".equals(key.getAlgorithm())) {
        final RSAPublicKey rsaKey = (RSAPublicKey) key;
        final BigInteger modulus = rsaKey.getModulus();
        if (keySize == 0 || keySize == modulus.bitLength()) {
            final String value = openSSLDigest(modulus);
            if (blacklistedValues.contains(value)) {
                addError("RSA modulus included in key blacklist (" + value + ")", item, stageId);
            }
        }
    }
}

From source file:com.puyuntech.flowerToHome.controller.admin.LoginController.java

/**
 * //  w w  w .jav a2 s  . c  o  m
 * ?. author:  date: 2015-9-21 ?1:29:55
 * 
 * @param request
 *            ??
 * @param model
 *            ?
 * @return ??
 */
@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:/";
    }

    /**
     * ???
     */
    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("com.puyuntech.ycmall.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("com.puyuntech.ycmall.exception.IllegalLicenseException")) {
            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", request.getSession().getId());
    model.addAttribute("failureMessage", failureMessage);
    return "/admin/login/index";
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * Gets the key length of supported keys
 * //from  w ww  .ja va 2s. co  m
 * @param pk
 *            PublicKey used to derive the keysize
 * @return -1 if key is unsupported, otherwise a number >= 0. 0 usually means the length can not be calculated, for example if the key is an EC
 *         key and the "implicitlyCA" encoding is used.
 */
public static int getKeyLength(final PublicKey pk) {
    int len = -1;
    if (pk instanceof RSAPublicKey) {
        final RSAPublicKey rsapub = (RSAPublicKey) pk;
        len = rsapub.getModulus().bitLength();
    } else if (pk instanceof JCEECPublicKey) {
        final JCEECPublicKey ecpriv = (JCEECPublicKey) pk;
        final org.bouncycastle.jce.spec.ECParameterSpec spec = ecpriv.getParameters();
        if (spec != null) {
            len = spec.getN().bitLength();
        } else {
            // We support the key, but we don't know the key length
            len = 0;
        }
    } else if (pk instanceof BCECPublicKey) {
        final BCECPublicKey ecpriv = (BCECPublicKey) pk;
        final org.bouncycastle.jce.spec.ECParameterSpec spec = ecpriv.getParameters();
        if (spec != null) {
            len = spec.getN().bitLength();
        } else {
            // We support the key, but we don't know the key length
            len = 0;
        }
    } else if (pk instanceof ECPublicKey) {
        final ECPublicKey ecpriv = (ECPublicKey) pk;
        final java.security.spec.ECParameterSpec spec = ecpriv.getParams();
        if (spec != null) {
            len = spec.getOrder().bitLength(); // does this really return something we expect?
        } else {
            // We support the key, but we don't know the key length
            len = 0;
        }
    } else if (pk instanceof DSAPublicKey) {
        final DSAPublicKey dsapub = (DSAPublicKey) pk;
        if (dsapub.getParams() != null) {
            len = dsapub.getParams().getP().bitLength();
        } else {
            len = dsapub.getY().bitLength();
        }
    }
    return len;
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * Print parameters of public part of a key.
 * /*from   ww w .  ja va  2  s.c om*/
 * @param publK
 *            the key
 * @param ps
 *            stream to print to.
 */
public static void printPublicKeyInfo(final PublicKey publK, final PrintStream ps) {
    if (publK instanceof RSAPublicKey) {
        ps.println("RSA key:");
        final RSAPublicKey rsa = (RSAPublicKey) publK;
        ps.println("  modulus: " + rsa.getModulus().toString(16));
        ps.println("  public exponent: " + rsa.getPublicExponent().toString(16));
        return;
    }
    if (publK instanceof ECPublicKey) {
        ps.println("Elliptic curve key:");
        final ECPublicKey ec = (ECPublicKey) publK;
        ps.println("  the affine x-coordinate: " + ec.getW().getAffineX().toString(16));
        ps.println("  the affine y-coordinate: " + ec.getW().getAffineY().toString(16));
        return;
    }
    if (publK instanceof DHPublicKey) {
        ps.println("DH key:");
        final DHPublicKey dh = (DHPublicKey) publK;
        ps.println("  the public value y: " + dh.getY().toString(16));
        return;
    }
    if (publK instanceof DSAPublicKey) {
        ps.println("DSA key:");
        final DSAPublicKey dsa = (DSAPublicKey) publK;
        ps.println("  the public value y: " + dsa.getY().toString(16));
        return;
    }
}

From source file:sernet.verinice.encryption.test.CryptoTest.java

X509Certificate generateCertificate(String dn, KeyPair pair, int days)
        throws GeneralSecurityException, IOException {
    PublicKey publicKey = pair.getPublic();
    PrivateKey privateKey = pair.getPrivate();
    if (publicKey instanceof RSAPublicKey) {
        RSAPublicKey rsaPk = (RSAPublicKey) publicKey;
        RSAPublicKeySpec rsaPkSpec = new RSAPublicKeySpec(rsaPk.getModulus(), rsaPk.getPublicExponent());
        try {//from  w  w w  . j  av a2 s . c o m
            publicKey = KeyFactory.getInstance("RSA").generatePublic(rsaPkSpec);
        } catch (InvalidKeySpecException e) {
            publicKey = pair.getPublic();
        }
    }
    if (privateKey instanceof RSAPrivateKey) {
        RSAPrivateKey rsaPk = (RSAPrivateKey) privateKey;
        RSAPrivateKeySpec rsaPkSpec = new RSAPrivateKeySpec(rsaPk.getModulus(), rsaPk.getPrivateExponent());
        try {
            privateKey = KeyFactory.getInstance("RSA").generatePrivate(rsaPkSpec);
        } catch (InvalidKeySpecException e) {
            privateKey = pair.getPrivate();
        }
    }

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    String commonName = "CN=" + dn + ", OU=None, O=None L=None, C=None";
    X500Principal dnName = new X500Principal(commonName);
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(dnName);
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    Calendar cal = Calendar.getInstance();
    certGen.setNotBefore(cal.getTime());
    cal.add(Calendar.YEAR, 5);
    certGen.setNotAfter(cal.getTime());
    certGen.setSubjectDN(dnName);
    certGen.setPublicKey(publicKey);
    certGen.setSignatureAlgorithm("MD5WithRSA");
    return certGen.generate(privateKey, BouncyCastleProvider.PROVIDER_NAME);
}