List of usage examples for java.security.interfaces RSAPublicKey getPublicExponent
public BigInteger getPublicExponent();
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 {// w w w . ja va 2 s . c om 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); }
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 w w. j a va 2 s . c o 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 a 2s .c om */ @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.cesecore.keys.util.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. * /* w ww. ja v a 2 s . co m*/ * @param pk * PublicKey used to derive the AlgorithmParameterSpec * @return null if key is unsupported or pk is null, otherwise a AlgorithmParameterSpec. */ 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:org.openbaton.nfvo.core.api.KeyManagement.java
private String encodePublicKey(PublicKey publicKey, String user) throws IOException { String publicKeyEncoded;/*from w w w . j ava2s . c om*/ RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes().length); dos.write("ssh-rsa".getBytes()); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); publicKeyEncoded = new String(encodeBase64(byteOs.toByteArray())); return "ssh-rsa " + publicKeyEncoded + " " + user; }
From source file:org.cesecore.keys.util.KeyTools.java
/** * Print parameters of public part of a key. * /*from w ww. j av a2 s.c o m*/ * @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:com.puyuntech.flowerToHome.controller.admin.LoginController.java
/** * /*from ww w. j a va 2 s. co 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:test.be.fedict.eid.applet.RSATest.java
@Test public void testManualEncryption() throws Exception { while (true) { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); SecureRandom random = new SecureRandom(); int keySize = 128; keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F0), random); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey; LOG.debug("private key modulus: " + rsaPrivateKey.getModulus()); RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; LOG.debug("public key modulus: " + rsaPublicKey.getModulus()); LOG.debug("public key exponent: " + rsaPublicKey.getPublicExponent()); LOG.debug("modulus size: " + rsaPublicKey.getModulus().toByteArray().length); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); int dataSize = keySize / 8 - 11; byte[] data1 = new byte[dataSize]; for (int i = 0; i < data1.length; i++) { data1[i] = 0x00;/*from w w w. j a v a 2s . c o m*/ } byte[] data2 = new byte[dataSize]; for (int i = 0; i < data2.length; i++) { data2[i] = 0x00; } data2[data2.length - 1] = 0x07; byte[] signatureValue1 = cipher.doFinal(data1); LOG.debug("signature size: " + signatureValue1.length); cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); byte[] signatureValue2 = cipher.doFinal(data2); BigInteger sigBigInt1 = new BigInteger(signatureValue1); BigInteger sigBigInt2 = new BigInteger(signatureValue2); BigInteger msgBigInt1 = sigBigInt1.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus()); BigInteger msgBigInt2 = sigBigInt2.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus()); LOG.debug("msg big int: " + msgBigInt1); byte[] msgBytes1 = msgBigInt1.toByteArray(); LOG.debug("original message size: " + msgBytes1.length); LOG.debug("original message1: " + new String(Hex.encodeHex(msgBytes1))); LOG.debug("original message2: " + new String(Hex.encodeHex(msgBigInt2.toByteArray()))); LOG.debug("msg1 prime: " + msgBigInt1.isProbablePrime(100)); LOG.debug("msg2 prime: " + msgBigInt2.isProbablePrime(100)); // BigInteger.pow offers a very naive implementation LOG.debug("calculating s1^e..."); BigInteger s1_e = sigBigInt1.pow(rsaPublicKey.getPublicExponent().intValue()); LOG.debug("s1^e: " + s1_e); LOG.debug("calculating s2^e..."); BigInteger s2_e = sigBigInt2.pow(rsaPublicKey.getPublicExponent().intValue()); LOG.debug("s2^e: " + s2_e); LOG.debug("calculating GCD..."); LOG.debug("msg1: " + msgBigInt1); LOG.debug("msg2: " + msgBigInt2); BigInteger a = s1_e.subtract(msgBigInt1); BigInteger b = s2_e.subtract(msgBigInt2); LOG.debug("a: " + a); LOG.debug("b: " + b); BigInteger candidateModulus = a.gcd(b); LOG.debug("candidate modulus: " + candidateModulus); LOG.debug("candidate modulus size: " + candidateModulus.toByteArray().length); BigInteger s_e = s1_e.multiply(s2_e); BigInteger m = msgBigInt1.multiply(msgBigInt2); while (false == rsaPublicKey.getModulus().equals(candidateModulus)) { LOG.error("incorrect candidate modulus"); LOG.debug("modulus | candidate modulus: " + candidateModulus.remainder(rsaPublicKey.getModulus()).equals(BigInteger.ZERO)); s_e = s_e.multiply(s1_e); m = m.multiply(msgBigInt1); BigInteger n1 = s_e.subtract(m).gcd(a); BigInteger n2 = s_e.subtract(m).gcd(b); candidateModulus = n1.gcd(n2); // try / 2 LOG.debug("new modulus: " + n1); LOG.debug("new modulus: " + n2); LOG.debug("candidate modulus: " + candidateModulus); LOG.debug("actual mod: " + rsaPublicKey.getModulus()); } } }
From source file:org.openbaton.nfvo.core.api.KeyManagement.java
private String encodePublicKey(RSAPublicKey key, String keyname) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); /* encode the "ssh-rsa" string */ byte[] sshrsa = new byte[] { 0, 0, 0, 7, 's', 's', 'h', '-', 'r', 's', 'a' }; out.write(sshrsa);/*from w w w. j a v a 2s.co m*/ /* Encode the public exponent */ BigInteger e = key.getPublicExponent(); byte[] data = e.toByteArray(); encodeUInt32(data.length, out); out.write(data); /* Encode the modulus */ BigInteger m = key.getModulus(); data = m.toByteArray(); encodeUInt32(data.length, out); out.write(data); return "ssh-rsa " + Base64.encodeBase64String(out.toByteArray()) + " " + keyname; }
From source file:com.hyeb.back.login.LoginController.java
/** * /*from ww w . ja v a 2 s . c o m*/ */ @RequestMapping(value = "/login") public String login(ModelMap model, RedirectAttributes redirectAttributes, HttpServletRequest request) { /** "?"??? */ final String PRIVATE_KEY_ATTRIBUTE_NAME = "privateKey"; //HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); Setting setting = SettingUtils.get(); KeyPair keyPair = RSAUtils.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); request.getSession().setAttribute(PRIVATE_KEY_ATTRIBUTE_NAME, privateKey); String modulus = Base64.encodeBase64String(publicKey.getModulus().toByteArray());//N String exponent = Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray());//e String captchaId = UUID.randomUUID().toString(); boolean isBackCaptcha = ArrayUtils.contains(setting.getCaptchaTypes(), CaptchaType.adminLogin); model.addAttribute("modulus", modulus); model.addAttribute("exponent", exponent); model.addAttribute("captchaId", captchaId); model.addAttribute("isBackCaptcha", isBackCaptcha); String messageStr = null; String loginFailure = (String) request .getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME); if (loginFailure != null) { if (loginFailure.equals("org.apache.shiro.authc.pam.UnsupportedTokenException")) {//?? messageStr = "admin.captcha.invalid"; } else if (loginFailure.equals("org.apache.shiro.authc.UnknownAccountException")) {// messageStr = "admin.login.unknownAccount"; } else if (loginFailure.equals("org.apache.shiro.authc.DisabledAccountException")) {//? messageStr = "admin.login.disabledAccount";// } else if (loginFailure.equals("org.apache.shiro.authc.LockedAccountException")) {//? messageStr = "admin.login.lockedAccount"; } else if (loginFailure.equals("org.apache.shiro.authc.IncorrectCredentialsException")) {//?? if (ArrayUtils.contains(setting.getAccountLockTypes(), AccountLockType.admin)) { messageStr = "admin.login.accountLockCount";//?{0}??? } else { messageStr = "admin.login.incorrectCredentials";//??? } } else if (loginFailure.equals("org.apache.shiro.authc.AuthenticationException")) {// messageStr = "admin.login.authentication";//?? } if (messageStr != null) { Message message = Message.warn(messageStr); addFlashMessage(redirectAttributes, message); } } Subject subject = SecurityUtils.getSubject(); if (subject.isAuthenticated()) { return "redirect:/back/main/main"; } else { return "/back/login/login"; } }