Java非对称加密(三)-代码及说明

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

} X509EncodedKeySpec keySpec = new X509EncodedKeySpec (publicKeyByte s); return keyFactory.generatePublic (keySpec); } catch (Exception e) { throw new RuntimeException ("load publicKey fail. " + e.getMessage ()); } } /** * 加载公钥(base64) * * @param publicKeyBase64 * 秘钥为BASE64编码 * @param keyAlgorithm * 如:RSA * @param providerName * 可以为空,如:BC * @return */ public static PublicKey loadPublicKey (String publicKeyBase64, String keyA lgorithm, String providerName) { byte [] publicKeyBytes = Encodes.decodeBase64(publicKeyBase64); return loadPublicKey (publicKeyBytes, keyAlgorithm, providerName); } /** * 加载公钥(⽂文件pem) * * @param publicKeyFile * 公钥秘钥⽂文件,内容为BASE64编码 * @param keyAlgorithm * 如:RSA * @param providerName * 可以为空,如:BC * @return */ public static PublicKey loadPublicKey (File publicKeyFile, String keyAlgor ithm, String providerName) { byte [] publicKeyBytes = null; try { publicKeyBytes = Encodes.decodeBase64(FileUtils.readFileToString (publicKeyFile));

} catch (Exception e) {

throw new RuntimeException ("加载公钥⽂文件内容失败:" + e.getMessage ())

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

私钥的加载默认同公钥,这⾥里里不不在贴代码,从公钥稍微调整下就OK

throw new RuntimeException ("加载公钥⽂文件内容失败:" + e.getMessage ()); } finally { IOUtils.closeQuietly (in); } } /** * 从keystore 加载公钥 * * @param keystoreUri * @param keystoreType * @param keystorePassword * @return */ public static PublicKey loadPublicKeyFromKeyStore (String keystoreUri, Str ing keystoreType, String keystorePassword) { InputStream in = null; try { KeyStore keyStore = KeyStore.getInstance (keystoreType); Resource resource = new DefaultResourceLoader ().getResource (keyst oreUri); in = resource.getInputStream (); keyStore.load (in, keystorePassword.toCharArray ()); Enumeration enumas = keyStore.aliases (); String keyAlias = null; if (enumas.hasMoreElements ()) { keyAlias = enumas.nextElement (); } return keyStore.getCertificate (keyAlias).getPublicKey ();

} catch (Exception e) {

throw new RuntimeException ("通过keystore 加载证书公钥失败:" + e.getMe ssage ());

} finally {

IOUtils.closeQuietly (in);

}

}

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71私钥的加载

加密和解密

相关文档
最新文档